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