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