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/Parser.h" 15 #include "RAIIObjectsForParser.h" 16 #include "clang/AST/DeclTemplate.h" 17 #include "clang/Parse/ParseDiagnostic.h" 18 #include "clang/Sema/DeclSpec.h" 19 #include "clang/Sema/Scope.h" 20 using namespace clang; 21 22 /// Get the FunctionDecl for a function or function template decl. 23 static FunctionDecl *getFunctionDecl(Decl *D) { 24 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(D)) 25 return fn; 26 return cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 27 } 28 29 /// ParseCXXInlineMethodDef - We parsed and verified that the specified 30 /// Declarator is a well formed C++ inline method definition. Now lex its body 31 /// and store its tokens for parsing after the C++ class is complete. 32 NamedDecl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS, 33 AttributeList *AccessAttrs, 34 ParsingDeclarator &D, 35 const ParsedTemplateInfo &TemplateInfo, 36 const VirtSpecifiers& VS, 37 FunctionDefinitionKind DefinitionKind, 38 ExprResult& Init) { 39 assert(D.isFunctionDeclarator() && "This isn't a function declarator!"); 40 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try) || 41 Tok.is(tok::equal)) && 42 "Current token not a '{', ':', '=', or 'try'!"); 43 44 MultiTemplateParamsArg TemplateParams( 45 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() : 0, 46 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0); 47 48 NamedDecl *FnD; 49 D.setFunctionDefinitionKind(DefinitionKind); 50 if (D.getDeclSpec().isFriendSpecified()) 51 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D, 52 TemplateParams); 53 else { 54 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D, 55 TemplateParams, 0, 56 VS, ICIS_NoInit); 57 if (FnD) { 58 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs); 59 bool TypeSpecContainsAuto = D.getDeclSpec().containsPlaceholderType(); 60 if (Init.isUsable()) 61 Actions.AddInitializerToDecl(FnD, Init.get(), false, 62 TypeSpecContainsAuto); 63 else 64 Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto); 65 } 66 } 67 68 HandleMemberFunctionDeclDelays(D, FnD); 69 70 D.complete(FnD); 71 72 if (Tok.is(tok::equal)) { 73 ConsumeToken(); 74 75 if (!FnD) { 76 SkipUntil(tok::semi); 77 return 0; 78 } 79 80 bool Delete = false; 81 SourceLocation KWLoc; 82 if (Tok.is(tok::kw_delete)) { 83 Diag(Tok, getLangOpts().CPlusPlus11 ? 84 diag::warn_cxx98_compat_deleted_function : 85 diag::ext_deleted_function); 86 87 KWLoc = ConsumeToken(); 88 Actions.SetDeclDeleted(FnD, KWLoc); 89 Delete = true; 90 } else if (Tok.is(tok::kw_default)) { 91 Diag(Tok, getLangOpts().CPlusPlus11 ? 92 diag::warn_cxx98_compat_defaulted_function : 93 diag::ext_defaulted_function); 94 95 KWLoc = ConsumeToken(); 96 Actions.SetDeclDefaulted(FnD, KWLoc); 97 } else { 98 llvm_unreachable("function definition after = not 'delete' or 'default'"); 99 } 100 101 if (Tok.is(tok::comma)) { 102 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration) 103 << Delete; 104 SkipUntil(tok::semi); 105 } else { 106 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 107 Delete ? "delete" : "default", tok::semi); 108 } 109 110 return FnD; 111 } 112 113 // In delayed template parsing mode, if we are within a class template 114 // or if we are about to parse function member template then consume 115 // the tokens and store them for parsing at the end of the translation unit. 116 if (getLangOpts().DelayedTemplateParsing && 117 DefinitionKind == FDK_Definition && 118 !D.getDeclSpec().isConstexprSpecified() && 119 ((Actions.CurContext->isDependentContext() || 120 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 121 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) && 122 !Actions.IsInsideALocalClassWithinATemplateFunction())) { 123 124 CachedTokens Toks; 125 LexTemplateFunctionForLateParsing(Toks); 126 127 if (FnD) { 128 FunctionDecl *FD = getFunctionDecl(FnD); 129 Actions.CheckForFunctionRedefinition(FD); 130 Actions.MarkAsLateParsedTemplate(FD, FnD, 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 // Skip over the rest of the decl and back to somewhere that looks 151 // reasonable. 152 SkipMalformedDecl(); 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 if (FnD) { 170 // If this is a friend function, mark that it's late-parsed so that 171 // it's still known to be a definition even before we attach the 172 // parsed body. Sema needs to treat friend function definitions 173 // differently during template instantiation, and it's possible for 174 // the containing class to be instantiated before all its member 175 // function definitions are parsed. 176 // 177 // If you remove this, you can remove the code that clears the flag 178 // after parsing the member. 179 if (D.getDeclSpec().isFriendSpecified()) { 180 FunctionDecl *FD = getFunctionDecl(FnD); 181 Actions.CheckForFunctionRedefinition(FD); 182 FD->setLateTemplateParsed(true); 183 } 184 } else { 185 // If semantic analysis could not build a function declaration, 186 // just throw away the late-parsed declaration. 187 delete getCurrentClass().LateParsedDeclarations.back(); 188 getCurrentClass().LateParsedDeclarations.pop_back(); 189 } 190 191 return FnD; 192 } 193 194 /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the 195 /// specified Declarator is a well formed C++ non-static data member 196 /// declaration. Now lex its initializer and store its tokens for parsing 197 /// after the class is complete. 198 void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) { 199 assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) && 200 "Current token not a '{' or '='!"); 201 202 LateParsedMemberInitializer *MI = 203 new LateParsedMemberInitializer(this, VarD); 204 getCurrentClass().LateParsedDeclarations.push_back(MI); 205 CachedTokens &Toks = MI->Toks; 206 207 tok::TokenKind kind = Tok.getKind(); 208 if (kind == tok::equal) { 209 Toks.push_back(Tok); 210 ConsumeToken(); 211 } 212 213 if (kind == tok::l_brace) { 214 // Begin by storing the '{' token. 215 Toks.push_back(Tok); 216 ConsumeBrace(); 217 218 // Consume everything up to (and including) the matching right brace. 219 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true); 220 } else { 221 // Consume everything up to (but excluding) the comma or semicolon. 222 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer); 223 } 224 225 // Store an artificial EOF token to ensure that we don't run off the end of 226 // the initializer when we come to parse it. 227 Token Eof; 228 Eof.startToken(); 229 Eof.setKind(tok::eof); 230 Eof.setLocation(Tok.getLocation()); 231 Toks.push_back(Eof); 232 } 233 234 Parser::LateParsedDeclaration::~LateParsedDeclaration() {} 235 void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {} 236 void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {} 237 void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {} 238 239 Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C) 240 : Self(P), Class(C) {} 241 242 Parser::LateParsedClass::~LateParsedClass() { 243 Self->DeallocateParsedClasses(Class); 244 } 245 246 void Parser::LateParsedClass::ParseLexedMethodDeclarations() { 247 Self->ParseLexedMethodDeclarations(*Class); 248 } 249 250 void Parser::LateParsedClass::ParseLexedMemberInitializers() { 251 Self->ParseLexedMemberInitializers(*Class); 252 } 253 254 void Parser::LateParsedClass::ParseLexedMethodDefs() { 255 Self->ParseLexedMethodDefs(*Class); 256 } 257 258 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() { 259 Self->ParseLexedMethodDeclaration(*this); 260 } 261 262 void Parser::LexedMethod::ParseLexedMethodDefs() { 263 Self->ParseLexedMethodDef(*this); 264 } 265 266 void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() { 267 Self->ParseLexedMemberInitializer(*this); 268 } 269 270 /// ParseLexedMethodDeclarations - We finished parsing the member 271 /// specification of a top (non-nested) C++ class. Now go over the 272 /// stack of method declarations with some parts for which parsing was 273 /// delayed (such as default arguments) and parse them. 274 void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) { 275 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; 276 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope); 277 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); 278 if (HasTemplateScope) { 279 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); 280 ++CurTemplateDepthTracker; 281 } 282 283 // The current scope is still active if we're the top-level class. 284 // Otherwise we'll need to push and enter a new scope. 285 bool HasClassScope = !Class.TopLevelClass; 286 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope, 287 HasClassScope); 288 if (HasClassScope) 289 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate); 290 291 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) { 292 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations(); 293 } 294 295 if (HasClassScope) 296 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate); 297 } 298 299 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) { 300 // If this is a member template, introduce the template parameter scope. 301 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope); 302 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); 303 if (LM.TemplateScope) { 304 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method); 305 ++CurTemplateDepthTracker; 306 } 307 // Start the delayed C++ method declaration 308 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method); 309 310 // Introduce the parameters into scope and parse their default 311 // arguments. 312 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | 313 Scope::FunctionDeclarationScope | Scope::DeclScope); 314 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) { 315 // Introduce the parameter into scope. 316 Actions.ActOnDelayedCXXMethodParameter(getCurScope(), 317 LM.DefaultArgs[I].Param); 318 319 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) { 320 // Save the current token position. 321 SourceLocation origLoc = Tok.getLocation(); 322 323 // Parse the default argument from its saved token stream. 324 Toks->push_back(Tok); // So that the current token doesn't get lost 325 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false); 326 327 // Consume the previously-pushed token. 328 ConsumeAnyToken(); 329 330 // Consume the '='. 331 assert(Tok.is(tok::equal) && "Default argument not starting with '='"); 332 SourceLocation EqualLoc = ConsumeToken(); 333 334 // The argument isn't actually potentially evaluated unless it is 335 // used. 336 EnterExpressionEvaluationContext Eval(Actions, 337 Sema::PotentiallyEvaluatedIfUsed, 338 LM.DefaultArgs[I].Param); 339 340 ExprResult DefArgResult; 341 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 342 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 343 DefArgResult = ParseBraceInitializer(); 344 } else 345 DefArgResult = ParseAssignmentExpression(); 346 if (DefArgResult.isInvalid()) 347 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param); 348 else { 349 if (Tok.is(tok::cxx_defaultarg_end)) 350 ConsumeToken(); 351 else { 352 // The last two tokens are the terminator and the saved value of 353 // Tok; the last token in the default argument is the one before 354 // those. 355 assert(Toks->size() >= 3 && "expected a token in default arg"); 356 Diag(Tok.getLocation(), diag::err_default_arg_unparsed) 357 << SourceRange(Tok.getLocation(), 358 (*Toks)[Toks->size() - 3].getLocation()); 359 } 360 Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc, 361 DefArgResult.take()); 362 } 363 364 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc, 365 Tok.getLocation()) && 366 "ParseAssignmentExpression went over the default arg tokens!"); 367 // There could be leftover tokens (e.g. because of an error). 368 // Skip through until we reach the original token position. 369 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof)) 370 ConsumeAnyToken(); 371 372 delete Toks; 373 LM.DefaultArgs[I].Toks = 0; 374 } 375 } 376 377 PrototypeScope.Exit(); 378 379 // Finish the delayed C++ method declaration. 380 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method); 381 } 382 383 /// ParseLexedMethodDefs - We finished parsing the member specification of a top 384 /// (non-nested) C++ class. Now go over the stack of lexed methods that were 385 /// collected during its parsing and parse them all. 386 void Parser::ParseLexedMethodDefs(ParsingClass &Class) { 387 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; 388 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope); 389 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); 390 if (HasTemplateScope) { 391 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); 392 ++CurTemplateDepthTracker; 393 } 394 bool HasClassScope = !Class.TopLevelClass; 395 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope, 396 HasClassScope); 397 398 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) { 399 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs(); 400 } 401 } 402 403 void Parser::ParseLexedMethodDef(LexedMethod &LM) { 404 // If this is a member template, introduce the template parameter scope. 405 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope); 406 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); 407 if (LM.TemplateScope) { 408 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D); 409 ++CurTemplateDepthTracker; 410 } 411 // Save the current token position. 412 SourceLocation origLoc = Tok.getLocation(); 413 414 assert(!LM.Toks.empty() && "Empty body!"); 415 // Append the current token at the end of the new token stream so that it 416 // doesn't get lost. 417 LM.Toks.push_back(Tok); 418 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false); 419 420 // Consume the previously pushed token. 421 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 422 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) 423 && "Inline method not starting with '{', ':' or 'try'"); 424 425 // Parse the method body. Function body parsing code is similar enough 426 // to be re-used for method bodies as well. 427 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope); 428 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D); 429 430 if (Tok.is(tok::kw_try)) { 431 ParseFunctionTryBlock(LM.D, FnScope); 432 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc, 433 Tok.getLocation()) && 434 "ParseFunctionTryBlock went over the cached tokens!"); 435 // There could be leftover tokens (e.g. because of an error). 436 // Skip through until we reach the original token position. 437 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof)) 438 ConsumeAnyToken(); 439 return; 440 } 441 if (Tok.is(tok::colon)) { 442 ParseConstructorInitializer(LM.D); 443 444 // Error recovery. 445 if (!Tok.is(tok::l_brace)) { 446 FnScope.Exit(); 447 Actions.ActOnFinishFunctionBody(LM.D, 0); 448 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof)) 449 ConsumeAnyToken(); 450 return; 451 } 452 } else 453 Actions.ActOnDefaultCtorInitializers(LM.D); 454 455 assert((Actions.getDiagnostics().hasErrorOccurred() || 456 !isa<FunctionTemplateDecl>(LM.D) || 457 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth() 458 < TemplateParameterDepth) && 459 "TemplateParameterDepth should be greater than the depth of " 460 "current template being instantiated!"); 461 462 ParseFunctionStatementBody(LM.D, FnScope); 463 464 // Clear the late-template-parsed bit if we set it before. 465 if (LM.D) getFunctionDecl(LM.D)->setLateTemplateParsed(false); 466 467 if (Tok.getLocation() != origLoc) { 468 // Due to parsing error, we either went over the cached tokens or 469 // there are still cached tokens left. If it's the latter case skip the 470 // leftover tokens. 471 // Since this is an uncommon situation that should be avoided, use the 472 // expensive isBeforeInTranslationUnit call. 473 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(), 474 origLoc)) 475 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof)) 476 ConsumeAnyToken(); 477 } 478 } 479 480 /// ParseLexedMemberInitializers - We finished parsing the member specification 481 /// of a top (non-nested) C++ class. Now go over the stack of lexed data member 482 /// initializers that were collected during its parsing and parse them all. 483 void Parser::ParseLexedMemberInitializers(ParsingClass &Class) { 484 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; 485 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, 486 HasTemplateScope); 487 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); 488 if (HasTemplateScope) { 489 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); 490 ++CurTemplateDepthTracker; 491 } 492 // Set or update the scope flags. 493 bool AlreadyHasClassScope = Class.TopLevelClass; 494 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope; 495 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope); 496 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope); 497 498 if (!AlreadyHasClassScope) 499 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), 500 Class.TagOrTemplate); 501 502 if (!Class.LateParsedDeclarations.empty()) { 503 // C++11 [expr.prim.general]p4: 504 // Otherwise, if a member-declarator declares a non-static data member 505 // (9.2) of a class X, the expression this is a prvalue of type "pointer 506 // to X" within the optional brace-or-equal-initializer. It shall not 507 // appear elsewhere in the member-declarator. 508 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate, 509 /*TypeQuals=*/(unsigned)0); 510 511 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) { 512 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers(); 513 } 514 } 515 516 if (!AlreadyHasClassScope) 517 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), 518 Class.TagOrTemplate); 519 520 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate); 521 } 522 523 void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) { 524 if (!MI.Field || MI.Field->isInvalidDecl()) 525 return; 526 527 // Append the current token at the end of the new token stream so that it 528 // doesn't get lost. 529 MI.Toks.push_back(Tok); 530 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false); 531 532 // Consume the previously pushed token. 533 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 534 535 SourceLocation EqualLoc; 536 537 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false, 538 EqualLoc); 539 540 Actions.ActOnCXXInClassMemberInitializer(MI.Field, EqualLoc, Init.release()); 541 542 // The next token should be our artificial terminating EOF token. 543 if (Tok.isNot(tok::eof)) { 544 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation); 545 if (!EndLoc.isValid()) 546 EndLoc = Tok.getLocation(); 547 // No fixit; we can't recover as if there were a semicolon here. 548 Diag(EndLoc, diag::err_expected_semi_decl_list); 549 550 // Consume tokens until we hit the artificial EOF. 551 while (Tok.isNot(tok::eof)) 552 ConsumeAnyToken(); 553 } 554 ConsumeAnyToken(); 555 } 556 557 /// ConsumeAndStoreUntil - Consume and store the token at the passed token 558 /// container until the token 'T' is reached (which gets 559 /// consumed/stored too, if ConsumeFinalToken). 560 /// If StopAtSemi is true, then we will stop early at a ';' character. 561 /// Returns true if token 'T1' or 'T2' was found. 562 /// NOTE: This is a specialized version of Parser::SkipUntil. 563 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, 564 CachedTokens &Toks, 565 bool StopAtSemi, bool ConsumeFinalToken) { 566 // We always want this function to consume at least one token if the first 567 // token isn't T and if not at EOF. 568 bool isFirstTokenConsumed = true; 569 while (1) { 570 // If we found one of the tokens, stop and return true. 571 if (Tok.is(T1) || Tok.is(T2)) { 572 if (ConsumeFinalToken) { 573 Toks.push_back(Tok); 574 ConsumeAnyToken(); 575 } 576 return true; 577 } 578 579 switch (Tok.getKind()) { 580 case tok::eof: 581 // Ran out of tokens. 582 return false; 583 584 case tok::l_paren: 585 // Recursively consume properly-nested parens. 586 Toks.push_back(Tok); 587 ConsumeParen(); 588 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); 589 break; 590 case tok::l_square: 591 // Recursively consume properly-nested square brackets. 592 Toks.push_back(Tok); 593 ConsumeBracket(); 594 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false); 595 break; 596 case tok::l_brace: 597 // Recursively consume properly-nested braces. 598 Toks.push_back(Tok); 599 ConsumeBrace(); 600 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 601 break; 602 603 // Okay, we found a ']' or '}' or ')', which we think should be balanced. 604 // Since the user wasn't looking for this token (if they were, it would 605 // already be handled), this isn't balanced. If there is a LHS token at a 606 // higher level, we will assume that this matches the unbalanced token 607 // and return it. Otherwise, this is a spurious RHS token, which we skip. 608 case tok::r_paren: 609 if (ParenCount && !isFirstTokenConsumed) 610 return false; // Matches something. 611 Toks.push_back(Tok); 612 ConsumeParen(); 613 break; 614 case tok::r_square: 615 if (BracketCount && !isFirstTokenConsumed) 616 return false; // Matches something. 617 Toks.push_back(Tok); 618 ConsumeBracket(); 619 break; 620 case tok::r_brace: 621 if (BraceCount && !isFirstTokenConsumed) 622 return false; // Matches something. 623 Toks.push_back(Tok); 624 ConsumeBrace(); 625 break; 626 627 case tok::code_completion: 628 Toks.push_back(Tok); 629 ConsumeCodeCompletionToken(); 630 break; 631 632 case tok::string_literal: 633 case tok::wide_string_literal: 634 case tok::utf8_string_literal: 635 case tok::utf16_string_literal: 636 case tok::utf32_string_literal: 637 Toks.push_back(Tok); 638 ConsumeStringToken(); 639 break; 640 case tok::semi: 641 if (StopAtSemi) 642 return false; 643 // FALL THROUGH. 644 default: 645 // consume this token. 646 Toks.push_back(Tok); 647 ConsumeToken(); 648 break; 649 } 650 isFirstTokenConsumed = false; 651 } 652 } 653 654 /// \brief Consume tokens and store them in the passed token container until 655 /// we've passed the try keyword and constructor initializers and have consumed 656 /// the opening brace of the function body. The opening brace will be consumed 657 /// if and only if there was no error. 658 /// 659 /// \return True on error. 660 bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) { 661 if (Tok.is(tok::kw_try)) { 662 Toks.push_back(Tok); 663 ConsumeToken(); 664 } 665 666 if (Tok.isNot(tok::colon)) { 667 // Easy case, just a function body. 668 669 // Grab any remaining garbage to be diagnosed later. We stop when we reach a 670 // brace: an opening one is the function body, while a closing one probably 671 // means we've reached the end of the class. 672 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks, 673 /*StopAtSemi=*/true, 674 /*ConsumeFinalToken=*/false); 675 if (Tok.isNot(tok::l_brace)) 676 return Diag(Tok.getLocation(), diag::err_expected_lbrace); 677 678 Toks.push_back(Tok); 679 ConsumeBrace(); 680 return false; 681 } 682 683 Toks.push_back(Tok); 684 ConsumeToken(); 685 686 // We can't reliably skip over a mem-initializer-id, because it could be 687 // a template-id involving not-yet-declared names. Given: 688 // 689 // S ( ) : a < b < c > ( e ) 690 // 691 // 'e' might be an initializer or part of a template argument, depending 692 // on whether 'b' is a template. 693 694 // Track whether we might be inside a template argument. We can give 695 // significantly better diagnostics if we know that we're not. 696 bool MightBeTemplateArgument = false; 697 698 while (true) { 699 // Skip over the mem-initializer-id, if possible. 700 if (Tok.is(tok::kw_decltype)) { 701 Toks.push_back(Tok); 702 SourceLocation OpenLoc = ConsumeToken(); 703 if (Tok.isNot(tok::l_paren)) 704 return Diag(Tok.getLocation(), diag::err_expected_lparen_after) 705 << "decltype"; 706 Toks.push_back(Tok); 707 ConsumeParen(); 708 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) { 709 Diag(Tok.getLocation(), diag::err_expected_rparen); 710 Diag(OpenLoc, diag::note_matching) << "("; 711 return true; 712 } 713 } 714 do { 715 // Walk over a component of a nested-name-specifier. 716 if (Tok.is(tok::coloncolon)) { 717 Toks.push_back(Tok); 718 ConsumeToken(); 719 720 if (Tok.is(tok::kw_template)) { 721 Toks.push_back(Tok); 722 ConsumeToken(); 723 } 724 } 725 726 if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) { 727 Toks.push_back(Tok); 728 ConsumeToken(); 729 } else if (Tok.is(tok::code_completion)) { 730 Toks.push_back(Tok); 731 ConsumeCodeCompletionToken(); 732 // Consume the rest of the initializers permissively. 733 // FIXME: We should be able to perform code-completion here even if 734 // there isn't a subsequent '{' token. 735 MightBeTemplateArgument = true; 736 break; 737 } else { 738 break; 739 } 740 } while (Tok.is(tok::coloncolon)); 741 742 if (Tok.is(tok::less)) 743 MightBeTemplateArgument = true; 744 745 if (MightBeTemplateArgument) { 746 // We may be inside a template argument list. Grab up to the start of the 747 // next parenthesized initializer or braced-init-list. This *might* be the 748 // initializer, or it might be a subexpression in the template argument 749 // list. 750 // FIXME: Count angle brackets, and clear MightBeTemplateArgument 751 // if all angles are closed. 752 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks, 753 /*StopAtSemi=*/true, 754 /*ConsumeFinalToken=*/false)) { 755 // We're not just missing the initializer, we're also missing the 756 // function body! 757 return Diag(Tok.getLocation(), diag::err_expected_lbrace); 758 } 759 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) { 760 // We found something weird in a mem-initializer-id. 761 return Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 762 ? diag::err_expected_lparen_or_lbrace 763 : diag::err_expected_lparen); 764 } 765 766 tok::TokenKind kind = Tok.getKind(); 767 Toks.push_back(Tok); 768 bool IsLParen = (kind == tok::l_paren); 769 SourceLocation OpenLoc = Tok.getLocation(); 770 771 if (IsLParen) { 772 ConsumeParen(); 773 } else { 774 assert(kind == tok::l_brace && "Must be left paren or brace here."); 775 ConsumeBrace(); 776 // In C++03, this has to be the start of the function body, which 777 // means the initializer is malformed; we'll diagnose it later. 778 if (!getLangOpts().CPlusPlus11) 779 return false; 780 } 781 782 // Grab the initializer (or the subexpression of the template argument). 783 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false 784 // if we might be inside the braces of a lambda-expression. 785 if (!ConsumeAndStoreUntil(IsLParen ? tok::r_paren : tok::r_brace, 786 Toks, /*StopAtSemi=*/true)) { 787 Diag(Tok, IsLParen ? diag::err_expected_rparen : 788 diag::err_expected_rbrace); 789 Diag(OpenLoc, diag::note_matching) << (IsLParen ? "(" : "{"); 790 return true; 791 } 792 793 // Grab pack ellipsis, if present. 794 if (Tok.is(tok::ellipsis)) { 795 Toks.push_back(Tok); 796 ConsumeToken(); 797 } 798 799 // If we know we just consumed a mem-initializer, we must have ',' or '{' 800 // next. 801 if (Tok.is(tok::comma)) { 802 Toks.push_back(Tok); 803 ConsumeToken(); 804 } else if (Tok.is(tok::l_brace)) { 805 // This is the function body if the ')' or '}' is immediately followed by 806 // a '{'. That cannot happen within a template argument, apart from the 807 // case where a template argument contains a compound literal: 808 // 809 // S ( ) : a < b < c > ( d ) { } 810 // // End of declaration, or still inside the template argument? 811 // 812 // ... and the case where the template argument contains a lambda: 813 // 814 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; } 815 // ( ) > ( ) { } 816 // 817 // FIXME: Disambiguate these cases. Note that the latter case is probably 818 // going to be made ill-formed by core issue 1607. 819 Toks.push_back(Tok); 820 ConsumeBrace(); 821 return false; 822 } else if (!MightBeTemplateArgument) { 823 return Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma); 824 } 825 } 826 } 827 828 /// \brief Consume and store tokens from the '?' to the ':' in a conditional 829 /// expression. 830 bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) { 831 // Consume '?'. 832 assert(Tok.is(tok::question)); 833 Toks.push_back(Tok); 834 ConsumeToken(); 835 836 while (Tok.isNot(tok::colon)) { 837 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks, /*StopAtSemi*/true, 838 /*ConsumeFinalToken*/false)) 839 return false; 840 841 // If we found a nested conditional, consume it. 842 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks)) 843 return false; 844 } 845 846 // Consume ':'. 847 Toks.push_back(Tok); 848 ConsumeToken(); 849 return true; 850 } 851 852 /// \brief A tentative parsing action that can also revert token annotations. 853 class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction { 854 public: 855 explicit UnannotatedTentativeParsingAction(Parser &Self, 856 tok::TokenKind EndKind) 857 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) { 858 // Stash away the old token stream, so we can restore it once the 859 // tentative parse is complete. 860 TentativeParsingAction Inner(Self); 861 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false); 862 Inner.Revert(); 863 } 864 865 void RevertAnnotations() { 866 Revert(); 867 868 // Put back the original tokens. 869 Self.SkipUntil(EndKind, true, /*DontConsume*/true); 870 if (Toks.size()) { 871 Token *Buffer = new Token[Toks.size()]; 872 std::copy(Toks.begin() + 1, Toks.end(), Buffer); 873 Buffer[Toks.size() - 1] = Self.Tok; 874 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true); 875 876 Self.Tok = Toks.front(); 877 } 878 } 879 880 private: 881 Parser &Self; 882 CachedTokens Toks; 883 tok::TokenKind EndKind; 884 }; 885 886 /// ConsumeAndStoreInitializer - Consume and store the token at the passed token 887 /// container until the end of the current initializer expression (either a 888 /// default argument or an in-class initializer for a non-static data member). 889 /// The final token is not consumed. 890 bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks, 891 CachedInitKind CIK) { 892 // We always want this function to consume at least one token if not at EOF. 893 bool IsFirstTokenConsumed = true; 894 895 // Number of possible unclosed <s we've seen so far. These might be templates, 896 // and might not, but if there were none of them (or we know for sure that 897 // we're within a template), we can avoid a tentative parse. 898 unsigned AngleCount = 0; 899 unsigned KnownTemplateCount = 0; 900 901 while (1) { 902 switch (Tok.getKind()) { 903 case tok::comma: 904 // If we might be in a template, perform a tentative parse to check. 905 if (!AngleCount) 906 // Not a template argument: this is the end of the initializer. 907 return true; 908 if (KnownTemplateCount) 909 goto consume_token; 910 911 // We hit a comma inside angle brackets. This is the hard case. The 912 // rule we follow is: 913 // * For a default argument, if the tokens after the comma form a 914 // syntactically-valid parameter-declaration-clause, in which each 915 // parameter has an initializer, then this comma ends the default 916 // argument. 917 // * For a default initializer, if the tokens after the comma form a 918 // syntactically-valid init-declarator-list, then this comma ends 919 // the default initializer. 920 { 921 UnannotatedTentativeParsingAction PA(*this, 922 CIK == CIK_DefaultInitializer 923 ? tok::semi : tok::r_paren); 924 Sema::TentativeAnalysisScope Scope(Actions); 925 926 TPResult Result = TPResult::Error(); 927 ConsumeToken(); 928 switch (CIK) { 929 case CIK_DefaultInitializer: 930 Result = TryParseInitDeclaratorList(); 931 // If we parsed a complete, ambiguous init-declarator-list, this 932 // is only syntactically-valid if it's followed by a semicolon. 933 if (Result == TPResult::Ambiguous() && Tok.isNot(tok::semi)) 934 Result = TPResult::False(); 935 break; 936 937 case CIK_DefaultArgument: 938 bool InvalidAsDeclaration = false; 939 Result = TryParseParameterDeclarationClause( 940 &InvalidAsDeclaration, /*VersusTemplateArgument*/true); 941 // If this is an expression or a declaration with a missing 942 // 'typename', assume it's not a declaration. 943 if (Result == TPResult::Ambiguous() && InvalidAsDeclaration) 944 Result = TPResult::False(); 945 break; 946 } 947 948 // If what follows could be a declaration, it is a declaration. 949 if (Result != TPResult::False() && Result != TPResult::Error()) { 950 PA.Revert(); 951 return true; 952 } 953 954 // In the uncommon case that we decide the following tokens are part 955 // of a template argument, revert any annotations we've performed in 956 // those tokens. We're not going to look them up until we've parsed 957 // the rest of the class, and that might add more declarations. 958 PA.RevertAnnotations(); 959 } 960 961 // Keep going. We know we're inside a template argument list now. 962 ++KnownTemplateCount; 963 goto consume_token; 964 965 case tok::eof: 966 // Ran out of tokens. 967 return false; 968 969 case tok::less: 970 // FIXME: A '<' can only start a template-id if it's preceded by an 971 // identifier, an operator-function-id, or a literal-operator-id. 972 ++AngleCount; 973 goto consume_token; 974 975 case tok::question: 976 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does, 977 // that is *never* the end of the initializer. Skip to the ':'. 978 if (!ConsumeAndStoreConditional(Toks)) 979 return false; 980 break; 981 982 case tok::greatergreatergreater: 983 if (!getLangOpts().CPlusPlus11) 984 goto consume_token; 985 if (AngleCount) --AngleCount; 986 if (KnownTemplateCount) --KnownTemplateCount; 987 // Fall through. 988 case tok::greatergreater: 989 if (!getLangOpts().CPlusPlus11) 990 goto consume_token; 991 if (AngleCount) --AngleCount; 992 if (KnownTemplateCount) --KnownTemplateCount; 993 // Fall through. 994 case tok::greater: 995 if (AngleCount) --AngleCount; 996 if (KnownTemplateCount) --KnownTemplateCount; 997 goto consume_token; 998 999 case tok::kw_template: 1000 // 'template' identifier '<' is known to start a template argument list, 1001 // and can be used to disambiguate the parse. 1002 // FIXME: Support all forms of 'template' unqualified-id '<'. 1003 Toks.push_back(Tok); 1004 ConsumeToken(); 1005 if (Tok.is(tok::identifier)) { 1006 Toks.push_back(Tok); 1007 ConsumeToken(); 1008 if (Tok.is(tok::less)) { 1009 ++KnownTemplateCount; 1010 Toks.push_back(Tok); 1011 ConsumeToken(); 1012 } 1013 } 1014 break; 1015 1016 case tok::kw_operator: 1017 // If 'operator' precedes other punctuation, that punctuation loses 1018 // its special behavior. 1019 Toks.push_back(Tok); 1020 ConsumeToken(); 1021 switch (Tok.getKind()) { 1022 case tok::comma: 1023 case tok::greatergreatergreater: 1024 case tok::greatergreater: 1025 case tok::greater: 1026 case tok::less: 1027 Toks.push_back(Tok); 1028 ConsumeToken(); 1029 break; 1030 default: 1031 break; 1032 } 1033 break; 1034 1035 case tok::l_paren: 1036 // Recursively consume properly-nested parens. 1037 Toks.push_back(Tok); 1038 ConsumeParen(); 1039 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); 1040 break; 1041 case tok::l_square: 1042 // Recursively consume properly-nested square brackets. 1043 Toks.push_back(Tok); 1044 ConsumeBracket(); 1045 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false); 1046 break; 1047 case tok::l_brace: 1048 // Recursively consume properly-nested braces. 1049 Toks.push_back(Tok); 1050 ConsumeBrace(); 1051 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 1052 break; 1053 1054 // Okay, we found a ']' or '}' or ')', which we think should be balanced. 1055 // Since the user wasn't looking for this token (if they were, it would 1056 // already be handled), this isn't balanced. If there is a LHS token at a 1057 // higher level, we will assume that this matches the unbalanced token 1058 // and return it. Otherwise, this is a spurious RHS token, which we skip. 1059 case tok::r_paren: 1060 if (CIK == CIK_DefaultArgument) 1061 return true; // End of the default argument. 1062 if (ParenCount && !IsFirstTokenConsumed) 1063 return false; // Matches something. 1064 goto consume_token; 1065 case tok::r_square: 1066 if (BracketCount && !IsFirstTokenConsumed) 1067 return false; // Matches something. 1068 goto consume_token; 1069 case tok::r_brace: 1070 if (BraceCount && !IsFirstTokenConsumed) 1071 return false; // Matches something. 1072 goto consume_token; 1073 1074 case tok::code_completion: 1075 Toks.push_back(Tok); 1076 ConsumeCodeCompletionToken(); 1077 break; 1078 1079 case tok::string_literal: 1080 case tok::wide_string_literal: 1081 case tok::utf8_string_literal: 1082 case tok::utf16_string_literal: 1083 case tok::utf32_string_literal: 1084 Toks.push_back(Tok); 1085 ConsumeStringToken(); 1086 break; 1087 case tok::semi: 1088 if (CIK == CIK_DefaultInitializer) 1089 return true; // End of the default initializer. 1090 // FALL THROUGH. 1091 default: 1092 consume_token: 1093 Toks.push_back(Tok); 1094 ConsumeToken(); 1095 break; 1096 } 1097 IsFirstTokenConsumed = false; 1098 } 1099 } 1100