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