1 //===--- ParseCXXInlineMethods.cpp - C++ class inline methods parsing------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements parsing for C++ class inline methods.
12 //===----------------------------------------------------------------------===//
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;
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,
28 const ParsedTemplateInfo &TemplateInfo,
29 const VirtSpecifiers& VS,
30 SourceLocation PureSpecLoc) {
31 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
32 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) &&
33 "Current token not a '{', ':', '=', or 'try'!");
35 MultiTemplateParamsArg TemplateParams(
36 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
38 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
41 if (D.getDeclSpec().isFriendSpecified())
42 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
45 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
46 TemplateParams, nullptr,
49 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
50 if (PureSpecLoc.isValid())
51 Actions.ActOnPureSpecifier(FnD, PureSpecLoc);
55 HandleMemberFunctionDeclDelays(D, FnD);
59 if (TryConsumeToken(tok::equal)) {
67 SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
68 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
69 Diag(KWLoc, getLangOpts().CPlusPlus11
70 ? diag::warn_cxx98_compat_deleted_function
71 : diag::ext_deleted_function);
72 Actions.SetDeclDeleted(FnD, KWLoc);
74 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
75 DeclAsFunction->setRangeEnd(KWEndLoc);
77 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
78 Diag(KWLoc, getLangOpts().CPlusPlus11
79 ? diag::warn_cxx98_compat_defaulted_function
80 : diag::ext_defaulted_function);
81 Actions.SetDeclDefaulted(FnD, KWLoc);
82 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
83 DeclAsFunction->setRangeEnd(KWEndLoc);
86 llvm_unreachable("function definition after = not 'delete' or 'default'");
89 if (Tok.is(tok::comma)) {
90 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
93 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
94 Delete ? "delete" : "default")) {
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 D.getFunctionDefinitionKind() == 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())) {
115 LexTemplateFunctionForLateParsing(Toks);
118 FunctionDecl *FD = FnD->getAsFunction();
119 Actions.CheckForFunctionRedefinition(FD);
120 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
126 // Consume the tokens and store them for later parsing.
128 LexedMethod* LM = new LexedMethod(this, FnD);
129 getCurrentClass().LateParsedDeclarations.push_back(LM);
130 LM->TemplateScope = getCurScope()->isTemplateParamScope();
131 CachedTokens &Toks = LM->Toks;
133 tok::TokenKind kind = Tok.getKind();
134 // Consume everything up to (and including) the left brace of the
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
143 delete getCurrentClass().LateParsedDeclarations.back();
144 getCurrentClass().LateParsedDeclarations.pop_back();
147 // Consume everything up to (and including) the matching right brace.
148 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
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);
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.
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);
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();
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.isOneOf(tok::l_brace, tok::equal) &&
190 "Current token not a '{' or '='!");
192 LateParsedMemberInitializer *MI =
193 new LateParsedMemberInitializer(this, VarD);
194 getCurrentClass().LateParsedDeclarations.push_back(MI);
195 CachedTokens &Toks = MI->Toks;
197 tok::TokenKind kind = Tok.getKind();
198 if (kind == tok::equal) {
203 if (kind == tok::l_brace) {
204 // Begin by storing the '{' token.
208 // Consume everything up to (and including) the matching right brace.
209 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
211 // Consume everything up to (but excluding) the comma or semicolon.
212 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
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.
219 Eof.setKind(tok::eof);
220 Eof.setLocation(Tok.getLocation());
221 Eof.setEofData(VarD);
225 Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
226 void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
227 void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
228 void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
230 Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
231 : Self(P), Class(C) {}
233 Parser::LateParsedClass::~LateParsedClass() {
234 Self->DeallocateParsedClasses(Class);
237 void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
238 Self->ParseLexedMethodDeclarations(*Class);
241 void Parser::LateParsedClass::ParseLexedMemberInitializers() {
242 Self->ParseLexedMemberInitializers(*Class);
245 void Parser::LateParsedClass::ParseLexedMethodDefs() {
246 Self->ParseLexedMethodDefs(*Class);
249 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
250 Self->ParseLexedMethodDeclaration(*this);
253 void Parser::LexedMethod::ParseLexedMethodDefs() {
254 Self->ParseLexedMethodDef(*this);
257 void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
258 Self->ParseLexedMemberInitializer(*this);
261 /// ParseLexedMethodDeclarations - We finished parsing the member
262 /// specification of a top (non-nested) C++ class. Now go over the
263 /// stack of method declarations with some parts for which parsing was
264 /// delayed (such as default arguments) and parse them.
265 void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
266 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
267 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
269 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
270 if (HasTemplateScope) {
271 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
272 ++CurTemplateDepthTracker;
275 // The current scope is still active if we're the top-level class.
276 // Otherwise we'll need to push and enter a new scope.
277 bool HasClassScope = !Class.TopLevelClass;
278 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
281 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
282 Class.TagOrTemplate);
284 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
285 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
289 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
290 Class.TagOrTemplate);
293 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
294 // If this is a member template, introduce the template parameter scope.
295 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
296 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
297 if (LM.TemplateScope) {
298 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
299 ++CurTemplateDepthTracker;
301 // Start the delayed C++ method declaration
302 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
304 // Introduce the parameters into scope and parse their default
306 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
307 Scope::FunctionDeclarationScope | Scope::DeclScope);
308 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
309 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
310 // Introduce the parameter into scope.
311 bool HasUnparsed = Param->hasUnparsedDefaultArg();
312 Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
313 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
314 // Mark the end of the default argument so that we know when to stop when
315 // we parse it later on.
316 Token LastDefaultArgToken = Toks->back();
318 DefArgEnd.startToken();
319 DefArgEnd.setKind(tok::eof);
320 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
321 DefArgEnd.setEofData(Param);
322 Toks->push_back(DefArgEnd);
324 // Parse the default argument from its saved token stream.
325 Toks->push_back(Tok); // So that the current token doesn't get lost
326 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
328 // Consume the previously-pushed token.
332 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
333 SourceLocation EqualLoc = ConsumeToken();
335 // The argument isn't actually potentially evaluated unless it is
337 EnterExpressionEvaluationContext Eval(Actions,
338 Sema::PotentiallyEvaluatedIfUsed,
341 ExprResult DefArgResult;
342 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
343 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
344 DefArgResult = ParseBraceInitializer();
346 DefArgResult = ParseAssignmentExpression();
347 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
348 if (DefArgResult.isInvalid()) {
349 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
351 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
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
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());
360 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
364 // There could be leftover tokens (e.g. because of an error).
365 // Skip through until we reach the 'end of default argument' token.
366 while (Tok.isNot(tok::eof))
369 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
373 LM.DefaultArgs[I].Toks = nullptr;
374 } else if (HasUnparsed) {
375 assert(Param->hasInheritedDefaultArg());
376 FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
377 ParmVarDecl *OldParam = Old->getParamDecl(I);
378 assert (!OldParam->hasUnparsedDefaultArg());
379 if (OldParam->hasUninstantiatedDefaultArg())
380 Param->setUninstantiatedDefaultArg(
381 Param->getUninstantiatedDefaultArg());
383 Param->setDefaultArg(OldParam->getInit());
387 // Parse a delayed exception-specification, if there is one.
388 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
389 // Add the 'stop' token.
390 Token LastExceptionSpecToken = Toks->back();
391 Token ExceptionSpecEnd;
392 ExceptionSpecEnd.startToken();
393 ExceptionSpecEnd.setKind(tok::eof);
394 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
395 ExceptionSpecEnd.setEofData(LM.Method);
396 Toks->push_back(ExceptionSpecEnd);
398 // Parse the default argument from its saved token stream.
399 Toks->push_back(Tok); // So that the current token doesn't get lost
400 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
402 // Consume the previously-pushed token.
405 // C++11 [expr.prim.general]p3:
406 // If a declaration declares a member function or member function
407 // template of a class X, the expression this is a prvalue of type
408 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
409 // and the end of the function-definition, member-declarator, or
411 CXXMethodDecl *Method;
412 if (FunctionTemplateDecl *FunTmpl
413 = dyn_cast<FunctionTemplateDecl>(LM.Method))
414 Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
416 Method = cast<CXXMethodDecl>(LM.Method);
418 Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
419 Method->getTypeQualifiers(),
420 getLangOpts().CPlusPlus11);
422 // Parse the exception-specification.
423 SourceRange SpecificationRange;
424 SmallVector<ParsedType, 4> DynamicExceptions;
425 SmallVector<SourceRange, 4> DynamicExceptionRanges;
426 ExprResult NoexceptExpr;
427 CachedTokens *ExceptionSpecTokens;
429 ExceptionSpecificationType EST
430 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
432 DynamicExceptionRanges, NoexceptExpr,
433 ExceptionSpecTokens);
435 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
436 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
438 // Attach the exception-specification to the method.
439 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
442 DynamicExceptionRanges,
443 NoexceptExpr.isUsable()?
444 NoexceptExpr.get() : nullptr);
446 // There could be leftover tokens (e.g. because of an error).
447 // Skip through until we reach the original token position.
448 while (Tok.isNot(tok::eof))
451 // Clean up the remaining EOF token.
452 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
456 LM.ExceptionSpecTokens = nullptr;
459 PrototypeScope.Exit();
461 // Finish the delayed C++ method declaration.
462 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
465 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
466 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
467 /// collected during its parsing and parse them all.
468 void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
469 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
470 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
471 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
472 if (HasTemplateScope) {
473 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
474 ++CurTemplateDepthTracker;
476 bool HasClassScope = !Class.TopLevelClass;
477 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
480 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
481 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
485 void Parser::ParseLexedMethodDef(LexedMethod &LM) {
486 // If this is a member template, introduce the template parameter scope.
487 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
488 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
489 if (LM.TemplateScope) {
490 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
491 ++CurTemplateDepthTracker;
494 assert(!LM.Toks.empty() && "Empty body!");
495 Token LastBodyToken = LM.Toks.back();
497 BodyEnd.startToken();
498 BodyEnd.setKind(tok::eof);
499 BodyEnd.setLocation(LastBodyToken.getEndLoc());
500 BodyEnd.setEofData(LM.D);
501 LM.Toks.push_back(BodyEnd);
502 // Append the current token at the end of the new token stream so that it
504 LM.Toks.push_back(Tok);
505 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
507 // Consume the previously pushed token.
508 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
509 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
510 && "Inline method not starting with '{', ':' or 'try'");
512 // Parse the method body. Function body parsing code is similar enough
513 // to be re-used for method bodies as well.
514 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
515 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
517 if (Tok.is(tok::kw_try)) {
518 ParseFunctionTryBlock(LM.D, FnScope);
520 while (Tok.isNot(tok::eof))
523 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
527 if (Tok.is(tok::colon)) {
528 ParseConstructorInitializer(LM.D);
531 if (!Tok.is(tok::l_brace)) {
533 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
535 while (Tok.isNot(tok::eof))
538 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
543 Actions.ActOnDefaultCtorInitializers(LM.D);
545 assert((Actions.getDiagnostics().hasErrorOccurred() ||
546 !isa<FunctionTemplateDecl>(LM.D) ||
547 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
548 < TemplateParameterDepth) &&
549 "TemplateParameterDepth should be greater than the depth of "
550 "current template being instantiated!");
552 ParseFunctionStatementBody(LM.D, FnScope);
554 // Clear the late-template-parsed bit if we set it before.
556 LM.D->getAsFunction()->setLateTemplateParsed(false);
558 while (Tok.isNot(tok::eof))
561 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
564 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
565 Actions.ActOnFinishInlineMethodDef(MD);
568 /// ParseLexedMemberInitializers - We finished parsing the member specification
569 /// of a top (non-nested) C++ class. Now go over the stack of lexed data member
570 /// initializers that were collected during its parsing and parse them all.
571 void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
572 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
573 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
575 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
576 if (HasTemplateScope) {
577 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
578 ++CurTemplateDepthTracker;
580 // Set or update the scope flags.
581 bool AlreadyHasClassScope = Class.TopLevelClass;
582 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
583 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
584 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
586 if (!AlreadyHasClassScope)
587 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
588 Class.TagOrTemplate);
590 if (!Class.LateParsedDeclarations.empty()) {
591 // C++11 [expr.prim.general]p4:
592 // Otherwise, if a member-declarator declares a non-static data member
593 // (9.2) of a class X, the expression this is a prvalue of type "pointer
594 // to X" within the optional brace-or-equal-initializer. It shall not
595 // appear elsewhere in the member-declarator.
596 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
597 /*TypeQuals=*/(unsigned)0);
599 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
600 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
604 if (!AlreadyHasClassScope)
605 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
606 Class.TagOrTemplate);
608 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
611 void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
612 if (!MI.Field || MI.Field->isInvalidDecl())
615 // Append the current token at the end of the new token stream so that it
617 MI.Toks.push_back(Tok);
618 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
620 // Consume the previously pushed token.
621 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
623 SourceLocation EqualLoc;
625 Actions.ActOnStartCXXInClassMemberInitializer();
627 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
630 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
633 // The next token should be our artificial terminating EOF token.
634 if (Tok.isNot(tok::eof)) {
635 if (!Init.isInvalid()) {
636 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
637 if (!EndLoc.isValid())
638 EndLoc = Tok.getLocation();
639 // No fixit; we can't recover as if there were a semicolon here.
640 Diag(EndLoc, diag::err_expected_semi_decl_list);
643 // Consume tokens until we hit the artificial EOF.
644 while (Tok.isNot(tok::eof))
647 // Make sure this is *our* artificial EOF token.
648 if (Tok.getEofData() == MI.Field)
652 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
653 /// container until the token 'T' is reached (which gets
654 /// consumed/stored too, if ConsumeFinalToken).
655 /// If StopAtSemi is true, then we will stop early at a ';' character.
656 /// Returns true if token 'T1' or 'T2' was found.
657 /// NOTE: This is a specialized version of Parser::SkipUntil.
658 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
660 bool StopAtSemi, bool ConsumeFinalToken) {
661 // We always want this function to consume at least one token if the first
662 // token isn't T and if not at EOF.
663 bool isFirstTokenConsumed = true;
665 // If we found one of the tokens, stop and return true.
666 if (Tok.is(T1) || Tok.is(T2)) {
667 if (ConsumeFinalToken) {
674 switch (Tok.getKind()) {
676 case tok::annot_module_begin:
677 case tok::annot_module_end:
678 case tok::annot_module_include:
679 // Ran out of tokens.
683 // Recursively consume properly-nested parens.
686 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
689 // Recursively consume properly-nested square brackets.
692 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
695 // Recursively consume properly-nested braces.
698 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
701 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
702 // Since the user wasn't looking for this token (if they were, it would
703 // already be handled), this isn't balanced. If there is a LHS token at a
704 // higher level, we will assume that this matches the unbalanced token
705 // and return it. Otherwise, this is a spurious RHS token, which we skip.
707 if (ParenCount && !isFirstTokenConsumed)
708 return false; // Matches something.
713 if (BracketCount && !isFirstTokenConsumed)
714 return false; // Matches something.
719 if (BraceCount && !isFirstTokenConsumed)
720 return false; // Matches something.
725 case tok::code_completion:
727 ConsumeCodeCompletionToken();
730 case tok::string_literal:
731 case tok::wide_string_literal:
732 case tok::utf8_string_literal:
733 case tok::utf16_string_literal:
734 case tok::utf32_string_literal:
736 ConsumeStringToken();
743 // consume this token.
748 isFirstTokenConsumed = false;
752 /// \brief Consume tokens and store them in the passed token container until
753 /// we've passed the try keyword and constructor initializers and have consumed
754 /// the opening brace of the function body. The opening brace will be consumed
755 /// if and only if there was no error.
757 /// \return True on error.
758 bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
759 if (Tok.is(tok::kw_try)) {
764 if (Tok.isNot(tok::colon)) {
765 // Easy case, just a function body.
767 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
768 // brace: an opening one is the function body, while a closing one probably
769 // means we've reached the end of the class.
770 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
772 /*ConsumeFinalToken=*/false);
773 if (Tok.isNot(tok::l_brace))
774 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
784 // We can't reliably skip over a mem-initializer-id, because it could be
785 // a template-id involving not-yet-declared names. Given:
787 // S ( ) : a < b < c > ( e )
789 // 'e' might be an initializer or part of a template argument, depending
790 // on whether 'b' is a template.
792 // Track whether we might be inside a template argument. We can give
793 // significantly better diagnostics if we know that we're not.
794 bool MightBeTemplateArgument = false;
797 // Skip over the mem-initializer-id, if possible.
798 if (Tok.is(tok::kw_decltype)) {
800 SourceLocation OpenLoc = ConsumeToken();
801 if (Tok.isNot(tok::l_paren))
802 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
806 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
807 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
808 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
813 // Walk over a component of a nested-name-specifier.
814 if (Tok.is(tok::coloncolon)) {
818 if (Tok.is(tok::kw_template)) {
824 if (Tok.isOneOf(tok::identifier, tok::kw_template)) {
827 } else if (Tok.is(tok::code_completion)) {
829 ConsumeCodeCompletionToken();
830 // Consume the rest of the initializers permissively.
831 // FIXME: We should be able to perform code-completion here even if
832 // there isn't a subsequent '{' token.
833 MightBeTemplateArgument = true;
838 } while (Tok.is(tok::coloncolon));
840 if (Tok.is(tok::less))
841 MightBeTemplateArgument = true;
843 if (MightBeTemplateArgument) {
844 // We may be inside a template argument list. Grab up to the start of the
845 // next parenthesized initializer or braced-init-list. This *might* be the
846 // initializer, or it might be a subexpression in the template argument
848 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
849 // if all angles are closed.
850 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
852 /*ConsumeFinalToken=*/false)) {
853 // We're not just missing the initializer, we're also missing the
855 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
857 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
858 // We found something weird in a mem-initializer-id.
859 if (getLangOpts().CPlusPlus11)
860 return Diag(Tok.getLocation(), diag::err_expected_either)
861 << tok::l_paren << tok::l_brace;
863 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
866 tok::TokenKind kind = Tok.getKind();
868 bool IsLParen = (kind == tok::l_paren);
869 SourceLocation OpenLoc = Tok.getLocation();
874 assert(kind == tok::l_brace && "Must be left paren or brace here.");
876 // In C++03, this has to be the start of the function body, which
877 // means the initializer is malformed; we'll diagnose it later.
878 if (!getLangOpts().CPlusPlus11)
882 // Grab the initializer (or the subexpression of the template argument).
883 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
884 // if we might be inside the braces of a lambda-expression.
885 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
886 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
887 Diag(Tok, diag::err_expected) << CloseKind;
888 Diag(OpenLoc, diag::note_matching) << kind;
892 // Grab pack ellipsis, if present.
893 if (Tok.is(tok::ellipsis)) {
898 // If we know we just consumed a mem-initializer, we must have ',' or '{'
900 if (Tok.is(tok::comma)) {
903 } else if (Tok.is(tok::l_brace)) {
904 // This is the function body if the ')' or '}' is immediately followed by
905 // a '{'. That cannot happen within a template argument, apart from the
906 // case where a template argument contains a compound literal:
908 // S ( ) : a < b < c > ( d ) { }
909 // // End of declaration, or still inside the template argument?
911 // ... and the case where the template argument contains a lambda:
913 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
916 // FIXME: Disambiguate these cases. Note that the latter case is probably
917 // going to be made ill-formed by core issue 1607.
921 } else if (!MightBeTemplateArgument) {
922 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
928 /// \brief Consume and store tokens from the '?' to the ':' in a conditional
930 bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
932 assert(Tok.is(tok::question));
936 while (Tok.isNot(tok::colon)) {
937 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
939 /*ConsumeFinalToken=*/false))
942 // If we found a nested conditional, consume it.
943 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
953 /// \brief A tentative parsing action that can also revert token annotations.
954 class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
956 explicit UnannotatedTentativeParsingAction(Parser &Self,
957 tok::TokenKind EndKind)
958 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
959 // Stash away the old token stream, so we can restore it once the
960 // tentative parse is complete.
961 TentativeParsingAction Inner(Self);
962 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
966 void RevertAnnotations() {
969 // Put back the original tokens.
970 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
972 Token *Buffer = new Token[Toks.size()];
973 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
974 Buffer[Toks.size() - 1] = Self.Tok;
975 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
977 Self.Tok = Toks.front();
984 tok::TokenKind EndKind;
987 /// ConsumeAndStoreInitializer - Consume and store the token at the passed token
988 /// container until the end of the current initializer expression (either a
989 /// default argument or an in-class initializer for a non-static data member).
991 /// Returns \c true if we reached the end of something initializer-shaped,
992 /// \c false if we bailed out.
993 bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
994 CachedInitKind CIK) {
995 // We always want this function to consume at least one token if not at EOF.
996 bool IsFirstToken = true;
998 // Number of possible unclosed <s we've seen so far. These might be templates,
999 // and might not, but if there were none of them (or we know for sure that
1000 // we're within a template), we can avoid a tentative parse.
1001 unsigned AngleCount = 0;
1002 unsigned KnownTemplateCount = 0;
1005 switch (Tok.getKind()) {
1007 // If we might be in a template, perform a tentative parse to check.
1009 // Not a template argument: this is the end of the initializer.
1011 if (KnownTemplateCount)
1014 // We hit a comma inside angle brackets. This is the hard case. The
1015 // rule we follow is:
1016 // * For a default argument, if the tokens after the comma form a
1017 // syntactically-valid parameter-declaration-clause, in which each
1018 // parameter has an initializer, then this comma ends the default
1020 // * For a default initializer, if the tokens after the comma form a
1021 // syntactically-valid init-declarator-list, then this comma ends
1022 // the default initializer.
1024 UnannotatedTentativeParsingAction PA(*this,
1025 CIK == CIK_DefaultInitializer
1026 ? tok::semi : tok::r_paren);
1027 Sema::TentativeAnalysisScope Scope(Actions);
1029 TPResult Result = TPResult::Error;
1032 case CIK_DefaultInitializer:
1033 Result = TryParseInitDeclaratorList();
1034 // If we parsed a complete, ambiguous init-declarator-list, this
1035 // is only syntactically-valid if it's followed by a semicolon.
1036 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1037 Result = TPResult::False;
1040 case CIK_DefaultArgument:
1041 bool InvalidAsDeclaration = false;
1042 Result = TryParseParameterDeclarationClause(
1043 &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
1044 // If this is an expression or a declaration with a missing
1045 // 'typename', assume it's not a declaration.
1046 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1047 Result = TPResult::False;
1051 // If what follows could be a declaration, it is a declaration.
1052 if (Result != TPResult::False && Result != TPResult::Error) {
1057 // In the uncommon case that we decide the following tokens are part
1058 // of a template argument, revert any annotations we've performed in
1059 // those tokens. We're not going to look them up until we've parsed
1060 // the rest of the class, and that might add more declarations.
1061 PA.RevertAnnotations();
1064 // Keep going. We know we're inside a template argument list now.
1065 ++KnownTemplateCount;
1069 case tok::annot_module_begin:
1070 case tok::annot_module_end:
1071 case tok::annot_module_include:
1072 // Ran out of tokens.
1076 // FIXME: A '<' can only start a template-id if it's preceded by an
1077 // identifier, an operator-function-id, or a literal-operator-id.
1082 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1083 // that is *never* the end of the initializer. Skip to the ':'.
1084 if (!ConsumeAndStoreConditional(Toks))
1088 case tok::greatergreatergreater:
1089 if (!getLangOpts().CPlusPlus11)
1091 if (AngleCount) --AngleCount;
1092 if (KnownTemplateCount) --KnownTemplateCount;
1094 case tok::greatergreater:
1095 if (!getLangOpts().CPlusPlus11)
1097 if (AngleCount) --AngleCount;
1098 if (KnownTemplateCount) --KnownTemplateCount;
1101 if (AngleCount) --AngleCount;
1102 if (KnownTemplateCount) --KnownTemplateCount;
1105 case tok::kw_template:
1106 // 'template' identifier '<' is known to start a template argument list,
1107 // and can be used to disambiguate the parse.
1108 // FIXME: Support all forms of 'template' unqualified-id '<'.
1109 Toks.push_back(Tok);
1111 if (Tok.is(tok::identifier)) {
1112 Toks.push_back(Tok);
1114 if (Tok.is(tok::less)) {
1116 ++KnownTemplateCount;
1117 Toks.push_back(Tok);
1123 case tok::kw_operator:
1124 // If 'operator' precedes other punctuation, that punctuation loses
1125 // its special behavior.
1126 Toks.push_back(Tok);
1128 switch (Tok.getKind()) {
1130 case tok::greatergreatergreater:
1131 case tok::greatergreater:
1134 Toks.push_back(Tok);
1143 // Recursively consume properly-nested parens.
1144 Toks.push_back(Tok);
1146 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1149 // Recursively consume properly-nested square brackets.
1150 Toks.push_back(Tok);
1152 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1155 // Recursively consume properly-nested braces.
1156 Toks.push_back(Tok);
1158 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1161 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1162 // Since the user wasn't looking for this token (if they were, it would
1163 // already be handled), this isn't balanced. If there is a LHS token at a
1164 // higher level, we will assume that this matches the unbalanced token
1165 // and return it. Otherwise, this is a spurious RHS token, which we
1166 // consume and pass on to downstream code to diagnose.
1168 if (CIK == CIK_DefaultArgument)
1169 return true; // End of the default argument.
1170 if (ParenCount && !IsFirstToken)
1172 Toks.push_back(Tok);
1176 if (BracketCount && !IsFirstToken)
1178 Toks.push_back(Tok);
1182 if (BraceCount && !IsFirstToken)
1184 Toks.push_back(Tok);
1188 case tok::code_completion:
1189 Toks.push_back(Tok);
1190 ConsumeCodeCompletionToken();
1193 case tok::string_literal:
1194 case tok::wide_string_literal:
1195 case tok::utf8_string_literal:
1196 case tok::utf16_string_literal:
1197 case tok::utf32_string_literal:
1198 Toks.push_back(Tok);
1199 ConsumeStringToken();
1202 if (CIK == CIK_DefaultInitializer)
1203 return true; // End of the default initializer.
1207 Toks.push_back(Tok);
1211 IsFirstToken = false;