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