1 //===--- ParseCXXInlineMethods.cpp - C++ class inline methods parsing------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements parsing for C++ class inline methods. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Parse/Parser.h" 14 #include "clang/AST/DeclTemplate.h" 15 #include "clang/Parse/ParseDiagnostic.h" 16 #include "clang/Parse/RAIIObjectsForParser.h" 17 #include "clang/Sema/DeclSpec.h" 18 #include "clang/Sema/Scope.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 NamedDecl *Parser::ParseCXXInlineMethodDef( 25 AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D, 26 const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS, 27 SourceLocation PureSpecLoc) { 28 assert(D.isFunctionDeclarator() && "This isn't a function declarator!"); 29 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) && 30 "Current token not a '{', ':', '=', or 'try'!"); 31 32 MultiTemplateParamsArg TemplateParams( 33 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() 34 : nullptr, 35 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0); 36 37 NamedDecl *FnD; 38 if (D.getDeclSpec().isFriendSpecified()) 39 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D, 40 TemplateParams); 41 else { 42 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D, 43 TemplateParams, nullptr, 44 VS, ICIS_NoInit); 45 if (FnD) { 46 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs); 47 if (PureSpecLoc.isValid()) 48 Actions.ActOnPureSpecifier(FnD, PureSpecLoc); 49 } 50 } 51 52 if (FnD) 53 HandleMemberFunctionDeclDelays(D, FnD); 54 55 D.complete(FnD); 56 57 if (TryConsumeToken(tok::equal)) { 58 if (!FnD) { 59 SkipUntil(tok::semi); 60 return nullptr; 61 } 62 63 bool Delete = false; 64 SourceLocation KWLoc; 65 SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1); 66 if (TryConsumeToken(tok::kw_delete, KWLoc)) { 67 Diag(KWLoc, getLangOpts().CPlusPlus11 68 ? diag::warn_cxx98_compat_defaulted_deleted_function 69 : diag::ext_defaulted_deleted_function) 70 << 1 /* deleted */; 71 Actions.SetDeclDeleted(FnD, KWLoc); 72 Delete = true; 73 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) { 74 DeclAsFunction->setRangeEnd(KWEndLoc); 75 } 76 } else if (TryConsumeToken(tok::kw_default, KWLoc)) { 77 Diag(KWLoc, getLangOpts().CPlusPlus11 78 ? diag::warn_cxx98_compat_defaulted_deleted_function 79 : diag::ext_defaulted_deleted_function) 80 << 0 /* defaulted */; 81 Actions.SetDeclDefaulted(FnD, KWLoc); 82 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) { 83 DeclAsFunction->setRangeEnd(KWEndLoc); 84 } 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 if (SkipFunctionBodies && (!FnD || Actions.canSkipFunctionBody(FnD)) && 102 trySkippingFunctionBody()) { 103 Actions.ActOnSkippedFunctionBody(FnD); 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 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Definition && 112 !D.getDeclSpec().hasConstexprSpecifier() && 113 !(FnD && FnD->getAsFunction() && 114 FnD->getAsFunction()->getReturnType()->getContainedAutoType()) && 115 ((Actions.CurContext->isDependentContext() || 116 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 117 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) && 118 !Actions.IsInsideALocalClassWithinATemplateFunction())) { 119 120 CachedTokens Toks; 121 LexTemplateFunctionForLateParsing(Toks); 122 123 if (FnD) { 124 FunctionDecl *FD = FnD->getAsFunction(); 125 Actions.CheckForFunctionRedefinition(FD); 126 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks); 127 } 128 129 return FnD; 130 } 131 132 // Consume the tokens and store them for later parsing. 133 134 LexedMethod* LM = new LexedMethod(this, FnD); 135 getCurrentClass().LateParsedDeclarations.push_back(LM); 136 CachedTokens &Toks = LM->Toks; 137 138 tok::TokenKind kind = Tok.getKind(); 139 // Consume everything up to (and including) the left brace of the 140 // function body. 141 if (ConsumeAndStoreFunctionPrologue(Toks)) { 142 // We didn't find the left-brace we expected after the 143 // constructor initializer; we already printed an error, and it's likely 144 // impossible to recover, so don't try to parse this method later. 145 // Skip over the rest of the decl and back to somewhere that looks 146 // reasonable. 147 SkipMalformedDecl(); 148 delete getCurrentClass().LateParsedDeclarations.back(); 149 getCurrentClass().LateParsedDeclarations.pop_back(); 150 return FnD; 151 } else { 152 // Consume everything up to (and including) the matching right brace. 153 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 154 } 155 156 // If we're in a function-try-block, we need to store all the catch blocks. 157 if (kind == tok::kw_try) { 158 while (Tok.is(tok::kw_catch)) { 159 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false); 160 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 161 } 162 } 163 164 if (FnD) { 165 FunctionDecl *FD = FnD->getAsFunction(); 166 // Track that this function will eventually have a body; Sema needs 167 // to know this. 168 Actions.CheckForFunctionRedefinition(FD); 169 FD->setWillHaveBody(true); 170 } else { 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.isOneOf(tok::l_brace, 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 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer); 209 } 210 211 // Store an artificial EOF token to ensure that we don't run off the end of 212 // the initializer when we come to parse it. 213 Token Eof; 214 Eof.startToken(); 215 Eof.setKind(tok::eof); 216 Eof.setLocation(Tok.getLocation()); 217 Eof.setEofData(VarD); 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 void Parser::LateParsedDeclaration::ParseLexedAttributes() {} 226 void Parser::LateParsedDeclaration::ParseLexedPragmas() {} 227 228 Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C) 229 : Self(P), Class(C) {} 230 231 Parser::LateParsedClass::~LateParsedClass() { 232 Self->DeallocateParsedClasses(Class); 233 } 234 235 void Parser::LateParsedClass::ParseLexedMethodDeclarations() { 236 Self->ParseLexedMethodDeclarations(*Class); 237 } 238 239 void Parser::LateParsedClass::ParseLexedMemberInitializers() { 240 Self->ParseLexedMemberInitializers(*Class); 241 } 242 243 void Parser::LateParsedClass::ParseLexedMethodDefs() { 244 Self->ParseLexedMethodDefs(*Class); 245 } 246 247 void Parser::LateParsedClass::ParseLexedAttributes() { 248 Self->ParseLexedAttributes(*Class); 249 } 250 251 void Parser::LateParsedClass::ParseLexedPragmas() { 252 Self->ParseLexedPragmas(*Class); 253 } 254 255 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() { 256 Self->ParseLexedMethodDeclaration(*this); 257 } 258 259 void Parser::LexedMethod::ParseLexedMethodDefs() { 260 Self->ParseLexedMethodDef(*this); 261 } 262 263 void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() { 264 Self->ParseLexedMemberInitializer(*this); 265 } 266 267 void Parser::LateParsedAttribute::ParseLexedAttributes() { 268 Self->ParseLexedAttribute(*this, true, false); 269 } 270 271 void Parser::LateParsedPragma::ParseLexedPragmas() { 272 Self->ParseLexedPragma(*this); 273 } 274 275 /// Utility to re-enter a possibly-templated scope while parsing its 276 /// late-parsed components. 277 struct Parser::ReenterTemplateScopeRAII { 278 Parser &P; 279 MultiParseScope Scopes; 280 TemplateParameterDepthRAII CurTemplateDepthTracker; 281 282 ReenterTemplateScopeRAII(Parser &P, Decl *MaybeTemplated, bool Enter = true) 283 : P(P), Scopes(P), CurTemplateDepthTracker(P.TemplateParameterDepth) { 284 if (Enter) { 285 CurTemplateDepthTracker.addDepth( 286 P.ReenterTemplateScopes(Scopes, MaybeTemplated)); 287 } 288 } 289 }; 290 291 /// Utility to re-enter a class scope while parsing its late-parsed components. 292 struct Parser::ReenterClassScopeRAII : ReenterTemplateScopeRAII { 293 ParsingClass &Class; 294 295 ReenterClassScopeRAII(Parser &P, ParsingClass &Class) 296 : ReenterTemplateScopeRAII(P, Class.TagOrTemplate, 297 /*Enter=*/!Class.TopLevelClass), 298 Class(Class) { 299 // If this is the top-level class, we're still within its scope. 300 if (Class.TopLevelClass) 301 return; 302 303 // Re-enter the class scope itself. 304 Scopes.Enter(Scope::ClassScope|Scope::DeclScope); 305 P.Actions.ActOnStartDelayedMemberDeclarations(P.getCurScope(), 306 Class.TagOrTemplate); 307 } 308 ~ReenterClassScopeRAII() { 309 if (Class.TopLevelClass) 310 return; 311 312 P.Actions.ActOnFinishDelayedMemberDeclarations(P.getCurScope(), 313 Class.TagOrTemplate); 314 } 315 }; 316 317 /// ParseLexedMethodDeclarations - We finished parsing the member 318 /// specification of a top (non-nested) C++ class. Now go over the 319 /// stack of method declarations with some parts for which parsing was 320 /// delayed (such as default arguments) and parse them. 321 void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) { 322 ReenterClassScopeRAII InClassScope(*this, Class); 323 324 for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations) 325 LateD->ParseLexedMethodDeclarations(); 326 } 327 328 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) { 329 // If this is a member template, introduce the template parameter scope. 330 ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.Method); 331 332 // Start the delayed C++ method declaration 333 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method); 334 335 // Introduce the parameters into scope and parse their default 336 // arguments. 337 InFunctionTemplateScope.Scopes.Enter(Scope::FunctionPrototypeScope | 338 Scope::FunctionDeclarationScope | 339 Scope::DeclScope); 340 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) { 341 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param); 342 // Introduce the parameter into scope. 343 bool HasUnparsed = Param->hasUnparsedDefaultArg(); 344 Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param); 345 std::unique_ptr<CachedTokens> Toks = std::move(LM.DefaultArgs[I].Toks); 346 if (Toks) { 347 ParenBraceBracketBalancer BalancerRAIIObj(*this); 348 349 // Mark the end of the default argument so that we know when to stop when 350 // we parse it later on. 351 Token LastDefaultArgToken = Toks->back(); 352 Token DefArgEnd; 353 DefArgEnd.startToken(); 354 DefArgEnd.setKind(tok::eof); 355 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc()); 356 DefArgEnd.setEofData(Param); 357 Toks->push_back(DefArgEnd); 358 359 // Parse the default argument from its saved token stream. 360 Toks->push_back(Tok); // So that the current token doesn't get lost 361 PP.EnterTokenStream(*Toks, true, /*IsReinject*/ true); 362 363 // Consume the previously-pushed token. 364 ConsumeAnyToken(); 365 366 // Consume the '='. 367 assert(Tok.is(tok::equal) && "Default argument not starting with '='"); 368 SourceLocation EqualLoc = ConsumeToken(); 369 370 // The argument isn't actually potentially evaluated unless it is 371 // used. 372 EnterExpressionEvaluationContext Eval( 373 Actions, 374 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, Param); 375 376 ExprResult DefArgResult; 377 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 378 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 379 DefArgResult = ParseBraceInitializer(); 380 } else 381 DefArgResult = ParseAssignmentExpression(); 382 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult); 383 if (DefArgResult.isInvalid()) { 384 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); 385 } else { 386 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) { 387 // The last two tokens are the terminator and the saved value of 388 // Tok; the last token in the default argument is the one before 389 // those. 390 assert(Toks->size() >= 3 && "expected a token in default arg"); 391 Diag(Tok.getLocation(), diag::err_default_arg_unparsed) 392 << SourceRange(Tok.getLocation(), 393 (*Toks)[Toks->size() - 3].getLocation()); 394 } 395 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 396 DefArgResult.get()); 397 } 398 399 // There could be leftover tokens (e.g. because of an error). 400 // Skip through until we reach the 'end of default argument' token. 401 while (Tok.isNot(tok::eof)) 402 ConsumeAnyToken(); 403 404 if (Tok.is(tok::eof) && Tok.getEofData() == Param) 405 ConsumeAnyToken(); 406 } else if (HasUnparsed) { 407 assert(Param->hasInheritedDefaultArg()); 408 const FunctionDecl *Old; 409 if (const auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(LM.Method)) 410 Old = 411 cast<FunctionDecl>(FunTmpl->getTemplatedDecl())->getPreviousDecl(); 412 else 413 Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl(); 414 if (Old) { 415 ParmVarDecl *OldParam = const_cast<ParmVarDecl*>(Old->getParamDecl(I)); 416 assert(!OldParam->hasUnparsedDefaultArg()); 417 if (OldParam->hasUninstantiatedDefaultArg()) 418 Param->setUninstantiatedDefaultArg( 419 OldParam->getUninstantiatedDefaultArg()); 420 else 421 Param->setDefaultArg(OldParam->getInit()); 422 } 423 } 424 } 425 426 // Parse a delayed exception-specification, if there is one. 427 if (CachedTokens *Toks = LM.ExceptionSpecTokens) { 428 ParenBraceBracketBalancer BalancerRAIIObj(*this); 429 430 // Add the 'stop' token. 431 Token LastExceptionSpecToken = Toks->back(); 432 Token ExceptionSpecEnd; 433 ExceptionSpecEnd.startToken(); 434 ExceptionSpecEnd.setKind(tok::eof); 435 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc()); 436 ExceptionSpecEnd.setEofData(LM.Method); 437 Toks->push_back(ExceptionSpecEnd); 438 439 // Parse the default argument from its saved token stream. 440 Toks->push_back(Tok); // So that the current token doesn't get lost 441 PP.EnterTokenStream(*Toks, true, /*IsReinject*/true); 442 443 // Consume the previously-pushed token. 444 ConsumeAnyToken(); 445 446 // C++11 [expr.prim.general]p3: 447 // If a declaration declares a member function or member function 448 // template of a class X, the expression this is a prvalue of type 449 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 450 // and the end of the function-definition, member-declarator, or 451 // declarator. 452 CXXMethodDecl *Method; 453 if (FunctionTemplateDecl *FunTmpl 454 = dyn_cast<FunctionTemplateDecl>(LM.Method)) 455 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 456 else 457 Method = dyn_cast<CXXMethodDecl>(LM.Method); 458 459 Sema::CXXThisScopeRAII ThisScope( 460 Actions, Method ? Method->getParent() : nullptr, 461 Method ? Method->getMethodQualifiers() : Qualifiers{}, 462 Method && getLangOpts().CPlusPlus11); 463 464 // Parse the exception-specification. 465 SourceRange SpecificationRange; 466 SmallVector<ParsedType, 4> DynamicExceptions; 467 SmallVector<SourceRange, 4> DynamicExceptionRanges; 468 ExprResult NoexceptExpr; 469 CachedTokens *ExceptionSpecTokens; 470 471 ExceptionSpecificationType EST 472 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange, 473 DynamicExceptions, 474 DynamicExceptionRanges, NoexceptExpr, 475 ExceptionSpecTokens); 476 477 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method) 478 Diag(Tok.getLocation(), diag::err_except_spec_unparsed); 479 480 // Attach the exception-specification to the method. 481 Actions.actOnDelayedExceptionSpecification(LM.Method, EST, 482 SpecificationRange, 483 DynamicExceptions, 484 DynamicExceptionRanges, 485 NoexceptExpr.isUsable()? 486 NoexceptExpr.get() : nullptr); 487 488 // There could be leftover tokens (e.g. because of an error). 489 // Skip through until we reach the original token position. 490 while (Tok.isNot(tok::eof)) 491 ConsumeAnyToken(); 492 493 // Clean up the remaining EOF token. 494 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method) 495 ConsumeAnyToken(); 496 497 delete Toks; 498 LM.ExceptionSpecTokens = nullptr; 499 } 500 501 InFunctionTemplateScope.Scopes.Exit(); 502 503 // Finish the delayed C++ method declaration. 504 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method); 505 } 506 507 /// ParseLexedMethodDefs - We finished parsing the member specification of a top 508 /// (non-nested) C++ class. Now go over the stack of lexed methods that were 509 /// collected during its parsing and parse them all. 510 void Parser::ParseLexedMethodDefs(ParsingClass &Class) { 511 ReenterClassScopeRAII InClassScope(*this, Class); 512 513 for (LateParsedDeclaration *D : Class.LateParsedDeclarations) 514 D->ParseLexedMethodDefs(); 515 } 516 517 void Parser::ParseLexedMethodDef(LexedMethod &LM) { 518 // If this is a member template, introduce the template parameter scope. 519 ReenterTemplateScopeRAII InFunctionTemplateScope(*this, LM.D); 520 521 ParenBraceBracketBalancer BalancerRAIIObj(*this); 522 523 assert(!LM.Toks.empty() && "Empty body!"); 524 Token LastBodyToken = LM.Toks.back(); 525 Token BodyEnd; 526 BodyEnd.startToken(); 527 BodyEnd.setKind(tok::eof); 528 BodyEnd.setLocation(LastBodyToken.getEndLoc()); 529 BodyEnd.setEofData(LM.D); 530 LM.Toks.push_back(BodyEnd); 531 // Append the current token at the end of the new token stream so that it 532 // doesn't get lost. 533 LM.Toks.push_back(Tok); 534 PP.EnterTokenStream(LM.Toks, true, /*IsReinject*/true); 535 536 // Consume the previously pushed token. 537 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 538 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) 539 && "Inline method not starting with '{', ':' or 'try'"); 540 541 // Parse the method body. Function body parsing code is similar enough 542 // to be re-used for method bodies as well. 543 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope | 544 Scope::CompoundStmtScope); 545 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D); 546 547 if (Tok.is(tok::kw_try)) { 548 ParseFunctionTryBlock(LM.D, FnScope); 549 550 while (Tok.isNot(tok::eof)) 551 ConsumeAnyToken(); 552 553 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D) 554 ConsumeAnyToken(); 555 return; 556 } 557 if (Tok.is(tok::colon)) { 558 ParseConstructorInitializer(LM.D); 559 560 // Error recovery. 561 if (!Tok.is(tok::l_brace)) { 562 FnScope.Exit(); 563 Actions.ActOnFinishFunctionBody(LM.D, nullptr); 564 565 while (Tok.isNot(tok::eof)) 566 ConsumeAnyToken(); 567 568 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D) 569 ConsumeAnyToken(); 570 return; 571 } 572 } else 573 Actions.ActOnDefaultCtorInitializers(LM.D); 574 575 assert((Actions.getDiagnostics().hasErrorOccurred() || 576 !isa<FunctionTemplateDecl>(LM.D) || 577 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth() 578 < TemplateParameterDepth) && 579 "TemplateParameterDepth should be greater than the depth of " 580 "current template being instantiated!"); 581 582 ParseFunctionStatementBody(LM.D, FnScope); 583 584 while (Tok.isNot(tok::eof)) 585 ConsumeAnyToken(); 586 587 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D) 588 ConsumeAnyToken(); 589 590 if (auto *FD = dyn_cast_or_null<FunctionDecl>(LM.D)) 591 if (isa<CXXMethodDecl>(FD) || 592 FD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)) 593 Actions.ActOnFinishInlineFunctionDef(FD); 594 } 595 596 /// ParseLexedMemberInitializers - We finished parsing the member specification 597 /// of a top (non-nested) C++ class. Now go over the stack of lexed data member 598 /// initializers that were collected during its parsing and parse them all. 599 void Parser::ParseLexedMemberInitializers(ParsingClass &Class) { 600 ReenterClassScopeRAII InClassScope(*this, Class); 601 602 if (!Class.LateParsedDeclarations.empty()) { 603 // C++11 [expr.prim.general]p4: 604 // Otherwise, if a member-declarator declares a non-static data member 605 // (9.2) of a class X, the expression this is a prvalue of type "pointer 606 // to X" within the optional brace-or-equal-initializer. It shall not 607 // appear elsewhere in the member-declarator. 608 // FIXME: This should be done in ParseLexedMemberInitializer, not here. 609 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate, 610 Qualifiers()); 611 612 for (LateParsedDeclaration *D : Class.LateParsedDeclarations) 613 D->ParseLexedMemberInitializers(); 614 } 615 616 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate); 617 } 618 619 void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) { 620 if (!MI.Field || MI.Field->isInvalidDecl()) 621 return; 622 623 ParenBraceBracketBalancer BalancerRAIIObj(*this); 624 625 // Append the current token at the end of the new token stream so that it 626 // doesn't get lost. 627 MI.Toks.push_back(Tok); 628 PP.EnterTokenStream(MI.Toks, true, /*IsReinject*/true); 629 630 // Consume the previously pushed token. 631 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 632 633 SourceLocation EqualLoc; 634 635 Actions.ActOnStartCXXInClassMemberInitializer(); 636 637 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false, 638 EqualLoc); 639 640 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc, 641 Init.get()); 642 643 // The next token should be our artificial terminating EOF token. 644 if (Tok.isNot(tok::eof)) { 645 if (!Init.isInvalid()) { 646 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation); 647 if (!EndLoc.isValid()) 648 EndLoc = Tok.getLocation(); 649 // No fixit; we can't recover as if there were a semicolon here. 650 Diag(EndLoc, diag::err_expected_semi_decl_list); 651 } 652 653 // Consume tokens until we hit the artificial EOF. 654 while (Tok.isNot(tok::eof)) 655 ConsumeAnyToken(); 656 } 657 // Make sure this is *our* artificial EOF token. 658 if (Tok.getEofData() == MI.Field) 659 ConsumeAnyToken(); 660 } 661 662 /// Wrapper class which calls ParseLexedAttribute, after setting up the 663 /// scope appropriately. 664 void Parser::ParseLexedAttributes(ParsingClass &Class) { 665 ReenterClassScopeRAII InClassScope(*this, Class); 666 667 for (LateParsedDeclaration *LateD : Class.LateParsedDeclarations) 668 LateD->ParseLexedAttributes(); 669 } 670 671 /// Parse all attributes in LAs, and attach them to Decl D. 672 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, 673 bool EnterScope, bool OnDefinition) { 674 assert(LAs.parseSoon() && 675 "Attribute list should be marked for immediate parsing."); 676 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) { 677 if (D) 678 LAs[i]->addDecl(D); 679 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition); 680 delete LAs[i]; 681 } 682 LAs.clear(); 683 } 684 685 /// Finish parsing an attribute for which parsing was delayed. 686 /// This will be called at the end of parsing a class declaration 687 /// for each LateParsedAttribute. We consume the saved tokens and 688 /// create an attribute with the arguments filled in. We add this 689 /// to the Attribute list for the decl. 690 void Parser::ParseLexedAttribute(LateParsedAttribute &LA, 691 bool EnterScope, bool OnDefinition) { 692 // Create a fake EOF so that attribute parsing won't go off the end of the 693 // attribute. 694 Token AttrEnd; 695 AttrEnd.startToken(); 696 AttrEnd.setKind(tok::eof); 697 AttrEnd.setLocation(Tok.getLocation()); 698 AttrEnd.setEofData(LA.Toks.data()); 699 LA.Toks.push_back(AttrEnd); 700 701 // Append the current token at the end of the new token stream so that it 702 // doesn't get lost. 703 LA.Toks.push_back(Tok); 704 PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true); 705 // Consume the previously pushed token. 706 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 707 708 ParsedAttributes Attrs(AttrFactory); 709 SourceLocation endLoc; 710 711 if (LA.Decls.size() > 0) { 712 Decl *D = LA.Decls[0]; 713 NamedDecl *ND = dyn_cast<NamedDecl>(D); 714 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext()); 715 716 // Allow 'this' within late-parsed attributes. 717 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(), 718 ND && ND->isCXXInstanceMember()); 719 720 if (LA.Decls.size() == 1) { 721 // If the Decl is templatized, add template parameters to scope. 722 ReenterTemplateScopeRAII InDeclScope(*this, D, EnterScope); 723 724 // If the Decl is on a function, add function parameters to the scope. 725 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate(); 726 if (HasFunScope) { 727 InDeclScope.Scopes.Enter(Scope::FnScope | Scope::DeclScope | 728 Scope::CompoundStmtScope); 729 Actions.ActOnReenterFunctionContext(Actions.CurScope, D); 730 } 731 732 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc, 733 nullptr, SourceLocation(), ParsedAttr::AS_GNU, 734 nullptr); 735 736 if (HasFunScope) 737 Actions.ActOnExitFunctionContext(); 738 } else { 739 // If there are multiple decls, then the decl cannot be within the 740 // function scope. 741 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc, 742 nullptr, SourceLocation(), ParsedAttr::AS_GNU, 743 nullptr); 744 } 745 } else { 746 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName(); 747 } 748 749 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() && 750 Attrs.begin()->isKnownToGCC()) 751 Diag(Tok, diag::warn_attribute_on_function_definition) 752 << &LA.AttrName; 753 754 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) 755 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs); 756 757 // Due to a parsing error, we either went over the cached tokens or 758 // there are still cached tokens left, so we skip the leftover tokens. 759 while (Tok.isNot(tok::eof)) 760 ConsumeAnyToken(); 761 762 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()) 763 ConsumeAnyToken(); 764 } 765 766 void Parser::ParseLexedPragmas(ParsingClass &Class) { 767 ReenterClassScopeRAII InClassScope(*this, Class); 768 769 for (LateParsedDeclaration *D : Class.LateParsedDeclarations) 770 D->ParseLexedPragmas(); 771 } 772 773 void Parser::ParseLexedPragma(LateParsedPragma &LP) { 774 PP.EnterToken(Tok, /*IsReinject=*/true); 775 PP.EnterTokenStream(LP.toks(), /*DisableMacroExpansion=*/true, 776 /*IsReinject=*/true); 777 778 // Consume the previously pushed token. 779 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 780 assert(Tok.isAnnotation() && "Expected annotation token."); 781 switch (Tok.getKind()) { 782 case tok::annot_attr_openmp: 783 case tok::annot_pragma_openmp: { 784 AccessSpecifier AS = LP.getAccessSpecifier(); 785 ParsedAttributesWithRange Attrs(AttrFactory); 786 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs); 787 break; 788 } 789 default: 790 llvm_unreachable("Unexpected token."); 791 } 792 } 793 794 /// ConsumeAndStoreUntil - Consume and store the token at the passed token 795 /// container until the token 'T' is reached (which gets 796 /// consumed/stored too, if ConsumeFinalToken). 797 /// If StopAtSemi is true, then we will stop early at a ';' character. 798 /// Returns true if token 'T1' or 'T2' was found. 799 /// NOTE: This is a specialized version of Parser::SkipUntil. 800 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, 801 CachedTokens &Toks, 802 bool StopAtSemi, bool ConsumeFinalToken) { 803 // We always want this function to consume at least one token if the first 804 // token isn't T and if not at EOF. 805 bool isFirstTokenConsumed = true; 806 while (1) { 807 // If we found one of the tokens, stop and return true. 808 if (Tok.is(T1) || Tok.is(T2)) { 809 if (ConsumeFinalToken) { 810 Toks.push_back(Tok); 811 ConsumeAnyToken(); 812 } 813 return true; 814 } 815 816 switch (Tok.getKind()) { 817 case tok::eof: 818 case tok::annot_module_begin: 819 case tok::annot_module_end: 820 case tok::annot_module_include: 821 // Ran out of tokens. 822 return false; 823 824 case tok::l_paren: 825 // Recursively consume properly-nested parens. 826 Toks.push_back(Tok); 827 ConsumeParen(); 828 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); 829 break; 830 case tok::l_square: 831 // Recursively consume properly-nested square brackets. 832 Toks.push_back(Tok); 833 ConsumeBracket(); 834 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false); 835 break; 836 case tok::l_brace: 837 // Recursively consume properly-nested braces. 838 Toks.push_back(Tok); 839 ConsumeBrace(); 840 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 841 break; 842 843 // Okay, we found a ']' or '}' or ')', which we think should be balanced. 844 // Since the user wasn't looking for this token (if they were, it would 845 // already be handled), this isn't balanced. If there is a LHS token at a 846 // higher level, we will assume that this matches the unbalanced token 847 // and return it. Otherwise, this is a spurious RHS token, which we skip. 848 case tok::r_paren: 849 if (ParenCount && !isFirstTokenConsumed) 850 return false; // Matches something. 851 Toks.push_back(Tok); 852 ConsumeParen(); 853 break; 854 case tok::r_square: 855 if (BracketCount && !isFirstTokenConsumed) 856 return false; // Matches something. 857 Toks.push_back(Tok); 858 ConsumeBracket(); 859 break; 860 case tok::r_brace: 861 if (BraceCount && !isFirstTokenConsumed) 862 return false; // Matches something. 863 Toks.push_back(Tok); 864 ConsumeBrace(); 865 break; 866 867 case tok::semi: 868 if (StopAtSemi) 869 return false; 870 LLVM_FALLTHROUGH; 871 default: 872 // consume this token. 873 Toks.push_back(Tok); 874 ConsumeAnyToken(/*ConsumeCodeCompletionTok*/true); 875 break; 876 } 877 isFirstTokenConsumed = false; 878 } 879 } 880 881 /// Consume tokens and store them in the passed token container until 882 /// we've passed the try keyword and constructor initializers and have consumed 883 /// the opening brace of the function body. The opening brace will be consumed 884 /// if and only if there was no error. 885 /// 886 /// \return True on error. 887 bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) { 888 if (Tok.is(tok::kw_try)) { 889 Toks.push_back(Tok); 890 ConsumeToken(); 891 } 892 893 if (Tok.isNot(tok::colon)) { 894 // Easy case, just a function body. 895 896 // Grab any remaining garbage to be diagnosed later. We stop when we reach a 897 // brace: an opening one is the function body, while a closing one probably 898 // means we've reached the end of the class. 899 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks, 900 /*StopAtSemi=*/true, 901 /*ConsumeFinalToken=*/false); 902 if (Tok.isNot(tok::l_brace)) 903 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace; 904 905 Toks.push_back(Tok); 906 ConsumeBrace(); 907 return false; 908 } 909 910 Toks.push_back(Tok); 911 ConsumeToken(); 912 913 // We can't reliably skip over a mem-initializer-id, because it could be 914 // a template-id involving not-yet-declared names. Given: 915 // 916 // S ( ) : a < b < c > ( e ) 917 // 918 // 'e' might be an initializer or part of a template argument, depending 919 // on whether 'b' is a template. 920 921 // Track whether we might be inside a template argument. We can give 922 // significantly better diagnostics if we know that we're not. 923 bool MightBeTemplateArgument = false; 924 925 while (true) { 926 // Skip over the mem-initializer-id, if possible. 927 if (Tok.is(tok::kw_decltype)) { 928 Toks.push_back(Tok); 929 SourceLocation OpenLoc = ConsumeToken(); 930 if (Tok.isNot(tok::l_paren)) 931 return Diag(Tok.getLocation(), diag::err_expected_lparen_after) 932 << "decltype"; 933 Toks.push_back(Tok); 934 ConsumeParen(); 935 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) { 936 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren; 937 Diag(OpenLoc, diag::note_matching) << tok::l_paren; 938 return true; 939 } 940 } 941 do { 942 // Walk over a component of a nested-name-specifier. 943 if (Tok.is(tok::coloncolon)) { 944 Toks.push_back(Tok); 945 ConsumeToken(); 946 947 if (Tok.is(tok::kw_template)) { 948 Toks.push_back(Tok); 949 ConsumeToken(); 950 } 951 } 952 953 if (Tok.is(tok::identifier)) { 954 Toks.push_back(Tok); 955 ConsumeToken(); 956 } else { 957 break; 958 } 959 } while (Tok.is(tok::coloncolon)); 960 961 if (Tok.is(tok::code_completion)) { 962 Toks.push_back(Tok); 963 ConsumeCodeCompletionToken(); 964 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) { 965 // Could be the start of another member initializer (the ',' has not 966 // been written yet) 967 continue; 968 } 969 } 970 971 if (Tok.is(tok::comma)) { 972 // The initialization is missing, we'll diagnose it later. 973 Toks.push_back(Tok); 974 ConsumeToken(); 975 continue; 976 } 977 if (Tok.is(tok::less)) 978 MightBeTemplateArgument = true; 979 980 if (MightBeTemplateArgument) { 981 // We may be inside a template argument list. Grab up to the start of the 982 // next parenthesized initializer or braced-init-list. This *might* be the 983 // initializer, or it might be a subexpression in the template argument 984 // list. 985 // FIXME: Count angle brackets, and clear MightBeTemplateArgument 986 // if all angles are closed. 987 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks, 988 /*StopAtSemi=*/true, 989 /*ConsumeFinalToken=*/false)) { 990 // We're not just missing the initializer, we're also missing the 991 // function body! 992 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace; 993 } 994 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) { 995 // We found something weird in a mem-initializer-id. 996 if (getLangOpts().CPlusPlus11) 997 return Diag(Tok.getLocation(), diag::err_expected_either) 998 << tok::l_paren << tok::l_brace; 999 else 1000 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren; 1001 } 1002 1003 tok::TokenKind kind = Tok.getKind(); 1004 Toks.push_back(Tok); 1005 bool IsLParen = (kind == tok::l_paren); 1006 SourceLocation OpenLoc = Tok.getLocation(); 1007 1008 if (IsLParen) { 1009 ConsumeParen(); 1010 } else { 1011 assert(kind == tok::l_brace && "Must be left paren or brace here."); 1012 ConsumeBrace(); 1013 // In C++03, this has to be the start of the function body, which 1014 // means the initializer is malformed; we'll diagnose it later. 1015 if (!getLangOpts().CPlusPlus11) 1016 return false; 1017 1018 const Token &PreviousToken = Toks[Toks.size() - 2]; 1019 if (!MightBeTemplateArgument && 1020 !PreviousToken.isOneOf(tok::identifier, tok::greater, 1021 tok::greatergreater)) { 1022 // If the opening brace is not preceded by one of these tokens, we are 1023 // missing the mem-initializer-id. In order to recover better, we need 1024 // to use heuristics to determine if this '{' is most likely the 1025 // beginning of a brace-init-list or the function body. 1026 // Check the token after the corresponding '}'. 1027 TentativeParsingAction PA(*this); 1028 if (SkipUntil(tok::r_brace) && 1029 !Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) { 1030 // Consider there was a malformed initializer and this is the start 1031 // of the function body. We'll diagnose it later. 1032 PA.Revert(); 1033 return false; 1034 } 1035 PA.Revert(); 1036 } 1037 } 1038 1039 // Grab the initializer (or the subexpression of the template argument). 1040 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false 1041 // if we might be inside the braces of a lambda-expression. 1042 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace; 1043 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) { 1044 Diag(Tok, diag::err_expected) << CloseKind; 1045 Diag(OpenLoc, diag::note_matching) << kind; 1046 return true; 1047 } 1048 1049 // Grab pack ellipsis, if present. 1050 if (Tok.is(tok::ellipsis)) { 1051 Toks.push_back(Tok); 1052 ConsumeToken(); 1053 } 1054 1055 // If we know we just consumed a mem-initializer, we must have ',' or '{' 1056 // next. 1057 if (Tok.is(tok::comma)) { 1058 Toks.push_back(Tok); 1059 ConsumeToken(); 1060 } else if (Tok.is(tok::l_brace)) { 1061 // This is the function body if the ')' or '}' is immediately followed by 1062 // a '{'. That cannot happen within a template argument, apart from the 1063 // case where a template argument contains a compound literal: 1064 // 1065 // S ( ) : a < b < c > ( d ) { } 1066 // // End of declaration, or still inside the template argument? 1067 // 1068 // ... and the case where the template argument contains a lambda: 1069 // 1070 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; } 1071 // ( ) > ( ) { } 1072 // 1073 // FIXME: Disambiguate these cases. Note that the latter case is probably 1074 // going to be made ill-formed by core issue 1607. 1075 Toks.push_back(Tok); 1076 ConsumeBrace(); 1077 return false; 1078 } else if (!MightBeTemplateArgument) { 1079 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace 1080 << tok::comma; 1081 } 1082 } 1083 } 1084 1085 /// Consume and store tokens from the '?' to the ':' in a conditional 1086 /// expression. 1087 bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) { 1088 // Consume '?'. 1089 assert(Tok.is(tok::question)); 1090 Toks.push_back(Tok); 1091 ConsumeToken(); 1092 1093 while (Tok.isNot(tok::colon)) { 1094 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks, 1095 /*StopAtSemi=*/true, 1096 /*ConsumeFinalToken=*/false)) 1097 return false; 1098 1099 // If we found a nested conditional, consume it. 1100 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks)) 1101 return false; 1102 } 1103 1104 // Consume ':'. 1105 Toks.push_back(Tok); 1106 ConsumeToken(); 1107 return true; 1108 } 1109 1110 /// A tentative parsing action that can also revert token annotations. 1111 class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction { 1112 public: 1113 explicit UnannotatedTentativeParsingAction(Parser &Self, 1114 tok::TokenKind EndKind) 1115 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) { 1116 // Stash away the old token stream, so we can restore it once the 1117 // tentative parse is complete. 1118 TentativeParsingAction Inner(Self); 1119 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false); 1120 Inner.Revert(); 1121 } 1122 1123 void RevertAnnotations() { 1124 Revert(); 1125 1126 // Put back the original tokens. 1127 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch); 1128 if (Toks.size()) { 1129 auto Buffer = std::make_unique<Token[]>(Toks.size()); 1130 std::copy(Toks.begin() + 1, Toks.end(), Buffer.get()); 1131 Buffer[Toks.size() - 1] = Self.Tok; 1132 Self.PP.EnterTokenStream(std::move(Buffer), Toks.size(), true, 1133 /*IsReinject*/ true); 1134 1135 Self.Tok = Toks.front(); 1136 } 1137 } 1138 1139 private: 1140 Parser &Self; 1141 CachedTokens Toks; 1142 tok::TokenKind EndKind; 1143 }; 1144 1145 /// ConsumeAndStoreInitializer - Consume and store the token at the passed token 1146 /// container until the end of the current initializer expression (either a 1147 /// default argument or an in-class initializer for a non-static data member). 1148 /// 1149 /// Returns \c true if we reached the end of something initializer-shaped, 1150 /// \c false if we bailed out. 1151 bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks, 1152 CachedInitKind CIK) { 1153 // We always want this function to consume at least one token if not at EOF. 1154 bool IsFirstToken = true; 1155 1156 // Number of possible unclosed <s we've seen so far. These might be templates, 1157 // and might not, but if there were none of them (or we know for sure that 1158 // we're within a template), we can avoid a tentative parse. 1159 unsigned AngleCount = 0; 1160 unsigned KnownTemplateCount = 0; 1161 1162 while (1) { 1163 switch (Tok.getKind()) { 1164 case tok::comma: 1165 // If we might be in a template, perform a tentative parse to check. 1166 if (!AngleCount) 1167 // Not a template argument: this is the end of the initializer. 1168 return true; 1169 if (KnownTemplateCount) 1170 goto consume_token; 1171 1172 // We hit a comma inside angle brackets. This is the hard case. The 1173 // rule we follow is: 1174 // * For a default argument, if the tokens after the comma form a 1175 // syntactically-valid parameter-declaration-clause, in which each 1176 // parameter has an initializer, then this comma ends the default 1177 // argument. 1178 // * For a default initializer, if the tokens after the comma form a 1179 // syntactically-valid init-declarator-list, then this comma ends 1180 // the default initializer. 1181 { 1182 UnannotatedTentativeParsingAction PA(*this, 1183 CIK == CIK_DefaultInitializer 1184 ? tok::semi : tok::r_paren); 1185 Sema::TentativeAnalysisScope Scope(Actions); 1186 1187 TPResult Result = TPResult::Error; 1188 ConsumeToken(); 1189 switch (CIK) { 1190 case CIK_DefaultInitializer: 1191 Result = TryParseInitDeclaratorList(); 1192 // If we parsed a complete, ambiguous init-declarator-list, this 1193 // is only syntactically-valid if it's followed by a semicolon. 1194 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi)) 1195 Result = TPResult::False; 1196 break; 1197 1198 case CIK_DefaultArgument: 1199 bool InvalidAsDeclaration = false; 1200 Result = TryParseParameterDeclarationClause( 1201 &InvalidAsDeclaration, /*VersusTemplateArg=*/true); 1202 // If this is an expression or a declaration with a missing 1203 // 'typename', assume it's not a declaration. 1204 if (Result == TPResult::Ambiguous && InvalidAsDeclaration) 1205 Result = TPResult::False; 1206 break; 1207 } 1208 1209 // Put the token stream back and undo any annotations we performed 1210 // after the comma. They may reflect a different parse than the one 1211 // we will actually perform at the end of the class. 1212 PA.RevertAnnotations(); 1213 1214 // If what follows could be a declaration, it is a declaration. 1215 if (Result != TPResult::False && Result != TPResult::Error) 1216 return true; 1217 } 1218 1219 // Keep going. We know we're inside a template argument list now. 1220 ++KnownTemplateCount; 1221 goto consume_token; 1222 1223 case tok::eof: 1224 case tok::annot_module_begin: 1225 case tok::annot_module_end: 1226 case tok::annot_module_include: 1227 // Ran out of tokens. 1228 return false; 1229 1230 case tok::less: 1231 // FIXME: A '<' can only start a template-id if it's preceded by an 1232 // identifier, an operator-function-id, or a literal-operator-id. 1233 ++AngleCount; 1234 goto consume_token; 1235 1236 case tok::question: 1237 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does, 1238 // that is *never* the end of the initializer. Skip to the ':'. 1239 if (!ConsumeAndStoreConditional(Toks)) 1240 return false; 1241 break; 1242 1243 case tok::greatergreatergreater: 1244 if (!getLangOpts().CPlusPlus11) 1245 goto consume_token; 1246 if (AngleCount) --AngleCount; 1247 if (KnownTemplateCount) --KnownTemplateCount; 1248 LLVM_FALLTHROUGH; 1249 case tok::greatergreater: 1250 if (!getLangOpts().CPlusPlus11) 1251 goto consume_token; 1252 if (AngleCount) --AngleCount; 1253 if (KnownTemplateCount) --KnownTemplateCount; 1254 LLVM_FALLTHROUGH; 1255 case tok::greater: 1256 if (AngleCount) --AngleCount; 1257 if (KnownTemplateCount) --KnownTemplateCount; 1258 goto consume_token; 1259 1260 case tok::kw_template: 1261 // 'template' identifier '<' is known to start a template argument list, 1262 // and can be used to disambiguate the parse. 1263 // FIXME: Support all forms of 'template' unqualified-id '<'. 1264 Toks.push_back(Tok); 1265 ConsumeToken(); 1266 if (Tok.is(tok::identifier)) { 1267 Toks.push_back(Tok); 1268 ConsumeToken(); 1269 if (Tok.is(tok::less)) { 1270 ++AngleCount; 1271 ++KnownTemplateCount; 1272 Toks.push_back(Tok); 1273 ConsumeToken(); 1274 } 1275 } 1276 break; 1277 1278 case tok::kw_operator: 1279 // If 'operator' precedes other punctuation, that punctuation loses 1280 // its special behavior. 1281 Toks.push_back(Tok); 1282 ConsumeToken(); 1283 switch (Tok.getKind()) { 1284 case tok::comma: 1285 case tok::greatergreatergreater: 1286 case tok::greatergreater: 1287 case tok::greater: 1288 case tok::less: 1289 Toks.push_back(Tok); 1290 ConsumeToken(); 1291 break; 1292 default: 1293 break; 1294 } 1295 break; 1296 1297 case tok::l_paren: 1298 // Recursively consume properly-nested parens. 1299 Toks.push_back(Tok); 1300 ConsumeParen(); 1301 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); 1302 break; 1303 case tok::l_square: 1304 // Recursively consume properly-nested square brackets. 1305 Toks.push_back(Tok); 1306 ConsumeBracket(); 1307 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false); 1308 break; 1309 case tok::l_brace: 1310 // Recursively consume properly-nested braces. 1311 Toks.push_back(Tok); 1312 ConsumeBrace(); 1313 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); 1314 break; 1315 1316 // Okay, we found a ']' or '}' or ')', which we think should be balanced. 1317 // Since the user wasn't looking for this token (if they were, it would 1318 // already be handled), this isn't balanced. If there is a LHS token at a 1319 // higher level, we will assume that this matches the unbalanced token 1320 // and return it. Otherwise, this is a spurious RHS token, which we 1321 // consume and pass on to downstream code to diagnose. 1322 case tok::r_paren: 1323 if (CIK == CIK_DefaultArgument) 1324 return true; // End of the default argument. 1325 if (ParenCount && !IsFirstToken) 1326 return false; 1327 Toks.push_back(Tok); 1328 ConsumeParen(); 1329 continue; 1330 case tok::r_square: 1331 if (BracketCount && !IsFirstToken) 1332 return false; 1333 Toks.push_back(Tok); 1334 ConsumeBracket(); 1335 continue; 1336 case tok::r_brace: 1337 if (BraceCount && !IsFirstToken) 1338 return false; 1339 Toks.push_back(Tok); 1340 ConsumeBrace(); 1341 continue; 1342 1343 case tok::code_completion: 1344 Toks.push_back(Tok); 1345 ConsumeCodeCompletionToken(); 1346 break; 1347 1348 case tok::string_literal: 1349 case tok::wide_string_literal: 1350 case tok::utf8_string_literal: 1351 case tok::utf16_string_literal: 1352 case tok::utf32_string_literal: 1353 Toks.push_back(Tok); 1354 ConsumeStringToken(); 1355 break; 1356 case tok::semi: 1357 if (CIK == CIK_DefaultInitializer) 1358 return true; // End of the default initializer. 1359 LLVM_FALLTHROUGH; 1360 default: 1361 consume_token: 1362 Toks.push_back(Tok); 1363 ConsumeToken(); 1364 break; 1365 } 1366 IsFirstToken = false; 1367 } 1368 } 1369