1 //===--- ParseCXXInlineMethods.cpp - C++ class inline methods 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 parsing for C++ class inline methods. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Parse/ParseDiagnostic.h" 15 #include "clang/Parse/Parser.h" 16 #include "clang/Sema/DeclSpec.h" 17 #include "clang/Sema/Scope.h" 18 #include "clang/AST/DeclTemplate.h" 19 using namespace clang; 20 21 /// ParseCXXInlineMethodDef - We parsed and verified that the specified 22 /// Declarator is a well formed C++ inline method definition. Now lex its body 23 /// and store its tokens for parsing after the C++ class is complete. 24 Decl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS, 25 AttributeList *AccessAttrs, 26 ParsingDeclarator &D, 27 const ParsedTemplateInfo &TemplateInfo, 28 const VirtSpecifiers& VS, 29 FunctionDefinitionKind DefinitionKind, 30 ExprResult& Init) { 31 assert(D.isFunctionDeclarator() && "This isn't a function declarator!"); 32 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try) || 33 Tok.is(tok::equal)) && 34 "Current token not a '{', ':', '=', or 'try'!"); 35 36 MultiTemplateParamsArg TemplateParams(Actions, 37 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() : 0, 38 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0); 39 40 Decl *FnD; 41 D.setFunctionDefinitionKind(DefinitionKind); 42 if (D.getDeclSpec().isFriendSpecified()) 43 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D, 44 move(TemplateParams)); 45 else { 46 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D, 47 move(TemplateParams), 0, 48 VS, /*HasDeferredInit=*/false); 49 if (FnD) { 50 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs, 51 false, true); 52 bool TypeSpecContainsAuto 53 = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto; 54 if (Init.isUsable()) 55 Actions.AddInitializerToDecl(FnD, Init.get(), false, 56 TypeSpecContainsAuto); 57 else 58 Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto); 59 } 60 } 61 62 HandleMemberFunctionDeclDelays(D, FnD); 63 64 D.complete(FnD); 65 66 if (Tok.is(tok::equal)) { 67 ConsumeToken(); 68 69 if (!FnD) { 70 SkipUntil(tok::semi); 71 return 0; 72 } 73 74 bool Delete = false; 75 SourceLocation KWLoc; 76 if (Tok.is(tok::kw_delete)) { 77 Diag(Tok, getLangOpts().CPlusPlus0x ? 78 diag::warn_cxx98_compat_deleted_function : 79 diag::ext_deleted_function); 80 81 KWLoc = ConsumeToken(); 82 Actions.SetDeclDeleted(FnD, KWLoc); 83 Delete = true; 84 } else if (Tok.is(tok::kw_default)) { 85 Diag(Tok, getLangOpts().CPlusPlus0x ? 86 diag::warn_cxx98_compat_defaulted_function : 87 diag::ext_defaulted_function); 88 89 KWLoc = ConsumeToken(); 90 Actions.SetDeclDefaulted(FnD, KWLoc); 91 } else { 92 llvm_unreachable("function definition after = not 'delete' or 'default'"); 93 } 94 95 if (Tok.is(tok::comma)) { 96 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration) 97 << Delete; 98 SkipUntil(tok::semi); 99 } else { 100 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 101 Delete ? "delete" : "default", tok::semi); 102 } 103 104 return FnD; 105 } 106 107 // In delayed template parsing mode, if we are within a class template 108 // or if we are about to parse function member template then consume 109 // the tokens and store them for parsing at the end of the translation unit. 110 if (getLangOpts().DelayedTemplateParsing && 111 ((Actions.CurContext->isDependentContext() || 112 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) && 113 !Actions.IsInsideALocalClassWithinATemplateFunction())) { 114 115 if (FnD) { 116 LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(FnD); 117 118 FunctionDecl *FD = 0; 119 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(FnD)) 120 FD = FunTmpl->getTemplatedDecl(); 121 else 122 FD = cast<FunctionDecl>(FnD); 123 Actions.CheckForFunctionRedefinition(FD); 124 125 LateParsedTemplateMap[FD] = LPT; 126 Actions.MarkAsLateParsedTemplate(FD); 127 LexTemplateFunctionForLateParsing(LPT->Toks); 128 } else { 129 CachedTokens Toks; 130 LexTemplateFunctionForLateParsing(Toks); 131 } 132 133 return FnD; 134 } 135 136 // Consume the tokens and store them for later parsing. 137 138 LexedMethod* LM = new LexedMethod(this, FnD); 139 getCurrentClass().LateParsedDeclarations.push_back(LM); 140 LM->TemplateScope = getCurScope()->isTemplateParamScope(); 141 CachedTokens &Toks = LM->Toks; 142 143 tok::TokenKind kind = Tok.getKind(); 144 // Consume everything up to (and including) the left brace of the 145 // function body. 146 if (ConsumeAndStoreFunctionPrologue(Toks)) { 147 // We didn't find the left-brace we expected after the 148 // constructor initializer; we already printed an error, and it's likely 149 // impossible to recover, so don't try to parse this method later. 150 // If we stopped at a semicolon, consume it to avoid an extra warning. 151 if (Tok.is(tok::semi)) 152 ConsumeToken(); 153 delete getCurrentClass().LateParsedDeclarations.back(); 154 getCurrentClass().LateParsedDeclarations.pop_back(); 155 return FnD; 156 } else { 157 // Consume everything up to (and including) the matching right brace. 158 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 159 } 160 161 // If we're in a function-try-block, we need to store all the catch blocks. 162 if (kind == tok::kw_try) { 163 while (Tok.is(tok::kw_catch)) { 164 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false); 165 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 166 } 167 } 168 169 170 if (!FnD) { 171 // If semantic analysis could not build a function declaration, 172 // just throw away the late-parsed declaration. 173 delete getCurrentClass().LateParsedDeclarations.back(); 174 getCurrentClass().LateParsedDeclarations.pop_back(); 175 } 176 177 return FnD; 178 } 179 180 /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the 181 /// specified Declarator is a well formed C++ non-static data member 182 /// declaration. Now lex its initializer and store its tokens for parsing 183 /// after the class is complete. 184 void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) { 185 assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) && 186 "Current token not a '{' or '='!"); 187 188 LateParsedMemberInitializer *MI = 189 new LateParsedMemberInitializer(this, VarD); 190 getCurrentClass().LateParsedDeclarations.push_back(MI); 191 CachedTokens &Toks = MI->Toks; 192 193 tok::TokenKind kind = Tok.getKind(); 194 if (kind == tok::equal) { 195 Toks.push_back(Tok); 196 ConsumeToken(); 197 } 198 199 if (kind == tok::l_brace) { 200 // Begin by storing the '{' token. 201 Toks.push_back(Tok); 202 ConsumeBrace(); 203 204 // Consume everything up to (and including) the matching right brace. 205 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true); 206 } else { 207 // Consume everything up to (but excluding) the comma or semicolon. 208 ConsumeAndStoreUntil(tok::comma, Toks, /*StopAtSemi=*/true, 209 /*ConsumeFinalToken=*/false); 210 } 211 212 // Store an artificial EOF token to ensure that we don't run off the end of 213 // the initializer when we come to parse it. 214 Token Eof; 215 Eof.startToken(); 216 Eof.setKind(tok::eof); 217 Eof.setLocation(Tok.getLocation()); 218 Toks.push_back(Eof); 219 } 220 221 Parser::LateParsedDeclaration::~LateParsedDeclaration() {} 222 void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {} 223 void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {} 224 void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {} 225 226 Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C) 227 : Self(P), Class(C) {} 228 229 Parser::LateParsedClass::~LateParsedClass() { 230 Self->DeallocateParsedClasses(Class); 231 } 232 233 void Parser::LateParsedClass::ParseLexedMethodDeclarations() { 234 Self->ParseLexedMethodDeclarations(*Class); 235 } 236 237 void Parser::LateParsedClass::ParseLexedMemberInitializers() { 238 Self->ParseLexedMemberInitializers(*Class); 239 } 240 241 void Parser::LateParsedClass::ParseLexedMethodDefs() { 242 Self->ParseLexedMethodDefs(*Class); 243 } 244 245 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() { 246 Self->ParseLexedMethodDeclaration(*this); 247 } 248 249 void Parser::LexedMethod::ParseLexedMethodDefs() { 250 Self->ParseLexedMethodDef(*this); 251 } 252 253 void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() { 254 Self->ParseLexedMemberInitializer(*this); 255 } 256 257 /// ParseLexedMethodDeclarations - We finished parsing the member 258 /// specification of a top (non-nested) C++ class. Now go over the 259 /// stack of method declarations with some parts for which parsing was 260 /// delayed (such as default arguments) and parse them. 261 void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) { 262 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; 263 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope); 264 if (HasTemplateScope) 265 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); 266 267 // The current scope is still active if we're the top-level class. 268 // Otherwise we'll need to push and enter a new scope. 269 bool HasClassScope = !Class.TopLevelClass; 270 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope, 271 HasClassScope); 272 if (HasClassScope) 273 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate); 274 275 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) { 276 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations(); 277 } 278 279 if (HasClassScope) 280 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate); 281 } 282 283 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) { 284 // If this is a member template, introduce the template parameter scope. 285 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope); 286 if (LM.TemplateScope) 287 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method); 288 289 // Start the delayed C++ method declaration 290 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method); 291 292 // Introduce the parameters into scope and parse their default 293 // arguments. 294 ParseScope PrototypeScope(this, 295 Scope::FunctionPrototypeScope|Scope::DeclScope); 296 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) { 297 // Introduce the parameter into scope. 298 Actions.ActOnDelayedCXXMethodParameter(getCurScope(), 299 LM.DefaultArgs[I].Param); 300 301 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) { 302 // Save the current token position. 303 SourceLocation origLoc = Tok.getLocation(); 304 305 // Parse the default argument from its saved token stream. 306 Toks->push_back(Tok); // So that the current token doesn't get lost 307 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false); 308 309 // Consume the previously-pushed token. 310 ConsumeAnyToken(); 311 312 // Consume the '='. 313 assert(Tok.is(tok::equal) && "Default argument not starting with '='"); 314 SourceLocation EqualLoc = ConsumeToken(); 315 316 // The argument isn't actually potentially evaluated unless it is 317 // used. 318 EnterExpressionEvaluationContext Eval(Actions, 319 Sema::PotentiallyEvaluatedIfUsed, 320 LM.DefaultArgs[I].Param); 321 322 ExprResult DefArgResult; 323 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 324 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 325 DefArgResult = ParseBraceInitializer(); 326 } else 327 DefArgResult = ParseAssignmentExpression(); 328 if (DefArgResult.isInvalid()) 329 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param); 330 else { 331 if (Tok.is(tok::cxx_defaultarg_end)) 332 ConsumeToken(); 333 else 334 Diag(Tok.getLocation(), diag::err_default_arg_unparsed); 335 Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc, 336 DefArgResult.take()); 337 } 338 339 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc, 340 Tok.getLocation()) && 341 "ParseAssignmentExpression went over the default arg tokens!"); 342 // There could be leftover tokens (e.g. because of an error). 343 // Skip through until we reach the original token position. 344 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof)) 345 ConsumeAnyToken(); 346 347 delete Toks; 348 LM.DefaultArgs[I].Toks = 0; 349 } 350 } 351 352 // Parse a delayed exception-specification, if there is one. 353 if (CachedTokens *Toks = LM.ExceptionSpecTokens) { 354 // Save the current token position. 355 SourceLocation origLoc = Tok.getLocation(); 356 357 // Parse the default argument from its saved token stream. 358 Toks->push_back(Tok); // So that the current token doesn't get lost 359 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false); 360 361 // Consume the previously-pushed token. 362 ConsumeAnyToken(); 363 364 // C++11 [expr.prim.general]p3: 365 // If a declaration declares a member function or member function 366 // template of a class X, the expression this is a prvalue of type 367 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 368 // and the end of the function-definition, member-declarator, or 369 // declarator. 370 CXXMethodDecl *Method; 371 if (FunctionTemplateDecl *FunTmpl 372 = dyn_cast<FunctionTemplateDecl>(LM.Method)) 373 Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 374 else 375 Method = cast<CXXMethodDecl>(LM.Method); 376 377 Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(), 378 Method->getTypeQualifiers(), 379 getLangOpts().CPlusPlus0x); 380 381 // Parse the exception-specification. 382 SourceRange SpecificationRange; 383 SmallVector<ParsedType, 4> DynamicExceptions; 384 SmallVector<SourceRange, 4> DynamicExceptionRanges; 385 ExprResult NoexceptExpr; 386 CachedTokens *ExceptionSpecTokens; 387 388 ExceptionSpecificationType EST 389 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange, 390 DynamicExceptions, 391 DynamicExceptionRanges, NoexceptExpr, 392 ExceptionSpecTokens); 393 394 // Clean up the remaining tokens. 395 if (Tok.is(tok::cxx_exceptspec_end)) 396 ConsumeToken(); 397 else if (EST != EST_None) 398 Diag(Tok.getLocation(), diag::err_except_spec_unparsed); 399 400 // Attach the exception-specification to the method. 401 if (EST != EST_None) 402 Actions.actOnDelayedExceptionSpecification(LM.Method, EST, 403 SpecificationRange, 404 DynamicExceptions, 405 DynamicExceptionRanges, 406 NoexceptExpr.isUsable()? 407 NoexceptExpr.get() : 0); 408 409 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc, 410 Tok.getLocation()) && 411 "tryParseExceptionSpecification went over the exception tokens!"); 412 413 // There could be leftover tokens (e.g. because of an error). 414 // Skip through until we reach the original token position. 415 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof)) 416 ConsumeAnyToken(); 417 418 delete LM.ExceptionSpecTokens; 419 LM.ExceptionSpecTokens = 0; 420 } 421 422 PrototypeScope.Exit(); 423 424 // Finish the delayed C++ method declaration. 425 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method); 426 } 427 428 /// ParseLexedMethodDefs - We finished parsing the member specification of a top 429 /// (non-nested) C++ class. Now go over the stack of lexed methods that were 430 /// collected during its parsing and parse them all. 431 void Parser::ParseLexedMethodDefs(ParsingClass &Class) { 432 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; 433 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope); 434 if (HasTemplateScope) 435 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); 436 437 bool HasClassScope = !Class.TopLevelClass; 438 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope, 439 HasClassScope); 440 441 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) { 442 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs(); 443 } 444 } 445 446 void Parser::ParseLexedMethodDef(LexedMethod &LM) { 447 // If this is a member template, introduce the template parameter scope. 448 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope); 449 if (LM.TemplateScope) 450 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D); 451 452 // Save the current token position. 453 SourceLocation origLoc = Tok.getLocation(); 454 455 assert(!LM.Toks.empty() && "Empty body!"); 456 // Append the current token at the end of the new token stream so that it 457 // doesn't get lost. 458 LM.Toks.push_back(Tok); 459 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false); 460 461 // Consume the previously pushed token. 462 ConsumeAnyToken(); 463 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) 464 && "Inline method not starting with '{', ':' or 'try'"); 465 466 // Parse the method body. Function body parsing code is similar enough 467 // to be re-used for method bodies as well. 468 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope); 469 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D); 470 471 if (Tok.is(tok::kw_try)) { 472 ParseFunctionTryBlock(LM.D, FnScope); 473 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc, 474 Tok.getLocation()) && 475 "ParseFunctionTryBlock went over the cached tokens!"); 476 // There could be leftover tokens (e.g. because of an error). 477 // Skip through until we reach the original token position. 478 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof)) 479 ConsumeAnyToken(); 480 return; 481 } 482 if (Tok.is(tok::colon)) { 483 ParseConstructorInitializer(LM.D); 484 485 // Error recovery. 486 if (!Tok.is(tok::l_brace)) { 487 FnScope.Exit(); 488 Actions.ActOnFinishFunctionBody(LM.D, 0); 489 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof)) 490 ConsumeAnyToken(); 491 return; 492 } 493 } else 494 Actions.ActOnDefaultCtorInitializers(LM.D); 495 496 ParseFunctionStatementBody(LM.D, FnScope); 497 498 if (Tok.getLocation() != origLoc) { 499 // Due to parsing error, we either went over the cached tokens or 500 // there are still cached tokens left. If it's the latter case skip the 501 // leftover tokens. 502 // Since this is an uncommon situation that should be avoided, use the 503 // expensive isBeforeInTranslationUnit call. 504 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(), 505 origLoc)) 506 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof)) 507 ConsumeAnyToken(); 508 } 509 } 510 511 /// ParseLexedMemberInitializers - We finished parsing the member specification 512 /// of a top (non-nested) C++ class. Now go over the stack of lexed data member 513 /// initializers that were collected during its parsing and parse them all. 514 void Parser::ParseLexedMemberInitializers(ParsingClass &Class) { 515 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; 516 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, 517 HasTemplateScope); 518 if (HasTemplateScope) 519 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); 520 521 // Set or update the scope flags. 522 bool AlreadyHasClassScope = Class.TopLevelClass; 523 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope; 524 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope); 525 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope); 526 527 if (!AlreadyHasClassScope) 528 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), 529 Class.TagOrTemplate); 530 531 { 532 // C++11 [expr.prim.general]p4: 533 // Otherwise, if a member-declarator declares a non-static data member 534 // (9.2) of a class X, the expression this is a prvalue of type "pointer 535 // to X" within the optional brace-or-equal-initializer. It shall not 536 // appear elsewhere in the member-declarator. 537 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate, 538 /*TypeQuals=*/(unsigned)0); 539 540 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) { 541 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers(); 542 } 543 } 544 545 if (!AlreadyHasClassScope) 546 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), 547 Class.TagOrTemplate); 548 549 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate); 550 } 551 552 void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) { 553 if (!MI.Field || MI.Field->isInvalidDecl()) 554 return; 555 556 // Append the current token at the end of the new token stream so that it 557 // doesn't get lost. 558 MI.Toks.push_back(Tok); 559 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false); 560 561 // Consume the previously pushed token. 562 ConsumeAnyToken(); 563 564 SourceLocation EqualLoc; 565 566 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false, 567 EqualLoc); 568 569 Actions.ActOnCXXInClassMemberInitializer(MI.Field, EqualLoc, Init.release()); 570 571 // The next token should be our artificial terminating EOF token. 572 if (Tok.isNot(tok::eof)) { 573 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation); 574 if (!EndLoc.isValid()) 575 EndLoc = Tok.getLocation(); 576 // No fixit; we can't recover as if there were a semicolon here. 577 Diag(EndLoc, diag::err_expected_semi_decl_list); 578 579 // Consume tokens until we hit the artificial EOF. 580 while (Tok.isNot(tok::eof)) 581 ConsumeAnyToken(); 582 } 583 ConsumeAnyToken(); 584 } 585 586 /// ConsumeAndStoreUntil - Consume and store the token at the passed token 587 /// container until the token 'T' is reached (which gets 588 /// consumed/stored too, if ConsumeFinalToken). 589 /// If StopAtSemi is true, then we will stop early at a ';' character. 590 /// Returns true if token 'T1' or 'T2' was found. 591 /// NOTE: This is a specialized version of Parser::SkipUntil. 592 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, 593 CachedTokens &Toks, 594 bool StopAtSemi, bool ConsumeFinalToken) { 595 // We always want this function to consume at least one token if the first 596 // token isn't T and if not at EOF. 597 bool isFirstTokenConsumed = true; 598 while (1) { 599 // If we found one of the tokens, stop and return true. 600 if (Tok.is(T1) || Tok.is(T2)) { 601 if (ConsumeFinalToken) { 602 Toks.push_back(Tok); 603 ConsumeAnyToken(); 604 } 605 return true; 606 } 607 608 switch (Tok.getKind()) { 609 case tok::eof: 610 // Ran out of tokens. 611 return false; 612 613 case tok::l_paren: 614 // Recursively consume properly-nested parens. 615 Toks.push_back(Tok); 616 ConsumeParen(); 617 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); 618 break; 619 case tok::l_square: 620 // Recursively consume properly-nested square brackets. 621 Toks.push_back(Tok); 622 ConsumeBracket(); 623 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false); 624 break; 625 case tok::l_brace: 626 // Recursively consume properly-nested braces. 627 Toks.push_back(Tok); 628 ConsumeBrace(); 629 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 630 break; 631 632 // Okay, we found a ']' or '}' or ')', which we think should be balanced. 633 // Since the user wasn't looking for this token (if they were, it would 634 // already be handled), this isn't balanced. If there is a LHS token at a 635 // higher level, we will assume that this matches the unbalanced token 636 // and return it. Otherwise, this is a spurious RHS token, which we skip. 637 case tok::r_paren: 638 if (ParenCount && !isFirstTokenConsumed) 639 return false; // Matches something. 640 Toks.push_back(Tok); 641 ConsumeParen(); 642 break; 643 case tok::r_square: 644 if (BracketCount && !isFirstTokenConsumed) 645 return false; // Matches something. 646 Toks.push_back(Tok); 647 ConsumeBracket(); 648 break; 649 case tok::r_brace: 650 if (BraceCount && !isFirstTokenConsumed) 651 return false; // Matches something. 652 Toks.push_back(Tok); 653 ConsumeBrace(); 654 break; 655 656 case tok::code_completion: 657 Toks.push_back(Tok); 658 ConsumeCodeCompletionToken(); 659 break; 660 661 case tok::string_literal: 662 case tok::wide_string_literal: 663 case tok::utf8_string_literal: 664 case tok::utf16_string_literal: 665 case tok::utf32_string_literal: 666 Toks.push_back(Tok); 667 ConsumeStringToken(); 668 break; 669 case tok::semi: 670 if (StopAtSemi) 671 return false; 672 // FALL THROUGH. 673 default: 674 // consume this token. 675 Toks.push_back(Tok); 676 ConsumeToken(); 677 break; 678 } 679 isFirstTokenConsumed = false; 680 } 681 } 682 683 /// \brief Consume tokens and store them in the passed token container until 684 /// we've passed the try keyword and constructor initializers and have consumed 685 /// the opening brace of the function body. The opening brace will be consumed 686 /// if and only if there was no error. 687 /// 688 /// \return True on error. 689 bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) { 690 if (Tok.is(tok::kw_try)) { 691 Toks.push_back(Tok); 692 ConsumeToken(); 693 } 694 bool ReadInitializer = false; 695 if (Tok.is(tok::colon)) { 696 // Initializers can contain braces too. 697 Toks.push_back(Tok); 698 ConsumeToken(); 699 700 while (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) { 701 if (Tok.is(tok::eof) || Tok.is(tok::semi)) 702 return Diag(Tok.getLocation(), diag::err_expected_lbrace); 703 704 // Grab the identifier. 705 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks, 706 /*StopAtSemi=*/true, 707 /*ConsumeFinalToken=*/false)) 708 return Diag(Tok.getLocation(), diag::err_expected_lparen); 709 710 tok::TokenKind kind = Tok.getKind(); 711 Toks.push_back(Tok); 712 bool IsLParen = (kind == tok::l_paren); 713 SourceLocation LOpen = Tok.getLocation(); 714 715 if (IsLParen) { 716 ConsumeParen(); 717 } else { 718 assert(kind == tok::l_brace && "Must be left paren or brace here."); 719 ConsumeBrace(); 720 // In C++03, this has to be the start of the function body, which 721 // means the initializer is malformed; we'll diagnose it later. 722 if (!getLangOpts().CPlusPlus0x) 723 return false; 724 } 725 726 // Grab the initializer 727 if (!ConsumeAndStoreUntil(IsLParen ? tok::r_paren : tok::r_brace, 728 Toks, /*StopAtSemi=*/true)) { 729 Diag(Tok, IsLParen ? diag::err_expected_rparen : 730 diag::err_expected_rbrace); 731 Diag(LOpen, diag::note_matching) << (IsLParen ? "(" : "{"); 732 return true; 733 } 734 735 // Grab pack ellipsis, if present 736 if (Tok.is(tok::ellipsis)) { 737 Toks.push_back(Tok); 738 ConsumeToken(); 739 } 740 741 // Grab the separating comma, if any. 742 if (Tok.is(tok::comma)) { 743 Toks.push_back(Tok); 744 ConsumeToken(); 745 } else if (Tok.isNot(tok::l_brace)) { 746 ReadInitializer = true; 747 break; 748 } 749 } 750 } 751 752 // Grab any remaining garbage to be diagnosed later. We stop when we reach a 753 // brace: an opening one is the function body, while a closing one probably 754 // means we've reached the end of the class. 755 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks, 756 /*StopAtSemi=*/true, 757 /*ConsumeFinalToken=*/false); 758 if (Tok.isNot(tok::l_brace)) { 759 if (ReadInitializer) 760 return Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma); 761 return Diag(Tok.getLocation(), diag::err_expected_lbrace); 762 } 763 764 Toks.push_back(Tok); 765 ConsumeBrace(); 766 return false; 767 } 768