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