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