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