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,
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 bool TypeSpecContainsAuto = D.getDeclSpec().containsPlaceholderType();
52 Actions.AddInitializerToDecl(FnD, Init.get(), false,
53 TypeSpecContainsAuto);
55 Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto);
59 HandleMemberFunctionDeclDelays(D, FnD);
63 if (TryConsumeToken(tok::equal)) {
71 SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
72 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
73 Diag(KWLoc, getLangOpts().CPlusPlus11
74 ? diag::warn_cxx98_compat_deleted_function
75 : diag::ext_deleted_function);
76 Actions.SetDeclDeleted(FnD, KWLoc);
78 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
79 DeclAsFunction->setRangeEnd(KWEndLoc);
81 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
82 Diag(KWLoc, getLangOpts().CPlusPlus11
83 ? diag::warn_cxx98_compat_defaulted_function
84 : diag::ext_defaulted_function);
85 Actions.SetDeclDefaulted(FnD, KWLoc);
86 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
87 DeclAsFunction->setRangeEnd(KWEndLoc);
90 llvm_unreachable("function definition after = not 'delete' or 'default'");
93 if (Tok.is(tok::comma)) {
94 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
97 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
98 Delete ? "delete" : "default")) {
105 // In delayed template parsing mode, if we are within a class template
106 // or if we are about to parse function member template then consume
107 // the tokens and store them for parsing at the end of the translation unit.
108 if (getLangOpts().DelayedTemplateParsing &&
109 D.getFunctionDefinitionKind() == FDK_Definition &&
110 !D.getDeclSpec().isConstexprSpecified() &&
111 !(FnD && FnD->getAsFunction() &&
112 FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
113 ((Actions.CurContext->isDependentContext() ||
114 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
115 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
116 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
119 LexTemplateFunctionForLateParsing(Toks);
122 FunctionDecl *FD = FnD->getAsFunction();
123 Actions.CheckForFunctionRedefinition(FD);
124 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
130 // Consume the tokens and store them for later parsing.
132 LexedMethod* LM = new LexedMethod(this, FnD);
133 getCurrentClass().LateParsedDeclarations.push_back(LM);
134 LM->TemplateScope = getCurScope()->isTemplateParamScope();
135 CachedTokens &Toks = LM->Toks;
137 tok::TokenKind kind = Tok.getKind();
138 // Consume everything up to (and including) the left brace of the
140 if (ConsumeAndStoreFunctionPrologue(Toks)) {
141 // We didn't find the left-brace we expected after the
142 // constructor initializer; we already printed an error, and it's likely
143 // impossible to recover, so don't try to parse this method later.
144 // Skip over the rest of the decl and back to somewhere that looks
147 delete getCurrentClass().LateParsedDeclarations.back();
148 getCurrentClass().LateParsedDeclarations.pop_back();
151 // Consume everything up to (and including) the matching right brace.
152 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
155 // If we're in a function-try-block, we need to store all the catch blocks.
156 if (kind == tok::kw_try) {
157 while (Tok.is(tok::kw_catch)) {
158 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
159 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
164 // If this is a friend function, mark that it's late-parsed so that
165 // it's still known to be a definition even before we attach the
166 // parsed body. Sema needs to treat friend function definitions
167 // differently during template instantiation, and it's possible for
168 // the containing class to be instantiated before all its member
169 // function definitions are parsed.
171 // If you remove this, you can remove the code that clears the flag
172 // after parsing the member.
173 if (D.getDeclSpec().isFriendSpecified()) {
174 FunctionDecl *FD = FnD->getAsFunction();
175 Actions.CheckForFunctionRedefinition(FD);
176 FD->setLateTemplateParsed(true);
179 // If semantic analysis could not build a function declaration,
180 // just throw away the late-parsed declaration.
181 delete getCurrentClass().LateParsedDeclarations.back();
182 getCurrentClass().LateParsedDeclarations.pop_back();
188 /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
189 /// specified Declarator is a well formed C++ non-static data member
190 /// declaration. Now lex its initializer and store its tokens for parsing
191 /// after the class is complete.
192 void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
193 assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
194 "Current token not a '{' or '='!");
196 LateParsedMemberInitializer *MI =
197 new LateParsedMemberInitializer(this, VarD);
198 getCurrentClass().LateParsedDeclarations.push_back(MI);
199 CachedTokens &Toks = MI->Toks;
201 tok::TokenKind kind = Tok.getKind();
202 if (kind == tok::equal) {
207 if (kind == tok::l_brace) {
208 // Begin by storing the '{' token.
212 // Consume everything up to (and including) the matching right brace.
213 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
215 // Consume everything up to (but excluding) the comma or semicolon.
216 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
219 // Store an artificial EOF token to ensure that we don't run off the end of
220 // the initializer when we come to parse it.
223 Eof.setKind(tok::eof);
224 Eof.setLocation(Tok.getLocation());
225 Eof.setEofData(VarD);
229 Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
230 void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
231 void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
232 void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
234 Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
235 : Self(P), Class(C) {}
237 Parser::LateParsedClass::~LateParsedClass() {
238 Self->DeallocateParsedClasses(Class);
241 void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
242 Self->ParseLexedMethodDeclarations(*Class);
245 void Parser::LateParsedClass::ParseLexedMemberInitializers() {
246 Self->ParseLexedMemberInitializers(*Class);
249 void Parser::LateParsedClass::ParseLexedMethodDefs() {
250 Self->ParseLexedMethodDefs(*Class);
253 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
254 Self->ParseLexedMethodDeclaration(*this);
257 void Parser::LexedMethod::ParseLexedMethodDefs() {
258 Self->ParseLexedMethodDef(*this);
261 void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
262 Self->ParseLexedMemberInitializer(*this);
265 /// ParseLexedMethodDeclarations - We finished parsing the member
266 /// specification of a top (non-nested) C++ class. Now go over the
267 /// stack of method declarations with some parts for which parsing was
268 /// delayed (such as default arguments) and parse them.
269 void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
270 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
271 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
273 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
274 if (HasTemplateScope) {
275 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
276 ++CurTemplateDepthTracker;
279 // The current scope is still active if we're the top-level class.
280 // Otherwise we'll need to push and enter a new scope.
281 bool HasClassScope = !Class.TopLevelClass;
282 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
285 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
286 Class.TagOrTemplate);
288 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
289 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
293 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
294 Class.TagOrTemplate);
297 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
298 // If this is a member template, introduce the template parameter scope.
299 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
300 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
301 if (LM.TemplateScope) {
302 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
303 ++CurTemplateDepthTracker;
305 // Start the delayed C++ method declaration
306 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
308 // Introduce the parameters into scope and parse their default
310 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
311 Scope::FunctionDeclarationScope | Scope::DeclScope);
312 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
313 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
314 // Introduce the parameter into scope.
315 bool HasUnparsed = Param->hasUnparsedDefaultArg();
316 Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
317 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
318 // Mark the end of the default argument so that we know when to stop when
319 // we parse it later on.
320 Token LastDefaultArgToken = Toks->back();
322 DefArgEnd.startToken();
323 DefArgEnd.setKind(tok::eof);
324 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
325 DefArgEnd.setEofData(Param);
326 Toks->push_back(DefArgEnd);
328 // Parse the default argument from its saved token stream.
329 Toks->push_back(Tok); // So that the current token doesn't get lost
330 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
332 // Consume the previously-pushed token.
336 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
337 SourceLocation EqualLoc = ConsumeToken();
339 // The argument isn't actually potentially evaluated unless it is
341 EnterExpressionEvaluationContext Eval(Actions,
342 Sema::PotentiallyEvaluatedIfUsed,
345 ExprResult DefArgResult;
346 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
347 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
348 DefArgResult = ParseBraceInitializer();
350 DefArgResult = ParseAssignmentExpression();
351 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
352 if (DefArgResult.isInvalid()) {
353 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
355 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
356 // The last two tokens are the terminator and the saved value of
357 // Tok; the last token in the default argument is the one before
359 assert(Toks->size() >= 3 && "expected a token in default arg");
360 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
361 << SourceRange(Tok.getLocation(),
362 (*Toks)[Toks->size() - 3].getLocation());
364 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
368 // There could be leftover tokens (e.g. because of an error).
369 // Skip through until we reach the 'end of default argument' token.
370 while (Tok.isNot(tok::eof))
373 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
377 LM.DefaultArgs[I].Toks = nullptr;
378 } else if (HasUnparsed) {
379 assert(Param->hasInheritedDefaultArg());
380 FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
381 ParmVarDecl *OldParam = Old->getParamDecl(I);
382 assert (!OldParam->hasUnparsedDefaultArg());
383 if (OldParam->hasUninstantiatedDefaultArg())
384 Param->setUninstantiatedDefaultArg(
385 Param->getUninstantiatedDefaultArg());
387 Param->setDefaultArg(OldParam->getInit());
391 // Parse a delayed exception-specification, if there is one.
392 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
393 // Add the 'stop' token.
394 Token LastExceptionSpecToken = Toks->back();
395 Token ExceptionSpecEnd;
396 ExceptionSpecEnd.startToken();
397 ExceptionSpecEnd.setKind(tok::eof);
398 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
399 ExceptionSpecEnd.setEofData(LM.Method);
400 Toks->push_back(ExceptionSpecEnd);
402 // Parse the default argument from its saved token stream.
403 Toks->push_back(Tok); // So that the current token doesn't get lost
404 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
406 // Consume the previously-pushed token.
409 // C++11 [expr.prim.general]p3:
410 // If a declaration declares a member function or member function
411 // template of a class X, the expression this is a prvalue of type
412 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
413 // and the end of the function-definition, member-declarator, or
415 CXXMethodDecl *Method;
416 if (FunctionTemplateDecl *FunTmpl
417 = dyn_cast<FunctionTemplateDecl>(LM.Method))
418 Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
420 Method = cast<CXXMethodDecl>(LM.Method);
422 Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
423 Method->getTypeQualifiers(),
424 getLangOpts().CPlusPlus11);
426 // Parse the exception-specification.
427 SourceRange SpecificationRange;
428 SmallVector<ParsedType, 4> DynamicExceptions;
429 SmallVector<SourceRange, 4> DynamicExceptionRanges;
430 ExprResult NoexceptExpr;
431 CachedTokens *ExceptionSpecTokens;
433 ExceptionSpecificationType EST
434 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
436 DynamicExceptionRanges, NoexceptExpr,
437 ExceptionSpecTokens);
439 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
440 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
442 // Attach the exception-specification to the method.
443 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
446 DynamicExceptionRanges,
447 NoexceptExpr.isUsable()?
448 NoexceptExpr.get() : nullptr);
450 // There could be leftover tokens (e.g. because of an error).
451 // Skip through until we reach the original token position.
452 while (Tok.isNot(tok::eof))
455 // Clean up the remaining EOF token.
456 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
460 LM.ExceptionSpecTokens = nullptr;
463 PrototypeScope.Exit();
465 // Finish the delayed C++ method declaration.
466 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
469 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
470 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
471 /// collected during its parsing and parse them all.
472 void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
473 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
474 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
475 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
476 if (HasTemplateScope) {
477 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
478 ++CurTemplateDepthTracker;
480 bool HasClassScope = !Class.TopLevelClass;
481 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
484 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
485 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
489 void Parser::ParseLexedMethodDef(LexedMethod &LM) {
490 // If this is a member template, introduce the template parameter scope.
491 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
492 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
493 if (LM.TemplateScope) {
494 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
495 ++CurTemplateDepthTracker;
498 assert(!LM.Toks.empty() && "Empty body!");
499 Token LastBodyToken = LM.Toks.back();
501 BodyEnd.startToken();
502 BodyEnd.setKind(tok::eof);
503 BodyEnd.setLocation(LastBodyToken.getEndLoc());
504 BodyEnd.setEofData(LM.D);
505 LM.Toks.push_back(BodyEnd);
506 // Append the current token at the end of the new token stream so that it
508 LM.Toks.push_back(Tok);
509 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
511 // Consume the previously pushed token.
512 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
513 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
514 && "Inline method not starting with '{', ':' or 'try'");
516 // Parse the method body. Function body parsing code is similar enough
517 // to be re-used for method bodies as well.
518 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
519 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
521 if (Tok.is(tok::kw_try)) {
522 ParseFunctionTryBlock(LM.D, FnScope);
524 while (Tok.isNot(tok::eof))
527 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
531 if (Tok.is(tok::colon)) {
532 ParseConstructorInitializer(LM.D);
535 if (!Tok.is(tok::l_brace)) {
537 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
539 while (Tok.isNot(tok::eof))
542 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
547 Actions.ActOnDefaultCtorInitializers(LM.D);
549 assert((Actions.getDiagnostics().hasErrorOccurred() ||
550 !isa<FunctionTemplateDecl>(LM.D) ||
551 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
552 < TemplateParameterDepth) &&
553 "TemplateParameterDepth should be greater than the depth of "
554 "current template being instantiated!");
556 ParseFunctionStatementBody(LM.D, FnScope);
558 // Clear the late-template-parsed bit if we set it before.
560 LM.D->getAsFunction()->setLateTemplateParsed(false);
562 while (Tok.isNot(tok::eof))
565 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
568 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
569 Actions.ActOnFinishInlineMethodDef(MD);
572 /// ParseLexedMemberInitializers - We finished parsing the member specification
573 /// of a top (non-nested) C++ class. Now go over the stack of lexed data member
574 /// initializers that were collected during its parsing and parse them all.
575 void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
576 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
577 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
579 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
580 if (HasTemplateScope) {
581 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
582 ++CurTemplateDepthTracker;
584 // Set or update the scope flags.
585 bool AlreadyHasClassScope = Class.TopLevelClass;
586 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
587 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
588 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
590 if (!AlreadyHasClassScope)
591 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
592 Class.TagOrTemplate);
594 if (!Class.LateParsedDeclarations.empty()) {
595 // C++11 [expr.prim.general]p4:
596 // Otherwise, if a member-declarator declares a non-static data member
597 // (9.2) of a class X, the expression this is a prvalue of type "pointer
598 // to X" within the optional brace-or-equal-initializer. It shall not
599 // appear elsewhere in the member-declarator.
600 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
601 /*TypeQuals=*/(unsigned)0);
603 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
604 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
608 if (!AlreadyHasClassScope)
609 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
610 Class.TagOrTemplate);
612 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
615 void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
616 if (!MI.Field || MI.Field->isInvalidDecl())
619 // Append the current token at the end of the new token stream so that it
621 MI.Toks.push_back(Tok);
622 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
624 // Consume the previously pushed token.
625 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
627 SourceLocation EqualLoc;
629 Actions.ActOnStartCXXInClassMemberInitializer();
631 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
634 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
637 // The next token should be our artificial terminating EOF token.
638 if (Tok.isNot(tok::eof)) {
639 if (!Init.isInvalid()) {
640 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
641 if (!EndLoc.isValid())
642 EndLoc = Tok.getLocation();
643 // No fixit; we can't recover as if there were a semicolon here.
644 Diag(EndLoc, diag::err_expected_semi_decl_list);
647 // Consume tokens until we hit the artificial EOF.
648 while (Tok.isNot(tok::eof))
651 // Make sure this is *our* artificial EOF token.
652 if (Tok.getEofData() == MI.Field)
656 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
657 /// container until the token 'T' is reached (which gets
658 /// consumed/stored too, if ConsumeFinalToken).
659 /// If StopAtSemi is true, then we will stop early at a ';' character.
660 /// Returns true if token 'T1' or 'T2' was found.
661 /// NOTE: This is a specialized version of Parser::SkipUntil.
662 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
664 bool StopAtSemi, bool ConsumeFinalToken) {
665 // We always want this function to consume at least one token if the first
666 // token isn't T and if not at EOF.
667 bool isFirstTokenConsumed = true;
669 // If we found one of the tokens, stop and return true.
670 if (Tok.is(T1) || Tok.is(T2)) {
671 if (ConsumeFinalToken) {
678 switch (Tok.getKind()) {
680 case tok::annot_module_begin:
681 case tok::annot_module_end:
682 case tok::annot_module_include:
683 // Ran out of tokens.
687 // Recursively consume properly-nested parens.
690 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
693 // Recursively consume properly-nested square brackets.
696 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
699 // Recursively consume properly-nested braces.
702 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
705 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
706 // Since the user wasn't looking for this token (if they were, it would
707 // already be handled), this isn't balanced. If there is a LHS token at a
708 // higher level, we will assume that this matches the unbalanced token
709 // and return it. Otherwise, this is a spurious RHS token, which we skip.
711 if (ParenCount && !isFirstTokenConsumed)
712 return false; // Matches something.
717 if (BracketCount && !isFirstTokenConsumed)
718 return false; // Matches something.
723 if (BraceCount && !isFirstTokenConsumed)
724 return false; // Matches something.
729 case tok::code_completion:
731 ConsumeCodeCompletionToken();
734 case tok::string_literal:
735 case tok::wide_string_literal:
736 case tok::utf8_string_literal:
737 case tok::utf16_string_literal:
738 case tok::utf32_string_literal:
740 ConsumeStringToken();
747 // consume this token.
752 isFirstTokenConsumed = false;
756 /// \brief Consume tokens and store them in the passed token container until
757 /// we've passed the try keyword and constructor initializers and have consumed
758 /// the opening brace of the function body. The opening brace will be consumed
759 /// if and only if there was no error.
761 /// \return True on error.
762 bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
763 if (Tok.is(tok::kw_try)) {
768 if (Tok.isNot(tok::colon)) {
769 // Easy case, just a function body.
771 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
772 // brace: an opening one is the function body, while a closing one probably
773 // means we've reached the end of the class.
774 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
776 /*ConsumeFinalToken=*/false);
777 if (Tok.isNot(tok::l_brace))
778 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
788 // We can't reliably skip over a mem-initializer-id, because it could be
789 // a template-id involving not-yet-declared names. Given:
791 // S ( ) : a < b < c > ( e )
793 // 'e' might be an initializer or part of a template argument, depending
794 // on whether 'b' is a template.
796 // Track whether we might be inside a template argument. We can give
797 // significantly better diagnostics if we know that we're not.
798 bool MightBeTemplateArgument = false;
801 // Skip over the mem-initializer-id, if possible.
802 if (Tok.is(tok::kw_decltype)) {
804 SourceLocation OpenLoc = ConsumeToken();
805 if (Tok.isNot(tok::l_paren))
806 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
810 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
811 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
812 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
817 // Walk over a component of a nested-name-specifier.
818 if (Tok.is(tok::coloncolon)) {
822 if (Tok.is(tok::kw_template)) {
828 if (Tok.isOneOf(tok::identifier, tok::kw_template)) {
831 } else if (Tok.is(tok::code_completion)) {
833 ConsumeCodeCompletionToken();
834 // Consume the rest of the initializers permissively.
835 // FIXME: We should be able to perform code-completion here even if
836 // there isn't a subsequent '{' token.
837 MightBeTemplateArgument = true;
842 } while (Tok.is(tok::coloncolon));
844 if (Tok.is(tok::less))
845 MightBeTemplateArgument = true;
847 if (MightBeTemplateArgument) {
848 // We may be inside a template argument list. Grab up to the start of the
849 // next parenthesized initializer or braced-init-list. This *might* be the
850 // initializer, or it might be a subexpression in the template argument
852 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
853 // if all angles are closed.
854 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
856 /*ConsumeFinalToken=*/false)) {
857 // We're not just missing the initializer, we're also missing the
859 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
861 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
862 // We found something weird in a mem-initializer-id.
863 if (getLangOpts().CPlusPlus11)
864 return Diag(Tok.getLocation(), diag::err_expected_either)
865 << tok::l_paren << tok::l_brace;
867 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
870 tok::TokenKind kind = Tok.getKind();
872 bool IsLParen = (kind == tok::l_paren);
873 SourceLocation OpenLoc = Tok.getLocation();
878 assert(kind == tok::l_brace && "Must be left paren or brace here.");
880 // In C++03, this has to be the start of the function body, which
881 // means the initializer is malformed; we'll diagnose it later.
882 if (!getLangOpts().CPlusPlus11)
886 // Grab the initializer (or the subexpression of the template argument).
887 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
888 // if we might be inside the braces of a lambda-expression.
889 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
890 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
891 Diag(Tok, diag::err_expected) << CloseKind;
892 Diag(OpenLoc, diag::note_matching) << kind;
896 // Grab pack ellipsis, if present.
897 if (Tok.is(tok::ellipsis)) {
902 // If we know we just consumed a mem-initializer, we must have ',' or '{'
904 if (Tok.is(tok::comma)) {
907 } else if (Tok.is(tok::l_brace)) {
908 // This is the function body if the ')' or '}' is immediately followed by
909 // a '{'. That cannot happen within a template argument, apart from the
910 // case where a template argument contains a compound literal:
912 // S ( ) : a < b < c > ( d ) { }
913 // // End of declaration, or still inside the template argument?
915 // ... and the case where the template argument contains a lambda:
917 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
920 // FIXME: Disambiguate these cases. Note that the latter case is probably
921 // going to be made ill-formed by core issue 1607.
925 } else if (!MightBeTemplateArgument) {
926 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
932 /// \brief Consume and store tokens from the '?' to the ':' in a conditional
934 bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
936 assert(Tok.is(tok::question));
940 while (Tok.isNot(tok::colon)) {
941 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
943 /*ConsumeFinalToken=*/false))
946 // If we found a nested conditional, consume it.
947 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
957 /// \brief A tentative parsing action that can also revert token annotations.
958 class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
960 explicit UnannotatedTentativeParsingAction(Parser &Self,
961 tok::TokenKind EndKind)
962 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
963 // Stash away the old token stream, so we can restore it once the
964 // tentative parse is complete.
965 TentativeParsingAction Inner(Self);
966 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
970 void RevertAnnotations() {
973 // Put back the original tokens.
974 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
976 Token *Buffer = new Token[Toks.size()];
977 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
978 Buffer[Toks.size() - 1] = Self.Tok;
979 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
981 Self.Tok = Toks.front();
988 tok::TokenKind EndKind;
991 /// ConsumeAndStoreInitializer - Consume and store the token at the passed token
992 /// container until the end of the current initializer expression (either a
993 /// default argument or an in-class initializer for a non-static data member).
995 /// Returns \c true if we reached the end of something initializer-shaped,
996 /// \c false if we bailed out.
997 bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
998 CachedInitKind CIK) {
999 // We always want this function to consume at least one token if not at EOF.
1000 bool IsFirstToken = true;
1002 // Number of possible unclosed <s we've seen so far. These might be templates,
1003 // and might not, but if there were none of them (or we know for sure that
1004 // we're within a template), we can avoid a tentative parse.
1005 unsigned AngleCount = 0;
1006 unsigned KnownTemplateCount = 0;
1009 switch (Tok.getKind()) {
1011 // If we might be in a template, perform a tentative parse to check.
1013 // Not a template argument: this is the end of the initializer.
1015 if (KnownTemplateCount)
1018 // We hit a comma inside angle brackets. This is the hard case. The
1019 // rule we follow is:
1020 // * For a default argument, if the tokens after the comma form a
1021 // syntactically-valid parameter-declaration-clause, in which each
1022 // parameter has an initializer, then this comma ends the default
1024 // * For a default initializer, if the tokens after the comma form a
1025 // syntactically-valid init-declarator-list, then this comma ends
1026 // the default initializer.
1028 UnannotatedTentativeParsingAction PA(*this,
1029 CIK == CIK_DefaultInitializer
1030 ? tok::semi : tok::r_paren);
1031 Sema::TentativeAnalysisScope Scope(Actions);
1033 TPResult Result = TPResult::Error;
1036 case CIK_DefaultInitializer:
1037 Result = TryParseInitDeclaratorList();
1038 // If we parsed a complete, ambiguous init-declarator-list, this
1039 // is only syntactically-valid if it's followed by a semicolon.
1040 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1041 Result = TPResult::False;
1044 case CIK_DefaultArgument:
1045 bool InvalidAsDeclaration = false;
1046 Result = TryParseParameterDeclarationClause(
1047 &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
1048 // If this is an expression or a declaration with a missing
1049 // 'typename', assume it's not a declaration.
1050 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1051 Result = TPResult::False;
1055 // If what follows could be a declaration, it is a declaration.
1056 if (Result != TPResult::False && Result != TPResult::Error) {
1061 // In the uncommon case that we decide the following tokens are part
1062 // of a template argument, revert any annotations we've performed in
1063 // those tokens. We're not going to look them up until we've parsed
1064 // the rest of the class, and that might add more declarations.
1065 PA.RevertAnnotations();
1068 // Keep going. We know we're inside a template argument list now.
1069 ++KnownTemplateCount;
1073 case tok::annot_module_begin:
1074 case tok::annot_module_end:
1075 case tok::annot_module_include:
1076 // Ran out of tokens.
1080 // FIXME: A '<' can only start a template-id if it's preceded by an
1081 // identifier, an operator-function-id, or a literal-operator-id.
1086 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1087 // that is *never* the end of the initializer. Skip to the ':'.
1088 if (!ConsumeAndStoreConditional(Toks))
1092 case tok::greatergreatergreater:
1093 if (!getLangOpts().CPlusPlus11)
1095 if (AngleCount) --AngleCount;
1096 if (KnownTemplateCount) --KnownTemplateCount;
1098 case tok::greatergreater:
1099 if (!getLangOpts().CPlusPlus11)
1101 if (AngleCount) --AngleCount;
1102 if (KnownTemplateCount) --KnownTemplateCount;
1105 if (AngleCount) --AngleCount;
1106 if (KnownTemplateCount) --KnownTemplateCount;
1109 case tok::kw_template:
1110 // 'template' identifier '<' is known to start a template argument list,
1111 // and can be used to disambiguate the parse.
1112 // FIXME: Support all forms of 'template' unqualified-id '<'.
1113 Toks.push_back(Tok);
1115 if (Tok.is(tok::identifier)) {
1116 Toks.push_back(Tok);
1118 if (Tok.is(tok::less)) {
1120 ++KnownTemplateCount;
1121 Toks.push_back(Tok);
1127 case tok::kw_operator:
1128 // If 'operator' precedes other punctuation, that punctuation loses
1129 // its special behavior.
1130 Toks.push_back(Tok);
1132 switch (Tok.getKind()) {
1134 case tok::greatergreatergreater:
1135 case tok::greatergreater:
1138 Toks.push_back(Tok);
1147 // Recursively consume properly-nested parens.
1148 Toks.push_back(Tok);
1150 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1153 // Recursively consume properly-nested square brackets.
1154 Toks.push_back(Tok);
1156 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1159 // Recursively consume properly-nested braces.
1160 Toks.push_back(Tok);
1162 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1165 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1166 // Since the user wasn't looking for this token (if they were, it would
1167 // already be handled), this isn't balanced. If there is a LHS token at a
1168 // higher level, we will assume that this matches the unbalanced token
1169 // and return it. Otherwise, this is a spurious RHS token, which we
1170 // consume and pass on to downstream code to diagnose.
1172 if (CIK == CIK_DefaultArgument)
1173 return true; // End of the default argument.
1174 if (ParenCount && !IsFirstToken)
1176 Toks.push_back(Tok);
1180 if (BracketCount && !IsFirstToken)
1182 Toks.push_back(Tok);
1186 if (BraceCount && !IsFirstToken)
1188 Toks.push_back(Tok);
1192 case tok::code_completion:
1193 Toks.push_back(Tok);
1194 ConsumeCodeCompletionToken();
1197 case tok::string_literal:
1198 case tok::wide_string_literal:
1199 case tok::utf8_string_literal:
1200 case tok::utf16_string_literal:
1201 case tok::utf32_string_literal:
1202 Toks.push_back(Tok);
1203 ConsumeStringToken();
1206 if (CIK == CIK_DefaultInitializer)
1207 return true; // End of the default initializer.
1211 Toks.push_back(Tok);
1215 IsFirstToken = false;