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