ParseExprCXX.cpp revision 2edf0a2520313cde900799b1eb9bd11c9c776afe
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? 39bool Parser::areTokensAdjacent(const Token &First, const 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(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 = tryParseExceptionSpecification(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 TypeResult TrailingReturnType; 796 if (Tok.is(tok::arrow)) { 797 SourceRange Range; 798 TrailingReturnType = ParseTrailingReturnType(Range); 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 TypeResult TrailingReturnType; 842 if (Tok.is(tok::arrow)) { 843 SourceRange Range; 844 TrailingReturnType = ParseTrailingReturnType(Range); 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 ParseScope BodyScope(this, ScopeFlags); 876 877 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope()); 878 879 // Parse compound-statement. 880 if (!Tok.is(tok::l_brace)) { 881 Diag(Tok, diag::err_expected_lambda_body); 882 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope()); 883 return ExprError(); 884 } 885 886 StmtResult Stmt(ParseCompoundStatementBody()); 887 BodyScope.Exit(); 888 889 if (!Stmt.isInvalid()) 890 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScope()); 891 892 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope()); 893 return ExprError(); 894} 895 896/// ParseCXXCasts - This handles the various ways to cast expressions to another 897/// type. 898/// 899/// postfix-expression: [C++ 5.2p1] 900/// 'dynamic_cast' '<' type-name '>' '(' expression ')' 901/// 'static_cast' '<' type-name '>' '(' expression ')' 902/// 'reinterpret_cast' '<' type-name '>' '(' expression ')' 903/// 'const_cast' '<' type-name '>' '(' expression ')' 904/// 905ExprResult Parser::ParseCXXCasts() { 906 tok::TokenKind Kind = Tok.getKind(); 907 const char *CastName = 0; // For error messages 908 909 switch (Kind) { 910 default: llvm_unreachable("Unknown C++ cast!"); 911 case tok::kw_const_cast: CastName = "const_cast"; break; 912 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break; 913 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break; 914 case tok::kw_static_cast: CastName = "static_cast"; break; 915 } 916 917 SourceLocation OpLoc = ConsumeToken(); 918 SourceLocation LAngleBracketLoc = Tok.getLocation(); 919 920 // Check for "<::" which is parsed as "[:". If found, fix token stream, 921 // diagnose error, suggest fix, and recover parsing. 922 Token Next = NextToken(); 923 if (Tok.is(tok::l_square) && Tok.getLength() == 2 && Next.is(tok::colon) && 924 areTokensAdjacent(Tok, Next)) 925 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true); 926 927 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName)) 928 return ExprError(); 929 930 // Parse the common declaration-specifiers piece. 931 DeclSpec DS(AttrFactory); 932 ParseSpecifierQualifierList(DS); 933 934 // Parse the abstract-declarator, if present. 935 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 936 ParseDeclarator(DeclaratorInfo); 937 938 SourceLocation RAngleBracketLoc = Tok.getLocation(); 939 940 if (ExpectAndConsume(tok::greater, diag::err_expected_greater)) 941 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<"); 942 943 SourceLocation LParenLoc, RParenLoc; 944 BalancedDelimiterTracker T(*this, tok::l_paren); 945 946 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName)) 947 return ExprError(); 948 949 ExprResult Result = ParseExpression(); 950 951 // Match the ')'. 952 T.consumeClose(); 953 954 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType()) 955 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, 956 LAngleBracketLoc, DeclaratorInfo, 957 RAngleBracketLoc, 958 T.getOpenLocation(), Result.take(), 959 T.getCloseLocation()); 960 961 return move(Result); 962} 963 964/// ParseCXXTypeid - This handles the C++ typeid expression. 965/// 966/// postfix-expression: [C++ 5.2p1] 967/// 'typeid' '(' expression ')' 968/// 'typeid' '(' type-id ')' 969/// 970ExprResult Parser::ParseCXXTypeid() { 971 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!"); 972 973 SourceLocation OpLoc = ConsumeToken(); 974 SourceLocation LParenLoc, RParenLoc; 975 BalancedDelimiterTracker T(*this, tok::l_paren); 976 977 // typeid expressions are always parenthesized. 978 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid")) 979 return ExprError(); 980 LParenLoc = T.getOpenLocation(); 981 982 ExprResult Result; 983 984 if (isTypeIdInParens()) { 985 TypeResult Ty = ParseTypeName(); 986 987 // Match the ')'. 988 T.consumeClose(); 989 RParenLoc = T.getCloseLocation(); 990 if (Ty.isInvalid() || RParenLoc.isInvalid()) 991 return ExprError(); 992 993 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true, 994 Ty.get().getAsOpaquePtr(), RParenLoc); 995 } else { 996 // C++0x [expr.typeid]p3: 997 // When typeid is applied to an expression other than an lvalue of a 998 // polymorphic class type [...] The expression is an unevaluated 999 // operand (Clause 5). 1000 // 1001 // Note that we can't tell whether the expression is an lvalue of a 1002 // polymorphic class type until after we've parsed the expression; we 1003 // speculatively assume the subexpression is unevaluated, and fix it up 1004 // later. 1005 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 1006 Result = ParseExpression(); 1007 1008 // Match the ')'. 1009 if (Result.isInvalid()) 1010 SkipUntil(tok::r_paren); 1011 else { 1012 T.consumeClose(); 1013 RParenLoc = T.getCloseLocation(); 1014 if (RParenLoc.isInvalid()) 1015 return ExprError(); 1016 1017 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false, 1018 Result.release(), RParenLoc); 1019 } 1020 } 1021 1022 return move(Result); 1023} 1024 1025/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression. 1026/// 1027/// '__uuidof' '(' expression ')' 1028/// '__uuidof' '(' type-id ')' 1029/// 1030ExprResult Parser::ParseCXXUuidof() { 1031 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!"); 1032 1033 SourceLocation OpLoc = ConsumeToken(); 1034 BalancedDelimiterTracker T(*this, tok::l_paren); 1035 1036 // __uuidof expressions are always parenthesized. 1037 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof")) 1038 return ExprError(); 1039 1040 ExprResult Result; 1041 1042 if (isTypeIdInParens()) { 1043 TypeResult Ty = ParseTypeName(); 1044 1045 // Match the ')'. 1046 T.consumeClose(); 1047 1048 if (Ty.isInvalid()) 1049 return ExprError(); 1050 1051 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true, 1052 Ty.get().getAsOpaquePtr(), 1053 T.getCloseLocation()); 1054 } else { 1055 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 1056 Result = ParseExpression(); 1057 1058 // Match the ')'. 1059 if (Result.isInvalid()) 1060 SkipUntil(tok::r_paren); 1061 else { 1062 T.consumeClose(); 1063 1064 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), 1065 /*isType=*/false, 1066 Result.release(), T.getCloseLocation()); 1067 } 1068 } 1069 1070 return move(Result); 1071} 1072 1073/// \brief Parse a C++ pseudo-destructor expression after the base, 1074/// . or -> operator, and nested-name-specifier have already been 1075/// parsed. 1076/// 1077/// postfix-expression: [C++ 5.2] 1078/// postfix-expression . pseudo-destructor-name 1079/// postfix-expression -> pseudo-destructor-name 1080/// 1081/// pseudo-destructor-name: 1082/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name 1083/// ::[opt] nested-name-specifier template simple-template-id :: 1084/// ~type-name 1085/// ::[opt] nested-name-specifier[opt] ~type-name 1086/// 1087ExprResult 1088Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc, 1089 tok::TokenKind OpKind, 1090 CXXScopeSpec &SS, 1091 ParsedType ObjectType) { 1092 // We're parsing either a pseudo-destructor-name or a dependent 1093 // member access that has the same form as a 1094 // pseudo-destructor-name. We parse both in the same way and let 1095 // the action model sort them out. 1096 // 1097 // Note that the ::[opt] nested-name-specifier[opt] has already 1098 // been parsed, and if there was a simple-template-id, it has 1099 // been coalesced into a template-id annotation token. 1100 UnqualifiedId FirstTypeName; 1101 SourceLocation CCLoc; 1102 if (Tok.is(tok::identifier)) { 1103 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 1104 ConsumeToken(); 1105 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"); 1106 CCLoc = ConsumeToken(); 1107 } else if (Tok.is(tok::annot_template_id)) { 1108 // FIXME: retrieve TemplateKWLoc from template-id annotation and 1109 // store it in the pseudo-dtor node (to be used when instantiating it). 1110 FirstTypeName.setTemplateId( 1111 (TemplateIdAnnotation *)Tok.getAnnotationValue()); 1112 ConsumeToken(); 1113 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"); 1114 CCLoc = ConsumeToken(); 1115 } else { 1116 FirstTypeName.setIdentifier(0, SourceLocation()); 1117 } 1118 1119 // Parse the tilde. 1120 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail"); 1121 SourceLocation TildeLoc = ConsumeToken(); 1122 1123 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) { 1124 DeclSpec DS(AttrFactory); 1125 ParseDecltypeSpecifier(DS); 1126 if (DS.getTypeSpecType() == TST_error) 1127 return ExprError(); 1128 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, 1129 OpKind, TildeLoc, DS, 1130 Tok.is(tok::l_paren)); 1131 } 1132 1133 if (!Tok.is(tok::identifier)) { 1134 Diag(Tok, diag::err_destructor_tilde_identifier); 1135 return ExprError(); 1136 } 1137 1138 // Parse the second type. 1139 UnqualifiedId SecondTypeName; 1140 IdentifierInfo *Name = Tok.getIdentifierInfo(); 1141 SourceLocation NameLoc = ConsumeToken(); 1142 SecondTypeName.setIdentifier(Name, NameLoc); 1143 1144 // If there is a '<', the second type name is a template-id. Parse 1145 // it as such. 1146 if (Tok.is(tok::less) && 1147 ParseUnqualifiedIdTemplateId(SS, SourceLocation(), 1148 Name, NameLoc, 1149 false, ObjectType, SecondTypeName, 1150 /*AssumeTemplateName=*/true)) 1151 return ExprError(); 1152 1153 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, 1154 OpLoc, OpKind, 1155 SS, FirstTypeName, CCLoc, 1156 TildeLoc, SecondTypeName, 1157 Tok.is(tok::l_paren)); 1158} 1159 1160/// ParseCXXBoolLiteral - This handles the C++ Boolean literals. 1161/// 1162/// boolean-literal: [C++ 2.13.5] 1163/// 'true' 1164/// 'false' 1165ExprResult Parser::ParseCXXBoolLiteral() { 1166 tok::TokenKind Kind = Tok.getKind(); 1167 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind); 1168} 1169 1170/// ParseThrowExpression - This handles the C++ throw expression. 1171/// 1172/// throw-expression: [C++ 15] 1173/// 'throw' assignment-expression[opt] 1174ExprResult Parser::ParseThrowExpression() { 1175 assert(Tok.is(tok::kw_throw) && "Not throw!"); 1176 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token. 1177 1178 // If the current token isn't the start of an assignment-expression, 1179 // then the expression is not present. This handles things like: 1180 // "C ? throw : (void)42", which is crazy but legal. 1181 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common. 1182 case tok::semi: 1183 case tok::r_paren: 1184 case tok::r_square: 1185 case tok::r_brace: 1186 case tok::colon: 1187 case tok::comma: 1188 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0); 1189 1190 default: 1191 ExprResult Expr(ParseAssignmentExpression()); 1192 if (Expr.isInvalid()) return move(Expr); 1193 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take()); 1194 } 1195} 1196 1197/// ParseCXXThis - This handles the C++ 'this' pointer. 1198/// 1199/// C++ 9.3.2: In the body of a non-static member function, the keyword this is 1200/// a non-lvalue expression whose value is the address of the object for which 1201/// the function is called. 1202ExprResult Parser::ParseCXXThis() { 1203 assert(Tok.is(tok::kw_this) && "Not 'this'!"); 1204 SourceLocation ThisLoc = ConsumeToken(); 1205 return Actions.ActOnCXXThis(ThisLoc); 1206} 1207 1208/// ParseCXXTypeConstructExpression - Parse construction of a specified type. 1209/// Can be interpreted either as function-style casting ("int(x)") 1210/// or class type construction ("ClassType(x,y,z)") 1211/// or creation of a value-initialized type ("int()"). 1212/// See [C++ 5.2.3]. 1213/// 1214/// postfix-expression: [C++ 5.2p1] 1215/// simple-type-specifier '(' expression-list[opt] ')' 1216/// [C++0x] simple-type-specifier braced-init-list 1217/// typename-specifier '(' expression-list[opt] ')' 1218/// [C++0x] typename-specifier braced-init-list 1219/// 1220ExprResult 1221Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) { 1222 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 1223 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get(); 1224 1225 assert((Tok.is(tok::l_paren) || 1226 (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace))) 1227 && "Expected '(' or '{'!"); 1228 1229 if (Tok.is(tok::l_brace)) { 1230 ExprResult Init = ParseBraceInitializer(); 1231 if (Init.isInvalid()) 1232 return Init; 1233 Expr *InitList = Init.take(); 1234 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(), 1235 MultiExprArg(&InitList, 1), 1236 SourceLocation()); 1237 } else { 1238 BalancedDelimiterTracker T(*this, tok::l_paren); 1239 T.consumeOpen(); 1240 1241 ExprVector Exprs(Actions); 1242 CommaLocsTy CommaLocs; 1243 1244 if (Tok.isNot(tok::r_paren)) { 1245 if (ParseExpressionList(Exprs, CommaLocs)) { 1246 SkipUntil(tok::r_paren); 1247 return ExprError(); 1248 } 1249 } 1250 1251 // Match the ')'. 1252 T.consumeClose(); 1253 1254 // TypeRep could be null, if it references an invalid typedef. 1255 if (!TypeRep) 1256 return ExprError(); 1257 1258 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& 1259 "Unexpected number of commas!"); 1260 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(), 1261 move_arg(Exprs), 1262 T.getCloseLocation()); 1263 } 1264} 1265 1266/// ParseCXXCondition - if/switch/while condition expression. 1267/// 1268/// condition: 1269/// expression 1270/// type-specifier-seq declarator '=' assignment-expression 1271/// [C++11] type-specifier-seq declarator '=' initializer-clause 1272/// [C++11] type-specifier-seq declarator braced-init-list 1273/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] 1274/// '=' assignment-expression 1275/// 1276/// \param ExprResult if the condition was parsed as an expression, the 1277/// parsed expression. 1278/// 1279/// \param DeclResult if the condition was parsed as a declaration, the 1280/// parsed declaration. 1281/// 1282/// \param Loc The location of the start of the statement that requires this 1283/// condition, e.g., the "for" in a for loop. 1284/// 1285/// \param ConvertToBoolean Whether the condition expression should be 1286/// converted to a boolean value. 1287/// 1288/// \returns true if there was a parsing, false otherwise. 1289bool Parser::ParseCXXCondition(ExprResult &ExprOut, 1290 Decl *&DeclOut, 1291 SourceLocation Loc, 1292 bool ConvertToBoolean) { 1293 if (Tok.is(tok::code_completion)) { 1294 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition); 1295 cutOffParsing(); 1296 return true; 1297 } 1298 1299 ParsedAttributesWithRange attrs(AttrFactory); 1300 MaybeParseCXX0XAttributes(attrs); 1301 1302 if (!isCXXConditionDeclaration()) { 1303 ProhibitAttributes(attrs); 1304 1305 // Parse the expression. 1306 ExprOut = ParseExpression(); // expression 1307 DeclOut = 0; 1308 if (ExprOut.isInvalid()) 1309 return true; 1310 1311 // If required, convert to a boolean value. 1312 if (ConvertToBoolean) 1313 ExprOut 1314 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get()); 1315 return ExprOut.isInvalid(); 1316 } 1317 1318 // type-specifier-seq 1319 DeclSpec DS(AttrFactory); 1320 ParseSpecifierQualifierList(DS); 1321 1322 // declarator 1323 Declarator DeclaratorInfo(DS, Declarator::ConditionContext); 1324 ParseDeclarator(DeclaratorInfo); 1325 1326 // simple-asm-expr[opt] 1327 if (Tok.is(tok::kw_asm)) { 1328 SourceLocation Loc; 1329 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 1330 if (AsmLabel.isInvalid()) { 1331 SkipUntil(tok::semi); 1332 return true; 1333 } 1334 DeclaratorInfo.setAsmLabel(AsmLabel.release()); 1335 DeclaratorInfo.SetRangeEnd(Loc); 1336 } 1337 1338 // If attributes are present, parse them. 1339 MaybeParseGNUAttributes(DeclaratorInfo); 1340 1341 // Type-check the declaration itself. 1342 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), 1343 DeclaratorInfo); 1344 DeclOut = Dcl.get(); 1345 ExprOut = ExprError(); 1346 1347 // '=' assignment-expression 1348 // If a '==' or '+=' is found, suggest a fixit to '='. 1349 bool CopyInitialization = isTokenEqualOrEqualTypo(); 1350 if (CopyInitialization) 1351 ConsumeToken(); 1352 1353 ExprResult InitExpr = ExprError(); 1354 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 1355 Diag(Tok.getLocation(), 1356 diag::warn_cxx98_compat_generalized_initializer_lists); 1357 InitExpr = ParseBraceInitializer(); 1358 } else if (CopyInitialization) { 1359 InitExpr = ParseAssignmentExpression(); 1360 } else if (Tok.is(tok::l_paren)) { 1361 // This was probably an attempt to initialize the variable. 1362 SourceLocation LParen = ConsumeParen(), RParen = LParen; 1363 if (SkipUntil(tok::r_paren, true, /*DontConsume=*/true)) 1364 RParen = ConsumeParen(); 1365 Diag(DeclOut ? DeclOut->getLocation() : LParen, 1366 diag::err_expected_init_in_condition_lparen) 1367 << SourceRange(LParen, RParen); 1368 } else { 1369 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(), 1370 diag::err_expected_init_in_condition); 1371 } 1372 1373 if (!InitExpr.isInvalid()) 1374 Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitialization, 1375 DS.getTypeSpecType() == DeclSpec::TST_auto); 1376 1377 // FIXME: Build a reference to this declaration? Convert it to bool? 1378 // (This is currently handled by Sema). 1379 1380 Actions.FinalizeDeclaration(DeclOut); 1381 1382 return false; 1383} 1384 1385/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. 1386/// This should only be called when the current token is known to be part of 1387/// simple-type-specifier. 1388/// 1389/// simple-type-specifier: 1390/// '::'[opt] nested-name-specifier[opt] type-name 1391/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO] 1392/// char 1393/// wchar_t 1394/// bool 1395/// short 1396/// int 1397/// long 1398/// signed 1399/// unsigned 1400/// float 1401/// double 1402/// void 1403/// [GNU] typeof-specifier 1404/// [C++0x] auto [TODO] 1405/// 1406/// type-name: 1407/// class-name 1408/// enum-name 1409/// typedef-name 1410/// 1411void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { 1412 DS.SetRangeStart(Tok.getLocation()); 1413 const char *PrevSpec; 1414 unsigned DiagID; 1415 SourceLocation Loc = Tok.getLocation(); 1416 1417 switch (Tok.getKind()) { 1418 case tok::identifier: // foo::bar 1419 case tok::coloncolon: // ::foo::bar 1420 llvm_unreachable("Annotation token should already be formed!"); 1421 default: 1422 llvm_unreachable("Not a simple-type-specifier token!"); 1423 1424 // type-name 1425 case tok::annot_typename: { 1426 if (getTypeAnnotation(Tok)) 1427 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, 1428 getTypeAnnotation(Tok)); 1429 else 1430 DS.SetTypeSpecError(); 1431 1432 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1433 ConsumeToken(); 1434 1435 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1436 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1437 // Objective-C interface. If we don't have Objective-C or a '<', this is 1438 // just a normal reference to a typedef name. 1439 if (Tok.is(tok::less) && getLangOpts().ObjC1) 1440 ParseObjCProtocolQualifiers(DS); 1441 1442 DS.Finish(Diags, PP); 1443 return; 1444 } 1445 1446 // builtin types 1447 case tok::kw_short: 1448 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID); 1449 break; 1450 case tok::kw_long: 1451 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID); 1452 break; 1453 case tok::kw___int64: 1454 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID); 1455 break; 1456 case tok::kw_signed: 1457 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID); 1458 break; 1459 case tok::kw_unsigned: 1460 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID); 1461 break; 1462 case tok::kw_void: 1463 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID); 1464 break; 1465 case tok::kw_char: 1466 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID); 1467 break; 1468 case tok::kw_int: 1469 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID); 1470 break; 1471 case tok::kw___int128: 1472 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID); 1473 break; 1474 case tok::kw_half: 1475 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID); 1476 break; 1477 case tok::kw_float: 1478 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID); 1479 break; 1480 case tok::kw_double: 1481 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID); 1482 break; 1483 case tok::kw_wchar_t: 1484 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID); 1485 break; 1486 case tok::kw_char16_t: 1487 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID); 1488 break; 1489 case tok::kw_char32_t: 1490 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID); 1491 break; 1492 case tok::kw_bool: 1493 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID); 1494 break; 1495 case tok::annot_decltype: 1496 case tok::kw_decltype: 1497 DS.SetRangeEnd(ParseDecltypeSpecifier(DS)); 1498 return DS.Finish(Diags, PP); 1499 1500 // GNU typeof support. 1501 case tok::kw_typeof: 1502 ParseTypeofSpecifier(DS); 1503 DS.Finish(Diags, PP); 1504 return; 1505 } 1506 if (Tok.is(tok::annot_typename)) 1507 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1508 else 1509 DS.SetRangeEnd(Tok.getLocation()); 1510 ConsumeToken(); 1511 DS.Finish(Diags, PP); 1512} 1513 1514/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++ 1515/// [dcl.name]), which is a non-empty sequence of type-specifiers, 1516/// e.g., "const short int". Note that the DeclSpec is *not* finished 1517/// by parsing the type-specifier-seq, because these sequences are 1518/// typically followed by some form of declarator. Returns true and 1519/// emits diagnostics if this is not a type-specifier-seq, false 1520/// otherwise. 1521/// 1522/// type-specifier-seq: [C++ 8.1] 1523/// type-specifier type-specifier-seq[opt] 1524/// 1525bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { 1526 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier); 1527 DS.Finish(Diags, PP); 1528 return false; 1529} 1530 1531/// \brief Finish parsing a C++ unqualified-id that is a template-id of 1532/// some form. 1533/// 1534/// This routine is invoked when a '<' is encountered after an identifier or 1535/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine 1536/// whether the unqualified-id is actually a template-id. This routine will 1537/// then parse the template arguments and form the appropriate template-id to 1538/// return to the caller. 1539/// 1540/// \param SS the nested-name-specifier that precedes this template-id, if 1541/// we're actually parsing a qualified-id. 1542/// 1543/// \param Name for constructor and destructor names, this is the actual 1544/// identifier that may be a template-name. 1545/// 1546/// \param NameLoc the location of the class-name in a constructor or 1547/// destructor. 1548/// 1549/// \param EnteringContext whether we're entering the scope of the 1550/// nested-name-specifier. 1551/// 1552/// \param ObjectType if this unqualified-id occurs within a member access 1553/// expression, the type of the base object whose member is being accessed. 1554/// 1555/// \param Id as input, describes the template-name or operator-function-id 1556/// that precedes the '<'. If template arguments were parsed successfully, 1557/// will be updated with the template-id. 1558/// 1559/// \param AssumeTemplateId When true, this routine will assume that the name 1560/// refers to a template without performing name lookup to verify. 1561/// 1562/// \returns true if a parse error occurred, false otherwise. 1563bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, 1564 SourceLocation TemplateKWLoc, 1565 IdentifierInfo *Name, 1566 SourceLocation NameLoc, 1567 bool EnteringContext, 1568 ParsedType ObjectType, 1569 UnqualifiedId &Id, 1570 bool AssumeTemplateId) { 1571 assert((AssumeTemplateId || Tok.is(tok::less)) && 1572 "Expected '<' to finish parsing a template-id"); 1573 1574 TemplateTy Template; 1575 TemplateNameKind TNK = TNK_Non_template; 1576 switch (Id.getKind()) { 1577 case UnqualifiedId::IK_Identifier: 1578 case UnqualifiedId::IK_OperatorFunctionId: 1579 case UnqualifiedId::IK_LiteralOperatorId: 1580 if (AssumeTemplateId) { 1581 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc, 1582 Id, ObjectType, EnteringContext, 1583 Template); 1584 if (TNK == TNK_Non_template) 1585 return true; 1586 } else { 1587 bool MemberOfUnknownSpecialization; 1588 TNK = Actions.isTemplateName(getCurScope(), SS, 1589 TemplateKWLoc.isValid(), Id, 1590 ObjectType, EnteringContext, Template, 1591 MemberOfUnknownSpecialization); 1592 1593 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization && 1594 ObjectType && IsTemplateArgumentList()) { 1595 // We have something like t->getAs<T>(), where getAs is a 1596 // member of an unknown specialization. However, this will only 1597 // parse correctly as a template, so suggest the keyword 'template' 1598 // before 'getAs' and treat this as a dependent template name. 1599 std::string Name; 1600 if (Id.getKind() == UnqualifiedId::IK_Identifier) 1601 Name = Id.Identifier->getName(); 1602 else { 1603 Name = "operator "; 1604 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId) 1605 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator); 1606 else 1607 Name += Id.Identifier->getName(); 1608 } 1609 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword) 1610 << Name 1611 << FixItHint::CreateInsertion(Id.StartLocation, "template "); 1612 TNK = Actions.ActOnDependentTemplateName(getCurScope(), 1613 SS, TemplateKWLoc, Id, 1614 ObjectType, EnteringContext, 1615 Template); 1616 if (TNK == TNK_Non_template) 1617 return true; 1618 } 1619 } 1620 break; 1621 1622 case UnqualifiedId::IK_ConstructorName: { 1623 UnqualifiedId TemplateName; 1624 bool MemberOfUnknownSpecialization; 1625 TemplateName.setIdentifier(Name, NameLoc); 1626 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), 1627 TemplateName, ObjectType, 1628 EnteringContext, Template, 1629 MemberOfUnknownSpecialization); 1630 break; 1631 } 1632 1633 case UnqualifiedId::IK_DestructorName: { 1634 UnqualifiedId TemplateName; 1635 bool MemberOfUnknownSpecialization; 1636 TemplateName.setIdentifier(Name, NameLoc); 1637 if (ObjectType) { 1638 TNK = Actions.ActOnDependentTemplateName(getCurScope(), 1639 SS, TemplateKWLoc, TemplateName, 1640 ObjectType, EnteringContext, 1641 Template); 1642 if (TNK == TNK_Non_template) 1643 return true; 1644 } else { 1645 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), 1646 TemplateName, ObjectType, 1647 EnteringContext, Template, 1648 MemberOfUnknownSpecialization); 1649 1650 if (TNK == TNK_Non_template && !Id.DestructorName.get()) { 1651 Diag(NameLoc, diag::err_destructor_template_id) 1652 << Name << SS.getRange(); 1653 return true; 1654 } 1655 } 1656 break; 1657 } 1658 1659 default: 1660 return false; 1661 } 1662 1663 if (TNK == TNK_Non_template) 1664 return false; 1665 1666 // Parse the enclosed template argument list. 1667 SourceLocation LAngleLoc, RAngleLoc; 1668 TemplateArgList TemplateArgs; 1669 if (Tok.is(tok::less) && 1670 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation, 1671 SS, true, LAngleLoc, 1672 TemplateArgs, 1673 RAngleLoc)) 1674 return true; 1675 1676 if (Id.getKind() == UnqualifiedId::IK_Identifier || 1677 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId || 1678 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) { 1679 // Form a parsed representation of the template-id to be stored in the 1680 // UnqualifiedId. 1681 TemplateIdAnnotation *TemplateId 1682 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds); 1683 1684 if (Id.getKind() == UnqualifiedId::IK_Identifier) { 1685 TemplateId->Name = Id.Identifier; 1686 TemplateId->Operator = OO_None; 1687 TemplateId->TemplateNameLoc = Id.StartLocation; 1688 } else { 1689 TemplateId->Name = 0; 1690 TemplateId->Operator = Id.OperatorFunctionId.Operator; 1691 TemplateId->TemplateNameLoc = Id.StartLocation; 1692 } 1693 1694 TemplateId->SS = SS; 1695 TemplateId->TemplateKWLoc = TemplateKWLoc; 1696 TemplateId->Template = Template; 1697 TemplateId->Kind = TNK; 1698 TemplateId->LAngleLoc = LAngleLoc; 1699 TemplateId->RAngleLoc = RAngleLoc; 1700 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs(); 1701 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); 1702 Arg != ArgEnd; ++Arg) 1703 Args[Arg] = TemplateArgs[Arg]; 1704 1705 Id.setTemplateId(TemplateId); 1706 return false; 1707 } 1708 1709 // Bundle the template arguments together. 1710 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(), 1711 TemplateArgs.size()); 1712 1713 // Constructor and destructor names. 1714 TypeResult Type 1715 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc, 1716 Template, NameLoc, 1717 LAngleLoc, TemplateArgsPtr, RAngleLoc, 1718 /*IsCtorOrDtorName=*/true); 1719 if (Type.isInvalid()) 1720 return true; 1721 1722 if (Id.getKind() == UnqualifiedId::IK_ConstructorName) 1723 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc); 1724 else 1725 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc); 1726 1727 return false; 1728} 1729 1730/// \brief Parse an operator-function-id or conversion-function-id as part 1731/// of a C++ unqualified-id. 1732/// 1733/// This routine is responsible only for parsing the operator-function-id or 1734/// conversion-function-id; it does not handle template arguments in any way. 1735/// 1736/// \code 1737/// operator-function-id: [C++ 13.5] 1738/// 'operator' operator 1739/// 1740/// operator: one of 1741/// new delete new[] delete[] 1742/// + - * / % ^ & | ~ 1743/// ! = < > += -= *= /= %= 1744/// ^= &= |= << >> >>= <<= == != 1745/// <= >= && || ++ -- , ->* -> 1746/// () [] 1747/// 1748/// conversion-function-id: [C++ 12.3.2] 1749/// operator conversion-type-id 1750/// 1751/// conversion-type-id: 1752/// type-specifier-seq conversion-declarator[opt] 1753/// 1754/// conversion-declarator: 1755/// ptr-operator conversion-declarator[opt] 1756/// \endcode 1757/// 1758/// \param The nested-name-specifier that preceded this unqualified-id. If 1759/// non-empty, then we are parsing the unqualified-id of a qualified-id. 1760/// 1761/// \param EnteringContext whether we are entering the scope of the 1762/// nested-name-specifier. 1763/// 1764/// \param ObjectType if this unqualified-id occurs within a member access 1765/// expression, the type of the base object whose member is being accessed. 1766/// 1767/// \param Result on a successful parse, contains the parsed unqualified-id. 1768/// 1769/// \returns true if parsing fails, false otherwise. 1770bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, 1771 ParsedType ObjectType, 1772 UnqualifiedId &Result) { 1773 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); 1774 1775 // Consume the 'operator' keyword. 1776 SourceLocation KeywordLoc = ConsumeToken(); 1777 1778 // Determine what kind of operator name we have. 1779 unsigned SymbolIdx = 0; 1780 SourceLocation SymbolLocations[3]; 1781 OverloadedOperatorKind Op = OO_None; 1782 switch (Tok.getKind()) { 1783 case tok::kw_new: 1784 case tok::kw_delete: { 1785 bool isNew = Tok.getKind() == tok::kw_new; 1786 // Consume the 'new' or 'delete'. 1787 SymbolLocations[SymbolIdx++] = ConsumeToken(); 1788 // Check for array new/delete. 1789 if (Tok.is(tok::l_square) && 1790 (!getLangOpts().CPlusPlus0x || NextToken().isNot(tok::l_square))) { 1791 // Consume the '[' and ']'. 1792 BalancedDelimiterTracker T(*this, tok::l_square); 1793 T.consumeOpen(); 1794 T.consumeClose(); 1795 if (T.getCloseLocation().isInvalid()) 1796 return true; 1797 1798 SymbolLocations[SymbolIdx++] = T.getOpenLocation(); 1799 SymbolLocations[SymbolIdx++] = T.getCloseLocation(); 1800 Op = isNew? OO_Array_New : OO_Array_Delete; 1801 } else { 1802 Op = isNew? OO_New : OO_Delete; 1803 } 1804 break; 1805 } 1806 1807#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 1808 case tok::Token: \ 1809 SymbolLocations[SymbolIdx++] = ConsumeToken(); \ 1810 Op = OO_##Name; \ 1811 break; 1812#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) 1813#include "clang/Basic/OperatorKinds.def" 1814 1815 case tok::l_paren: { 1816 // Consume the '(' and ')'. 1817 BalancedDelimiterTracker T(*this, tok::l_paren); 1818 T.consumeOpen(); 1819 T.consumeClose(); 1820 if (T.getCloseLocation().isInvalid()) 1821 return true; 1822 1823 SymbolLocations[SymbolIdx++] = T.getOpenLocation(); 1824 SymbolLocations[SymbolIdx++] = T.getCloseLocation(); 1825 Op = OO_Call; 1826 break; 1827 } 1828 1829 case tok::l_square: { 1830 // Consume the '[' and ']'. 1831 BalancedDelimiterTracker T(*this, tok::l_square); 1832 T.consumeOpen(); 1833 T.consumeClose(); 1834 if (T.getCloseLocation().isInvalid()) 1835 return true; 1836 1837 SymbolLocations[SymbolIdx++] = T.getOpenLocation(); 1838 SymbolLocations[SymbolIdx++] = T.getCloseLocation(); 1839 Op = OO_Subscript; 1840 break; 1841 } 1842 1843 case tok::code_completion: { 1844 // Code completion for the operator name. 1845 Actions.CodeCompleteOperatorName(getCurScope()); 1846 cutOffParsing(); 1847 // Don't try to parse any further. 1848 return true; 1849 } 1850 1851 default: 1852 break; 1853 } 1854 1855 if (Op != OO_None) { 1856 // We have parsed an operator-function-id. 1857 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations); 1858 return false; 1859 } 1860 1861 // Parse a literal-operator-id. 1862 // 1863 // literal-operator-id: [C++0x 13.5.8] 1864 // operator "" identifier 1865 1866 if (getLangOpts().CPlusPlus0x && isTokenStringLiteral()) { 1867 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator); 1868 1869 SourceLocation DiagLoc; 1870 unsigned DiagId = 0; 1871 1872 // We're past translation phase 6, so perform string literal concatenation 1873 // before checking for "". 1874 llvm::SmallVector<Token, 4> Toks; 1875 llvm::SmallVector<SourceLocation, 4> TokLocs; 1876 while (isTokenStringLiteral()) { 1877 if (!Tok.is(tok::string_literal) && !DiagId) { 1878 DiagLoc = Tok.getLocation(); 1879 DiagId = diag::err_literal_operator_string_prefix; 1880 } 1881 Toks.push_back(Tok); 1882 TokLocs.push_back(ConsumeStringToken()); 1883 } 1884 1885 StringLiteralParser Literal(Toks.data(), Toks.size(), PP); 1886 if (Literal.hadError) 1887 return true; 1888 1889 // Grab the literal operator's suffix, which will be either the next token 1890 // or a ud-suffix from the string literal. 1891 IdentifierInfo *II = 0; 1892 SourceLocation SuffixLoc; 1893 if (!Literal.getUDSuffix().empty()) { 1894 II = &PP.getIdentifierTable().get(Literal.getUDSuffix()); 1895 SuffixLoc = 1896 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()], 1897 Literal.getUDSuffixOffset(), 1898 PP.getSourceManager(), getLangOpts()); 1899 // This form is not permitted by the standard (yet). 1900 DiagLoc = SuffixLoc; 1901 DiagId = diag::err_literal_operator_missing_space; 1902 } else if (Tok.is(tok::identifier)) { 1903 II = Tok.getIdentifierInfo(); 1904 SuffixLoc = ConsumeToken(); 1905 TokLocs.push_back(SuffixLoc); 1906 } else { 1907 Diag(Tok.getLocation(), diag::err_expected_ident); 1908 return true; 1909 } 1910 1911 // The string literal must be empty. 1912 if (!Literal.GetString().empty() || Literal.Pascal) { 1913 DiagLoc = TokLocs.front(); 1914 DiagId = diag::err_literal_operator_string_not_empty; 1915 } 1916 1917 if (DiagId) { 1918 // This isn't a valid literal-operator-id, but we think we know 1919 // what the user meant. Tell them what they should have written. 1920 llvm::SmallString<32> Str; 1921 Str += "\"\" "; 1922 Str += II->getName(); 1923 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement( 1924 SourceRange(TokLocs.front(), TokLocs.back()), Str); 1925 } 1926 1927 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc); 1928 return false; 1929 } 1930 1931 // Parse a conversion-function-id. 1932 // 1933 // conversion-function-id: [C++ 12.3.2] 1934 // operator conversion-type-id 1935 // 1936 // conversion-type-id: 1937 // type-specifier-seq conversion-declarator[opt] 1938 // 1939 // conversion-declarator: 1940 // ptr-operator conversion-declarator[opt] 1941 1942 // Parse the type-specifier-seq. 1943 DeclSpec DS(AttrFactory); 1944 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType? 1945 return true; 1946 1947 // Parse the conversion-declarator, which is merely a sequence of 1948 // ptr-operators. 1949 Declarator D(DS, Declarator::TypeNameContext); 1950 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0); 1951 1952 // Finish up the type. 1953 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D); 1954 if (Ty.isInvalid()) 1955 return true; 1956 1957 // Note that this is a conversion-function-id. 1958 Result.setConversionFunctionId(KeywordLoc, Ty.get(), 1959 D.getSourceRange().getEnd()); 1960 return false; 1961} 1962 1963/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the 1964/// name of an entity. 1965/// 1966/// \code 1967/// unqualified-id: [C++ expr.prim.general] 1968/// identifier 1969/// operator-function-id 1970/// conversion-function-id 1971/// [C++0x] literal-operator-id [TODO] 1972/// ~ class-name 1973/// template-id 1974/// 1975/// \endcode 1976/// 1977/// \param The nested-name-specifier that preceded this unqualified-id. If 1978/// non-empty, then we are parsing the unqualified-id of a qualified-id. 1979/// 1980/// \param EnteringContext whether we are entering the scope of the 1981/// nested-name-specifier. 1982/// 1983/// \param AllowDestructorName whether we allow parsing of a destructor name. 1984/// 1985/// \param AllowConstructorName whether we allow parsing a constructor name. 1986/// 1987/// \param ObjectType if this unqualified-id occurs within a member access 1988/// expression, the type of the base object whose member is being accessed. 1989/// 1990/// \param Result on a successful parse, contains the parsed unqualified-id. 1991/// 1992/// \returns true if parsing fails, false otherwise. 1993bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, 1994 bool AllowDestructorName, 1995 bool AllowConstructorName, 1996 ParsedType ObjectType, 1997 SourceLocation& TemplateKWLoc, 1998 UnqualifiedId &Result) { 1999 2000 // Handle 'A::template B'. This is for template-ids which have not 2001 // already been annotated by ParseOptionalCXXScopeSpecifier(). 2002 bool TemplateSpecified = false; 2003 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) && 2004 (ObjectType || SS.isSet())) { 2005 TemplateSpecified = true; 2006 TemplateKWLoc = ConsumeToken(); 2007 } 2008 2009 // unqualified-id: 2010 // identifier 2011 // template-id (when it hasn't already been annotated) 2012 if (Tok.is(tok::identifier)) { 2013 // Consume the identifier. 2014 IdentifierInfo *Id = Tok.getIdentifierInfo(); 2015 SourceLocation IdLoc = ConsumeToken(); 2016 2017 if (!getLangOpts().CPlusPlus) { 2018 // If we're not in C++, only identifiers matter. Record the 2019 // identifier and return. 2020 Result.setIdentifier(Id, IdLoc); 2021 return false; 2022 } 2023 2024 if (AllowConstructorName && 2025 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) { 2026 // We have parsed a constructor name. 2027 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), 2028 &SS, false, false, 2029 ParsedType(), 2030 /*IsCtorOrDtorName=*/true, 2031 /*NonTrivialTypeSourceInfo=*/true); 2032 Result.setConstructorName(Ty, IdLoc, IdLoc); 2033 } else { 2034 // We have parsed an identifier. 2035 Result.setIdentifier(Id, IdLoc); 2036 } 2037 2038 // If the next token is a '<', we may have a template. 2039 if (TemplateSpecified || Tok.is(tok::less)) 2040 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc, 2041 EnteringContext, ObjectType, 2042 Result, TemplateSpecified); 2043 2044 return false; 2045 } 2046 2047 // unqualified-id: 2048 // template-id (already parsed and annotated) 2049 if (Tok.is(tok::annot_template_id)) { 2050 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 2051 2052 // If the template-name names the current class, then this is a constructor 2053 if (AllowConstructorName && TemplateId->Name && 2054 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 2055 if (SS.isSet()) { 2056 // C++ [class.qual]p2 specifies that a qualified template-name 2057 // is taken as the constructor name where a constructor can be 2058 // declared. Thus, the template arguments are extraneous, so 2059 // complain about them and remove them entirely. 2060 Diag(TemplateId->TemplateNameLoc, 2061 diag::err_out_of_line_constructor_template_id) 2062 << TemplateId->Name 2063 << FixItHint::CreateRemoval( 2064 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)); 2065 ParsedType Ty = Actions.getTypeName(*TemplateId->Name, 2066 TemplateId->TemplateNameLoc, 2067 getCurScope(), 2068 &SS, false, false, 2069 ParsedType(), 2070 /*IsCtorOrDtorName=*/true, 2071 /*NontrivialTypeSourceInfo=*/true); 2072 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc, 2073 TemplateId->RAngleLoc); 2074 ConsumeToken(); 2075 return false; 2076 } 2077 2078 Result.setConstructorTemplateId(TemplateId); 2079 ConsumeToken(); 2080 return false; 2081 } 2082 2083 // We have already parsed a template-id; consume the annotation token as 2084 // our unqualified-id. 2085 Result.setTemplateId(TemplateId); 2086 TemplateKWLoc = TemplateId->TemplateKWLoc; 2087 ConsumeToken(); 2088 return false; 2089 } 2090 2091 // unqualified-id: 2092 // operator-function-id 2093 // conversion-function-id 2094 if (Tok.is(tok::kw_operator)) { 2095 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result)) 2096 return true; 2097 2098 // If we have an operator-function-id or a literal-operator-id and the next 2099 // token is a '<', we may have a 2100 // 2101 // template-id: 2102 // operator-function-id < template-argument-list[opt] > 2103 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId || 2104 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) && 2105 (TemplateSpecified || Tok.is(tok::less))) 2106 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, 2107 0, SourceLocation(), 2108 EnteringContext, ObjectType, 2109 Result, TemplateSpecified); 2110 2111 return false; 2112 } 2113 2114 if (getLangOpts().CPlusPlus && 2115 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) { 2116 // C++ [expr.unary.op]p10: 2117 // There is an ambiguity in the unary-expression ~X(), where X is a 2118 // class-name. The ambiguity is resolved in favor of treating ~ as a 2119 // unary complement rather than treating ~X as referring to a destructor. 2120 2121 // Parse the '~'. 2122 SourceLocation TildeLoc = ConsumeToken(); 2123 2124 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) { 2125 DeclSpec DS(AttrFactory); 2126 SourceLocation EndLoc = ParseDecltypeSpecifier(DS); 2127 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) { 2128 Result.setDestructorName(TildeLoc, Type, EndLoc); 2129 return false; 2130 } 2131 return true; 2132 } 2133 2134 // Parse the class-name. 2135 if (Tok.isNot(tok::identifier)) { 2136 Diag(Tok, diag::err_destructor_tilde_identifier); 2137 return true; 2138 } 2139 2140 // Parse the class-name (or template-name in a simple-template-id). 2141 IdentifierInfo *ClassName = Tok.getIdentifierInfo(); 2142 SourceLocation ClassNameLoc = ConsumeToken(); 2143 2144 if (TemplateSpecified || Tok.is(tok::less)) { 2145 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc); 2146 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, 2147 ClassName, ClassNameLoc, 2148 EnteringContext, ObjectType, 2149 Result, TemplateSpecified); 2150 } 2151 2152 // Note that this is a destructor name. 2153 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName, 2154 ClassNameLoc, getCurScope(), 2155 SS, ObjectType, 2156 EnteringContext); 2157 if (!Ty) 2158 return true; 2159 2160 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc); 2161 return false; 2162 } 2163 2164 Diag(Tok, diag::err_expected_unqualified_id) 2165 << getLangOpts().CPlusPlus; 2166 return true; 2167} 2168 2169/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate 2170/// memory in a typesafe manner and call constructors. 2171/// 2172/// This method is called to parse the new expression after the optional :: has 2173/// been already parsed. If the :: was present, "UseGlobal" is true and "Start" 2174/// is its location. Otherwise, "Start" is the location of the 'new' token. 2175/// 2176/// new-expression: 2177/// '::'[opt] 'new' new-placement[opt] new-type-id 2178/// new-initializer[opt] 2179/// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 2180/// new-initializer[opt] 2181/// 2182/// new-placement: 2183/// '(' expression-list ')' 2184/// 2185/// new-type-id: 2186/// type-specifier-seq new-declarator[opt] 2187/// [GNU] attributes type-specifier-seq new-declarator[opt] 2188/// 2189/// new-declarator: 2190/// ptr-operator new-declarator[opt] 2191/// direct-new-declarator 2192/// 2193/// new-initializer: 2194/// '(' expression-list[opt] ')' 2195/// [C++0x] braced-init-list 2196/// 2197ExprResult 2198Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) { 2199 assert(Tok.is(tok::kw_new) && "expected 'new' token"); 2200 ConsumeToken(); // Consume 'new' 2201 2202 // A '(' now can be a new-placement or the '(' wrapping the type-id in the 2203 // second form of new-expression. It can't be a new-type-id. 2204 2205 ExprVector PlacementArgs(Actions); 2206 SourceLocation PlacementLParen, PlacementRParen; 2207 2208 SourceRange TypeIdParens; 2209 DeclSpec DS(AttrFactory); 2210 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext); 2211 if (Tok.is(tok::l_paren)) { 2212 // If it turns out to be a placement, we change the type location. 2213 BalancedDelimiterTracker T(*this, tok::l_paren); 2214 T.consumeOpen(); 2215 PlacementLParen = T.getOpenLocation(); 2216 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) { 2217 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 2218 return ExprError(); 2219 } 2220 2221 T.consumeClose(); 2222 PlacementRParen = T.getCloseLocation(); 2223 if (PlacementRParen.isInvalid()) { 2224 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 2225 return ExprError(); 2226 } 2227 2228 if (PlacementArgs.empty()) { 2229 // Reset the placement locations. There was no placement. 2230 TypeIdParens = T.getRange(); 2231 PlacementLParen = PlacementRParen = SourceLocation(); 2232 } else { 2233 // We still need the type. 2234 if (Tok.is(tok::l_paren)) { 2235 BalancedDelimiterTracker T(*this, tok::l_paren); 2236 T.consumeOpen(); 2237 MaybeParseGNUAttributes(DeclaratorInfo); 2238 ParseSpecifierQualifierList(DS); 2239 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 2240 ParseDeclarator(DeclaratorInfo); 2241 T.consumeClose(); 2242 TypeIdParens = T.getRange(); 2243 } else { 2244 MaybeParseGNUAttributes(DeclaratorInfo); 2245 if (ParseCXXTypeSpecifierSeq(DS)) 2246 DeclaratorInfo.setInvalidType(true); 2247 else { 2248 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 2249 ParseDeclaratorInternal(DeclaratorInfo, 2250 &Parser::ParseDirectNewDeclarator); 2251 } 2252 } 2253 } 2254 } else { 2255 // A new-type-id is a simplified type-id, where essentially the 2256 // direct-declarator is replaced by a direct-new-declarator. 2257 MaybeParseGNUAttributes(DeclaratorInfo); 2258 if (ParseCXXTypeSpecifierSeq(DS)) 2259 DeclaratorInfo.setInvalidType(true); 2260 else { 2261 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 2262 ParseDeclaratorInternal(DeclaratorInfo, 2263 &Parser::ParseDirectNewDeclarator); 2264 } 2265 } 2266 if (DeclaratorInfo.isInvalidType()) { 2267 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 2268 return ExprError(); 2269 } 2270 2271 ExprResult Initializer; 2272 2273 if (Tok.is(tok::l_paren)) { 2274 SourceLocation ConstructorLParen, ConstructorRParen; 2275 ExprVector ConstructorArgs(Actions); 2276 BalancedDelimiterTracker T(*this, tok::l_paren); 2277 T.consumeOpen(); 2278 ConstructorLParen = T.getOpenLocation(); 2279 if (Tok.isNot(tok::r_paren)) { 2280 CommaLocsTy CommaLocs; 2281 if (ParseExpressionList(ConstructorArgs, CommaLocs)) { 2282 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 2283 return ExprError(); 2284 } 2285 } 2286 T.consumeClose(); 2287 ConstructorRParen = T.getCloseLocation(); 2288 if (ConstructorRParen.isInvalid()) { 2289 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 2290 return ExprError(); 2291 } 2292 Initializer = Actions.ActOnParenListExpr(ConstructorLParen, 2293 ConstructorRParen, 2294 move_arg(ConstructorArgs)); 2295 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus0x) { 2296 Diag(Tok.getLocation(), 2297 diag::warn_cxx98_compat_generalized_initializer_lists); 2298 Initializer = ParseBraceInitializer(); 2299 } 2300 if (Initializer.isInvalid()) 2301 return Initializer; 2302 2303 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen, 2304 move_arg(PlacementArgs), PlacementRParen, 2305 TypeIdParens, DeclaratorInfo, Initializer.take()); 2306} 2307 2308/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be 2309/// passed to ParseDeclaratorInternal. 2310/// 2311/// direct-new-declarator: 2312/// '[' expression ']' 2313/// direct-new-declarator '[' constant-expression ']' 2314/// 2315void Parser::ParseDirectNewDeclarator(Declarator &D) { 2316 // Parse the array dimensions. 2317 bool first = true; 2318 while (Tok.is(tok::l_square)) { 2319 // An array-size expression can't start with a lambda. 2320 if (CheckProhibitedCXX11Attribute()) 2321 continue; 2322 2323 BalancedDelimiterTracker T(*this, tok::l_square); 2324 T.consumeOpen(); 2325 2326 ExprResult Size(first ? ParseExpression() 2327 : ParseConstantExpression()); 2328 if (Size.isInvalid()) { 2329 // Recover 2330 SkipUntil(tok::r_square); 2331 return; 2332 } 2333 first = false; 2334 2335 T.consumeClose(); 2336 2337 // Attributes here appertain to the array type. C++11 [expr.new]p5. 2338 ParsedAttributes Attrs(AttrFactory); 2339 MaybeParseCXX0XAttributes(Attrs); 2340 2341 D.AddTypeInfo(DeclaratorChunk::getArray(0, 2342 /*static=*/false, /*star=*/false, 2343 Size.release(), 2344 T.getOpenLocation(), 2345 T.getCloseLocation()), 2346 Attrs, T.getCloseLocation()); 2347 2348 if (T.getCloseLocation().isInvalid()) 2349 return; 2350 } 2351} 2352 2353/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id. 2354/// This ambiguity appears in the syntax of the C++ new operator. 2355/// 2356/// new-expression: 2357/// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 2358/// new-initializer[opt] 2359/// 2360/// new-placement: 2361/// '(' expression-list ')' 2362/// 2363bool Parser::ParseExpressionListOrTypeId( 2364 SmallVectorImpl<Expr*> &PlacementArgs, 2365 Declarator &D) { 2366 // The '(' was already consumed. 2367 if (isTypeIdInParens()) { 2368 ParseSpecifierQualifierList(D.getMutableDeclSpec()); 2369 D.SetSourceRange(D.getDeclSpec().getSourceRange()); 2370 ParseDeclarator(D); 2371 return D.isInvalidType(); 2372 } 2373 2374 // It's not a type, it has to be an expression list. 2375 // Discard the comma locations - ActOnCXXNew has enough parameters. 2376 CommaLocsTy CommaLocs; 2377 return ParseExpressionList(PlacementArgs, CommaLocs); 2378} 2379 2380/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used 2381/// to free memory allocated by new. 2382/// 2383/// This method is called to parse the 'delete' expression after the optional 2384/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true 2385/// and "Start" is its location. Otherwise, "Start" is the location of the 2386/// 'delete' token. 2387/// 2388/// delete-expression: 2389/// '::'[opt] 'delete' cast-expression 2390/// '::'[opt] 'delete' '[' ']' cast-expression 2391ExprResult 2392Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) { 2393 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword"); 2394 ConsumeToken(); // Consume 'delete' 2395 2396 // Array delete? 2397 bool ArrayDelete = false; 2398 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) { 2399 // FIXME: This could be the start of a lambda-expression. We should 2400 // disambiguate this, but that will require arbitrary lookahead if 2401 // the next token is '(': 2402 // delete [](int*){ /* ... */ 2403 ArrayDelete = true; 2404 BalancedDelimiterTracker T(*this, tok::l_square); 2405 2406 T.consumeOpen(); 2407 T.consumeClose(); 2408 if (T.getCloseLocation().isInvalid()) 2409 return ExprError(); 2410 } 2411 2412 ExprResult Operand(ParseCastExpression(false)); 2413 if (Operand.isInvalid()) 2414 return move(Operand); 2415 2416 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take()); 2417} 2418 2419static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) { 2420 switch(kind) { 2421 default: llvm_unreachable("Not a known unary type trait."); 2422 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign; 2423 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor; 2424 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy; 2425 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign; 2426 case tok::kw___has_trivial_constructor: 2427 return UTT_HasTrivialDefaultConstructor; 2428 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy; 2429 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor; 2430 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor; 2431 case tok::kw___is_abstract: return UTT_IsAbstract; 2432 case tok::kw___is_arithmetic: return UTT_IsArithmetic; 2433 case tok::kw___is_array: return UTT_IsArray; 2434 case tok::kw___is_class: return UTT_IsClass; 2435 case tok::kw___is_complete_type: return UTT_IsCompleteType; 2436 case tok::kw___is_compound: return UTT_IsCompound; 2437 case tok::kw___is_const: return UTT_IsConst; 2438 case tok::kw___is_empty: return UTT_IsEmpty; 2439 case tok::kw___is_enum: return UTT_IsEnum; 2440 case tok::kw___is_final: return UTT_IsFinal; 2441 case tok::kw___is_floating_point: return UTT_IsFloatingPoint; 2442 case tok::kw___is_function: return UTT_IsFunction; 2443 case tok::kw___is_fundamental: return UTT_IsFundamental; 2444 case tok::kw___is_integral: return UTT_IsIntegral; 2445 case tok::kw___is_lvalue_reference: return UTT_IsLvalueReference; 2446 case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer; 2447 case tok::kw___is_member_object_pointer: return UTT_IsMemberObjectPointer; 2448 case tok::kw___is_member_pointer: return UTT_IsMemberPointer; 2449 case tok::kw___is_object: return UTT_IsObject; 2450 case tok::kw___is_literal: return UTT_IsLiteral; 2451 case tok::kw___is_literal_type: return UTT_IsLiteral; 2452 case tok::kw___is_pod: return UTT_IsPOD; 2453 case tok::kw___is_pointer: return UTT_IsPointer; 2454 case tok::kw___is_polymorphic: return UTT_IsPolymorphic; 2455 case tok::kw___is_reference: return UTT_IsReference; 2456 case tok::kw___is_rvalue_reference: return UTT_IsRvalueReference; 2457 case tok::kw___is_scalar: return UTT_IsScalar; 2458 case tok::kw___is_signed: return UTT_IsSigned; 2459 case tok::kw___is_standard_layout: return UTT_IsStandardLayout; 2460 case tok::kw___is_trivial: return UTT_IsTrivial; 2461 case tok::kw___is_trivially_copyable: return UTT_IsTriviallyCopyable; 2462 case tok::kw___is_union: return UTT_IsUnion; 2463 case tok::kw___is_unsigned: return UTT_IsUnsigned; 2464 case tok::kw___is_void: return UTT_IsVoid; 2465 case tok::kw___is_volatile: return UTT_IsVolatile; 2466 } 2467} 2468 2469static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) { 2470 switch(kind) { 2471 default: llvm_unreachable("Not a known binary type trait"); 2472 case tok::kw___is_base_of: return BTT_IsBaseOf; 2473 case tok::kw___is_convertible: return BTT_IsConvertible; 2474 case tok::kw___is_same: return BTT_IsSame; 2475 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible; 2476 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo; 2477 case tok::kw___is_trivially_assignable: return BTT_IsTriviallyAssignable; 2478 } 2479} 2480 2481static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) { 2482 switch (kind) { 2483 default: llvm_unreachable("Not a known type trait"); 2484 case tok::kw___is_trivially_constructible: 2485 return TT_IsTriviallyConstructible; 2486 } 2487} 2488 2489static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) { 2490 switch(kind) { 2491 default: llvm_unreachable("Not a known binary type trait"); 2492 case tok::kw___array_rank: return ATT_ArrayRank; 2493 case tok::kw___array_extent: return ATT_ArrayExtent; 2494 } 2495} 2496 2497static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) { 2498 switch(kind) { 2499 default: llvm_unreachable("Not a known unary expression trait."); 2500 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr; 2501 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr; 2502 } 2503} 2504 2505/// ParseUnaryTypeTrait - Parse the built-in unary type-trait 2506/// pseudo-functions that allow implementation of the TR1/C++0x type traits 2507/// templates. 2508/// 2509/// primary-expression: 2510/// [GNU] unary-type-trait '(' type-id ')' 2511/// 2512ExprResult Parser::ParseUnaryTypeTrait() { 2513 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind()); 2514 SourceLocation Loc = ConsumeToken(); 2515 2516 BalancedDelimiterTracker T(*this, tok::l_paren); 2517 if (T.expectAndConsume(diag::err_expected_lparen)) 2518 return ExprError(); 2519 2520 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type 2521 // there will be cryptic errors about mismatched parentheses and missing 2522 // specifiers. 2523 TypeResult Ty = ParseTypeName(); 2524 2525 T.consumeClose(); 2526 2527 if (Ty.isInvalid()) 2528 return ExprError(); 2529 2530 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), T.getCloseLocation()); 2531} 2532 2533/// ParseBinaryTypeTrait - Parse the built-in binary type-trait 2534/// pseudo-functions that allow implementation of the TR1/C++0x type traits 2535/// templates. 2536/// 2537/// primary-expression: 2538/// [GNU] binary-type-trait '(' type-id ',' type-id ')' 2539/// 2540ExprResult Parser::ParseBinaryTypeTrait() { 2541 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind()); 2542 SourceLocation Loc = ConsumeToken(); 2543 2544 BalancedDelimiterTracker T(*this, tok::l_paren); 2545 if (T.expectAndConsume(diag::err_expected_lparen)) 2546 return ExprError(); 2547 2548 TypeResult LhsTy = ParseTypeName(); 2549 if (LhsTy.isInvalid()) { 2550 SkipUntil(tok::r_paren); 2551 return ExprError(); 2552 } 2553 2554 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) { 2555 SkipUntil(tok::r_paren); 2556 return ExprError(); 2557 } 2558 2559 TypeResult RhsTy = ParseTypeName(); 2560 if (RhsTy.isInvalid()) { 2561 SkipUntil(tok::r_paren); 2562 return ExprError(); 2563 } 2564 2565 T.consumeClose(); 2566 2567 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(), 2568 T.getCloseLocation()); 2569} 2570 2571/// \brief Parse the built-in type-trait pseudo-functions that allow 2572/// implementation of the TR1/C++11 type traits templates. 2573/// 2574/// primary-expression: 2575/// type-trait '(' type-id-seq ')' 2576/// 2577/// type-id-seq: 2578/// type-id ...[opt] type-id-seq[opt] 2579/// 2580ExprResult Parser::ParseTypeTrait() { 2581 TypeTrait Kind = TypeTraitFromTokKind(Tok.getKind()); 2582 SourceLocation Loc = ConsumeToken(); 2583 2584 BalancedDelimiterTracker Parens(*this, tok::l_paren); 2585 if (Parens.expectAndConsume(diag::err_expected_lparen)) 2586 return ExprError(); 2587 2588 llvm::SmallVector<ParsedType, 2> Args; 2589 do { 2590 // Parse the next type. 2591 TypeResult Ty = ParseTypeName(); 2592 if (Ty.isInvalid()) { 2593 Parens.skipToEnd(); 2594 return ExprError(); 2595 } 2596 2597 // Parse the ellipsis, if present. 2598 if (Tok.is(tok::ellipsis)) { 2599 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken()); 2600 if (Ty.isInvalid()) { 2601 Parens.skipToEnd(); 2602 return ExprError(); 2603 } 2604 } 2605 2606 // Add this type to the list of arguments. 2607 Args.push_back(Ty.get()); 2608 2609 if (Tok.is(tok::comma)) { 2610 ConsumeToken(); 2611 continue; 2612 } 2613 2614 break; 2615 } while (true); 2616 2617 if (Parens.consumeClose()) 2618 return ExprError(); 2619 2620 return Actions.ActOnTypeTrait(Kind, Loc, Args, Parens.getCloseLocation()); 2621} 2622 2623/// ParseArrayTypeTrait - Parse the built-in array type-trait 2624/// pseudo-functions. 2625/// 2626/// primary-expression: 2627/// [Embarcadero] '__array_rank' '(' type-id ')' 2628/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')' 2629/// 2630ExprResult Parser::ParseArrayTypeTrait() { 2631 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind()); 2632 SourceLocation Loc = ConsumeToken(); 2633 2634 BalancedDelimiterTracker T(*this, tok::l_paren); 2635 if (T.expectAndConsume(diag::err_expected_lparen)) 2636 return ExprError(); 2637 2638 TypeResult Ty = ParseTypeName(); 2639 if (Ty.isInvalid()) { 2640 SkipUntil(tok::comma); 2641 SkipUntil(tok::r_paren); 2642 return ExprError(); 2643 } 2644 2645 switch (ATT) { 2646 case ATT_ArrayRank: { 2647 T.consumeClose(); 2648 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL, 2649 T.getCloseLocation()); 2650 } 2651 case ATT_ArrayExtent: { 2652 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) { 2653 SkipUntil(tok::r_paren); 2654 return ExprError(); 2655 } 2656 2657 ExprResult DimExpr = ParseExpression(); 2658 T.consumeClose(); 2659 2660 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(), 2661 T.getCloseLocation()); 2662 } 2663 } 2664 llvm_unreachable("Invalid ArrayTypeTrait!"); 2665} 2666 2667/// ParseExpressionTrait - Parse built-in expression-trait 2668/// pseudo-functions like __is_lvalue_expr( xxx ). 2669/// 2670/// primary-expression: 2671/// [Embarcadero] expression-trait '(' expression ')' 2672/// 2673ExprResult Parser::ParseExpressionTrait() { 2674 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind()); 2675 SourceLocation Loc = ConsumeToken(); 2676 2677 BalancedDelimiterTracker T(*this, tok::l_paren); 2678 if (T.expectAndConsume(diag::err_expected_lparen)) 2679 return ExprError(); 2680 2681 ExprResult Expr = ParseExpression(); 2682 2683 T.consumeClose(); 2684 2685 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(), 2686 T.getCloseLocation()); 2687} 2688 2689 2690/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a 2691/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate 2692/// based on the context past the parens. 2693ExprResult 2694Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, 2695 ParsedType &CastTy, 2696 BalancedDelimiterTracker &Tracker) { 2697 assert(getLangOpts().CPlusPlus && "Should only be called for C++!"); 2698 assert(ExprType == CastExpr && "Compound literals are not ambiguous!"); 2699 assert(isTypeIdInParens() && "Not a type-id!"); 2700 2701 ExprResult Result(true); 2702 CastTy = ParsedType(); 2703 2704 // We need to disambiguate a very ugly part of the C++ syntax: 2705 // 2706 // (T())x; - type-id 2707 // (T())*x; - type-id 2708 // (T())/x; - expression 2709 // (T()); - expression 2710 // 2711 // The bad news is that we cannot use the specialized tentative parser, since 2712 // it can only verify that the thing inside the parens can be parsed as 2713 // type-id, it is not useful for determining the context past the parens. 2714 // 2715 // The good news is that the parser can disambiguate this part without 2716 // making any unnecessary Action calls. 2717 // 2718 // It uses a scheme similar to parsing inline methods. The parenthesized 2719 // tokens are cached, the context that follows is determined (possibly by 2720 // parsing a cast-expression), and then we re-introduce the cached tokens 2721 // into the token stream and parse them appropriately. 2722 2723 ParenParseOption ParseAs; 2724 CachedTokens Toks; 2725 2726 // Store the tokens of the parentheses. We will parse them after we determine 2727 // the context that follows them. 2728 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) { 2729 // We didn't find the ')' we expected. 2730 Tracker.consumeClose(); 2731 return ExprError(); 2732 } 2733 2734 if (Tok.is(tok::l_brace)) { 2735 ParseAs = CompoundLiteral; 2736 } else { 2737 bool NotCastExpr; 2738 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression 2739 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) { 2740 NotCastExpr = true; 2741 } else { 2742 // Try parsing the cast-expression that may follow. 2743 // If it is not a cast-expression, NotCastExpr will be true and no token 2744 // will be consumed. 2745 Result = ParseCastExpression(false/*isUnaryExpression*/, 2746 false/*isAddressofOperand*/, 2747 NotCastExpr, 2748 // type-id has priority. 2749 IsTypeCast); 2750 } 2751 2752 // If we parsed a cast-expression, it's really a type-id, otherwise it's 2753 // an expression. 2754 ParseAs = NotCastExpr ? SimpleExpr : CastExpr; 2755 } 2756 2757 // The current token should go after the cached tokens. 2758 Toks.push_back(Tok); 2759 // Re-enter the stored parenthesized tokens into the token stream, so we may 2760 // parse them now. 2761 PP.EnterTokenStream(Toks.data(), Toks.size(), 2762 true/*DisableMacroExpansion*/, false/*OwnsTokens*/); 2763 // Drop the current token and bring the first cached one. It's the same token 2764 // as when we entered this function. 2765 ConsumeAnyToken(); 2766 2767 if (ParseAs >= CompoundLiteral) { 2768 // Parse the type declarator. 2769 DeclSpec DS(AttrFactory); 2770 ParseSpecifierQualifierList(DS); 2771 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 2772 ParseDeclarator(DeclaratorInfo); 2773 2774 // Match the ')'. 2775 Tracker.consumeClose(); 2776 2777 if (ParseAs == CompoundLiteral) { 2778 ExprType = CompoundLiteral; 2779 TypeResult Ty = ParseTypeName(); 2780 return ParseCompoundLiteralExpression(Ty.get(), 2781 Tracker.getOpenLocation(), 2782 Tracker.getCloseLocation()); 2783 } 2784 2785 // We parsed '(' type-id ')' and the thing after it wasn't a '{'. 2786 assert(ParseAs == CastExpr); 2787 2788 if (DeclaratorInfo.isInvalidType()) 2789 return ExprError(); 2790 2791 // Result is what ParseCastExpression returned earlier. 2792 if (!Result.isInvalid()) 2793 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(), 2794 DeclaratorInfo, CastTy, 2795 Tracker.getCloseLocation(), Result.take()); 2796 return move(Result); 2797 } 2798 2799 // Not a compound literal, and not followed by a cast-expression. 2800 assert(ParseAs == SimpleExpr); 2801 2802 ExprType = SimpleExpr; 2803 Result = ParseExpression(); 2804 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 2805 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(), 2806 Tok.getLocation(), Result.take()); 2807 2808 // Match the ')'. 2809 if (Result.isInvalid()) { 2810 SkipUntil(tok::r_paren); 2811 return ExprError(); 2812 } 2813 2814 Tracker.consumeClose(); 2815 return move(Result); 2816} 2817