]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseCXXInlineMethods.cpp
MFV r316875: 7336 vfork and O_CLOEXEC causes zfs_mount EBUSY
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Parse / ParseCXXInlineMethods.cpp
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 "clang/AST/DeclTemplate.h"
16 #include "clang/Parse/ParseDiagnostic.h"
17 #include "clang/Parse/RAIIObjectsForParser.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                                       SourceLocation PureSpecLoc) {
31   assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
32   assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) &&
33          "Current token not a '{', ':', '=', or 'try'!");
34
35   MultiTemplateParamsArg TemplateParams(
36       TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
37                                   : nullptr,
38       TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
39
40   NamedDecl *FnD;
41   if (D.getDeclSpec().isFriendSpecified())
42     FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
43                                           TemplateParams);
44   else {
45     FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
46                                            TemplateParams, nullptr,
47                                            VS, ICIS_NoInit);
48     if (FnD) {
49       Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
50       if (PureSpecLoc.isValid())
51         Actions.ActOnPureSpecifier(FnD, PureSpecLoc);
52     }
53   }
54
55   if (FnD)
56     HandleMemberFunctionDeclDelays(D, FnD);
57
58   D.complete(FnD);
59
60   if (TryConsumeToken(tok::equal)) {
61     if (!FnD) {
62       SkipUntil(tok::semi);
63       return nullptr;
64     }
65
66     bool Delete = false;
67     SourceLocation KWLoc;
68     SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
69     if (TryConsumeToken(tok::kw_delete, KWLoc)) {
70       Diag(KWLoc, getLangOpts().CPlusPlus11
71                       ? diag::warn_cxx98_compat_defaulted_deleted_function
72                       : diag::ext_defaulted_deleted_function)
73         << 1 /* deleted */;
74       Actions.SetDeclDeleted(FnD, KWLoc);
75       Delete = true;
76       if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
77         DeclAsFunction->setRangeEnd(KWEndLoc);
78       }
79     } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
80       Diag(KWLoc, getLangOpts().CPlusPlus11
81                       ? diag::warn_cxx98_compat_defaulted_deleted_function
82                       : diag::ext_defaulted_deleted_function)
83         << 0 /* defaulted */;
84       Actions.SetDeclDefaulted(FnD, KWLoc);
85       if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
86         DeclAsFunction->setRangeEnd(KWEndLoc);
87       }
88     } else {
89       llvm_unreachable("function definition after = not 'delete' or 'default'");
90     }
91
92     if (Tok.is(tok::comma)) {
93       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
94         << Delete;
95       SkipUntil(tok::semi);
96     } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
97                                 Delete ? "delete" : "default")) {
98       SkipUntil(tok::semi);
99     }
100
101     return FnD;
102   }
103
104   if (SkipFunctionBodies && (!FnD || Actions.canSkipFunctionBody(FnD)) &&
105       trySkippingFunctionBody()) {
106     Actions.ActOnSkippedFunctionBody(FnD);
107     return FnD;
108   }
109
110   // In delayed template parsing mode, if we are within a class template
111   // or if we are about to parse function member template then consume
112   // the tokens and store them for parsing at the end of the translation unit.
113   if (getLangOpts().DelayedTemplateParsing &&
114       D.getFunctionDefinitionKind() == FDK_Definition &&
115       !D.getDeclSpec().isConstexprSpecified() &&
116       !(FnD && FnD->getAsFunction() &&
117         FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
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 = FnD->getAsFunction();
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     FunctionDecl *FD = FnD->getAsFunction();
170     // Track that this function will eventually have a body; Sema needs
171     // to know this.
172     Actions.CheckForFunctionRedefinition(FD);
173     FD->setWillHaveBody(true);
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.isOneOf(tok::l_brace, 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   Eof.setEofData(VarD);
222   Toks.push_back(Eof);
223 }
224
225 Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
226 void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
227 void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
228 void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
229
230 Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
231   : Self(P), Class(C) {}
232
233 Parser::LateParsedClass::~LateParsedClass() {
234   Self->DeallocateParsedClasses(Class);
235 }
236
237 void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
238   Self->ParseLexedMethodDeclarations(*Class);
239 }
240
241 void Parser::LateParsedClass::ParseLexedMemberInitializers() {
242   Self->ParseLexedMemberInitializers(*Class);
243 }
244
245 void Parser::LateParsedClass::ParseLexedMethodDefs() {
246   Self->ParseLexedMethodDefs(*Class);
247 }
248
249 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
250   Self->ParseLexedMethodDeclaration(*this);
251 }
252
253 void Parser::LexedMethod::ParseLexedMethodDefs() {
254   Self->ParseLexedMethodDef(*this);
255 }
256
257 void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
258   Self->ParseLexedMemberInitializer(*this);
259 }
260
261 /// ParseLexedMethodDeclarations - We finished parsing the member
262 /// specification of a top (non-nested) C++ class. Now go over the
263 /// stack of method declarations with some parts for which parsing was
264 /// delayed (such as default arguments) and parse them.
265 void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
266   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
267   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
268                                 HasTemplateScope);
269   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
270   if (HasTemplateScope) {
271     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
272     ++CurTemplateDepthTracker;
273   }
274
275   // The current scope is still active if we're the top-level class.
276   // Otherwise we'll need to push and enter a new scope.
277   bool HasClassScope = !Class.TopLevelClass;
278   ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
279                         HasClassScope);
280   if (HasClassScope)
281     Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
282                                                 Class.TagOrTemplate);
283
284   for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
285     Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
286   }
287
288   if (HasClassScope)
289     Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
290                                                  Class.TagOrTemplate);
291 }
292
293 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
294   // If this is a member template, introduce the template parameter scope.
295   ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
296   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
297   if (LM.TemplateScope) {
298     Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
299     ++CurTemplateDepthTracker;
300   }
301   // Start the delayed C++ method declaration
302   Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
303
304   // Introduce the parameters into scope and parse their default
305   // arguments.
306   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
307                             Scope::FunctionDeclarationScope | Scope::DeclScope);
308   for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
309     auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
310     // Introduce the parameter into scope.
311     bool HasUnparsed = Param->hasUnparsedDefaultArg();
312     Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
313     std::unique_ptr<CachedTokens> Toks = std::move(LM.DefaultArgs[I].Toks);
314     if (Toks) {
315       // Mark the end of the default argument so that we know when to stop when
316       // we parse it later on.
317       Token LastDefaultArgToken = Toks->back();
318       Token DefArgEnd;
319       DefArgEnd.startToken();
320       DefArgEnd.setKind(tok::eof);
321       DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
322       DefArgEnd.setEofData(Param);
323       Toks->push_back(DefArgEnd);
324
325       // Parse the default argument from its saved token stream.
326       Toks->push_back(Tok); // So that the current token doesn't get lost
327       PP.EnterTokenStream(*Toks, true);
328
329       // Consume the previously-pushed token.
330       ConsumeAnyToken();
331
332       // Consume the '='.
333       assert(Tok.is(tok::equal) && "Default argument not starting with '='");
334       SourceLocation EqualLoc = ConsumeToken();
335
336       // The argument isn't actually potentially evaluated unless it is
337       // used.
338       EnterExpressionEvaluationContext Eval(
339           Actions,
340           Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, Param);
341
342       ExprResult DefArgResult;
343       if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
344         Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
345         DefArgResult = ParseBraceInitializer();
346       } else
347         DefArgResult = ParseAssignmentExpression();
348       DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
349       if (DefArgResult.isInvalid()) {
350         Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
351       } else {
352         if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
353           // The last two tokens are the terminator and the saved value of
354           // Tok; the last token in the default argument is the one before
355           // those.
356           assert(Toks->size() >= 3 && "expected a token in default arg");
357           Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
358             << SourceRange(Tok.getLocation(),
359                            (*Toks)[Toks->size() - 3].getLocation());
360         }
361         Actions.ActOnParamDefaultArgument(Param, EqualLoc,
362                                           DefArgResult.get());
363       }
364
365       // There could be leftover tokens (e.g. because of an error).
366       // Skip through until we reach the 'end of default argument' token.
367       while (Tok.isNot(tok::eof))
368         ConsumeAnyToken();
369
370       if (Tok.is(tok::eof) && Tok.getEofData() == Param)
371         ConsumeAnyToken();
372     } else if (HasUnparsed) {
373       assert(Param->hasInheritedDefaultArg());
374       FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
375       ParmVarDecl *OldParam = Old->getParamDecl(I);
376       assert (!OldParam->hasUnparsedDefaultArg());
377       if (OldParam->hasUninstantiatedDefaultArg())
378         Param->setUninstantiatedDefaultArg(
379             OldParam->getUninstantiatedDefaultArg());
380       else
381         Param->setDefaultArg(OldParam->getInit());
382     }
383   }
384
385   // Parse a delayed exception-specification, if there is one.
386   if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
387     // Add the 'stop' token.
388     Token LastExceptionSpecToken = Toks->back();
389     Token ExceptionSpecEnd;
390     ExceptionSpecEnd.startToken();
391     ExceptionSpecEnd.setKind(tok::eof);
392     ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
393     ExceptionSpecEnd.setEofData(LM.Method);
394     Toks->push_back(ExceptionSpecEnd);
395
396     // Parse the default argument from its saved token stream.
397     Toks->push_back(Tok); // So that the current token doesn't get lost
398     PP.EnterTokenStream(*Toks, true);
399
400     // Consume the previously-pushed token.
401     ConsumeAnyToken();
402
403     // C++11 [expr.prim.general]p3:
404     //   If a declaration declares a member function or member function
405     //   template of a class X, the expression this is a prvalue of type
406     //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
407     //   and the end of the function-definition, member-declarator, or
408     //   declarator.
409     CXXMethodDecl *Method;
410     if (FunctionTemplateDecl *FunTmpl
411           = dyn_cast<FunctionTemplateDecl>(LM.Method))
412       Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
413     else
414       Method = cast<CXXMethodDecl>(LM.Method);
415
416     Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
417                                      Method->getTypeQualifiers(),
418                                      getLangOpts().CPlusPlus11);
419
420     // Parse the exception-specification.
421     SourceRange SpecificationRange;
422     SmallVector<ParsedType, 4> DynamicExceptions;
423     SmallVector<SourceRange, 4> DynamicExceptionRanges;
424     ExprResult NoexceptExpr;
425     CachedTokens *ExceptionSpecTokens;
426
427     ExceptionSpecificationType EST
428       = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
429                                        DynamicExceptions,
430                                        DynamicExceptionRanges, NoexceptExpr,
431                                        ExceptionSpecTokens);
432
433     if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
434       Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
435
436     // Attach the exception-specification to the method.
437     Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
438                                                SpecificationRange,
439                                                DynamicExceptions,
440                                                DynamicExceptionRanges,
441                                                NoexceptExpr.isUsable()?
442                                                  NoexceptExpr.get() : nullptr);
443
444     // There could be leftover tokens (e.g. because of an error).
445     // Skip through until we reach the original token position.
446     while (Tok.isNot(tok::eof))
447       ConsumeAnyToken();
448
449     // Clean up the remaining EOF token.
450     if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
451       ConsumeAnyToken();
452
453     delete Toks;
454     LM.ExceptionSpecTokens = nullptr;
455   }
456
457   PrototypeScope.Exit();
458
459   // Finish the delayed C++ method declaration.
460   Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
461 }
462
463 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
464 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
465 /// collected during its parsing and parse them all.
466 void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
467   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
468   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
469   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
470   if (HasTemplateScope) {
471     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
472     ++CurTemplateDepthTracker;
473   }
474   bool HasClassScope = !Class.TopLevelClass;
475   ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
476                         HasClassScope);
477
478   for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
479     Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
480   }
481 }
482
483 void Parser::ParseLexedMethodDef(LexedMethod &LM) {
484   // If this is a member template, introduce the template parameter scope.
485   ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
486   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
487   if (LM.TemplateScope) {
488     Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
489     ++CurTemplateDepthTracker;
490   }
491
492   assert(!LM.Toks.empty() && "Empty body!");
493   Token LastBodyToken = LM.Toks.back();
494   Token BodyEnd;
495   BodyEnd.startToken();
496   BodyEnd.setKind(tok::eof);
497   BodyEnd.setLocation(LastBodyToken.getEndLoc());
498   BodyEnd.setEofData(LM.D);
499   LM.Toks.push_back(BodyEnd);
500   // Append the current token at the end of the new token stream so that it
501   // doesn't get lost.
502   LM.Toks.push_back(Tok);
503   PP.EnterTokenStream(LM.Toks, true);
504
505   // Consume the previously pushed token.
506   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
507   assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
508          && "Inline method not starting with '{', ':' or 'try'");
509
510   // Parse the method body. Function body parsing code is similar enough
511   // to be re-used for method bodies as well.
512   ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
513                                Scope::CompoundStmtScope);
514   Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
515
516   if (Tok.is(tok::kw_try)) {
517     ParseFunctionTryBlock(LM.D, FnScope);
518
519     while (Tok.isNot(tok::eof))
520       ConsumeAnyToken();
521
522     if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
523       ConsumeAnyToken();
524     return;
525   }
526   if (Tok.is(tok::colon)) {
527     ParseConstructorInitializer(LM.D);
528
529     // Error recovery.
530     if (!Tok.is(tok::l_brace)) {
531       FnScope.Exit();
532       Actions.ActOnFinishFunctionBody(LM.D, nullptr);
533
534       while (Tok.isNot(tok::eof))
535         ConsumeAnyToken();
536
537       if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
538         ConsumeAnyToken();
539       return;
540     }
541   } else
542     Actions.ActOnDefaultCtorInitializers(LM.D);
543
544   assert((Actions.getDiagnostics().hasErrorOccurred() ||
545           !isa<FunctionTemplateDecl>(LM.D) ||
546           cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
547             < TemplateParameterDepth) &&
548          "TemplateParameterDepth should be greater than the depth of "
549          "current template being instantiated!");
550
551   ParseFunctionStatementBody(LM.D, FnScope);
552
553   while (Tok.isNot(tok::eof))
554     ConsumeAnyToken();
555
556   if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
557     ConsumeAnyToken();
558
559   if (auto *FD = dyn_cast_or_null<FunctionDecl>(LM.D))
560     if (isa<CXXMethodDecl>(FD) ||
561         FD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend))
562       Actions.ActOnFinishInlineFunctionDef(FD);
563 }
564
565 /// ParseLexedMemberInitializers - We finished parsing the member specification
566 /// of a top (non-nested) C++ class. Now go over the stack of lexed data member
567 /// initializers that were collected during its parsing and parse them all.
568 void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
569   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
570   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
571                                 HasTemplateScope);
572   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
573   if (HasTemplateScope) {
574     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
575     ++CurTemplateDepthTracker;
576   }
577   // Set or update the scope flags.
578   bool AlreadyHasClassScope = Class.TopLevelClass;
579   unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
580   ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
581   ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
582
583   if (!AlreadyHasClassScope)
584     Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
585                                                 Class.TagOrTemplate);
586
587   if (!Class.LateParsedDeclarations.empty()) {
588     // C++11 [expr.prim.general]p4:
589     //   Otherwise, if a member-declarator declares a non-static data member 
590     //  (9.2) of a class X, the expression this is a prvalue of type "pointer
591     //  to X" within the optional brace-or-equal-initializer. It shall not 
592     //  appear elsewhere in the member-declarator.
593     Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
594                                      /*TypeQuals=*/(unsigned)0);
595
596     for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
597       Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
598     }
599   }
600   
601   if (!AlreadyHasClassScope)
602     Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
603                                                  Class.TagOrTemplate);
604
605   Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
606 }
607
608 void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
609   if (!MI.Field || MI.Field->isInvalidDecl())
610     return;
611
612   // Append the current token at the end of the new token stream so that it
613   // doesn't get lost.
614   MI.Toks.push_back(Tok);
615   PP.EnterTokenStream(MI.Toks, true);
616
617   // Consume the previously pushed token.
618   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
619
620   SourceLocation EqualLoc;
621
622   Actions.ActOnStartCXXInClassMemberInitializer();
623
624   ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false, 
625                                               EqualLoc);
626
627   Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
628                                                  Init.get());
629
630   // The next token should be our artificial terminating EOF token.
631   if (Tok.isNot(tok::eof)) {
632     if (!Init.isInvalid()) {
633       SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
634       if (!EndLoc.isValid())
635         EndLoc = Tok.getLocation();
636       // No fixit; we can't recover as if there were a semicolon here.
637       Diag(EndLoc, diag::err_expected_semi_decl_list);
638     }
639
640     // Consume tokens until we hit the artificial EOF.
641     while (Tok.isNot(tok::eof))
642       ConsumeAnyToken();
643   }
644   // Make sure this is *our* artificial EOF token.
645   if (Tok.getEofData() == MI.Field)
646     ConsumeAnyToken();
647 }
648
649 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
650 /// container until the token 'T' is reached (which gets
651 /// consumed/stored too, if ConsumeFinalToken).
652 /// If StopAtSemi is true, then we will stop early at a ';' character.
653 /// Returns true if token 'T1' or 'T2' was found.
654 /// NOTE: This is a specialized version of Parser::SkipUntil.
655 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
656                                   CachedTokens &Toks,
657                                   bool StopAtSemi, bool ConsumeFinalToken) {
658   // We always want this function to consume at least one token if the first
659   // token isn't T and if not at EOF.
660   bool isFirstTokenConsumed = true;
661   while (1) {
662     // If we found one of the tokens, stop and return true.
663     if (Tok.is(T1) || Tok.is(T2)) {
664       if (ConsumeFinalToken) {
665         Toks.push_back(Tok);
666         ConsumeAnyToken();
667       }
668       return true;
669     }
670
671     switch (Tok.getKind()) {
672     case tok::eof:
673     case tok::annot_module_begin:
674     case tok::annot_module_end:
675     case tok::annot_module_include:
676       // Ran out of tokens.
677       return false;
678
679     case tok::l_paren:
680       // Recursively consume properly-nested parens.
681       Toks.push_back(Tok);
682       ConsumeParen();
683       ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
684       break;
685     case tok::l_square:
686       // Recursively consume properly-nested square brackets.
687       Toks.push_back(Tok);
688       ConsumeBracket();
689       ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
690       break;
691     case tok::l_brace:
692       // Recursively consume properly-nested braces.
693       Toks.push_back(Tok);
694       ConsumeBrace();
695       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
696       break;
697
698     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
699     // Since the user wasn't looking for this token (if they were, it would
700     // already be handled), this isn't balanced.  If there is a LHS token at a
701     // higher level, we will assume that this matches the unbalanced token
702     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
703     case tok::r_paren:
704       if (ParenCount && !isFirstTokenConsumed)
705         return false;  // Matches something.
706       Toks.push_back(Tok);
707       ConsumeParen();
708       break;
709     case tok::r_square:
710       if (BracketCount && !isFirstTokenConsumed)
711         return false;  // Matches something.
712       Toks.push_back(Tok);
713       ConsumeBracket();
714       break;
715     case tok::r_brace:
716       if (BraceCount && !isFirstTokenConsumed)
717         return false;  // Matches something.
718       Toks.push_back(Tok);
719       ConsumeBrace();
720       break;
721
722     case tok::semi:
723       if (StopAtSemi)
724         return false;
725       // FALL THROUGH.
726     default:
727       // consume this token.
728       Toks.push_back(Tok);
729       ConsumeAnyToken(/*ConsumeCodeCompletionTok*/true);
730       break;
731     }
732     isFirstTokenConsumed = false;
733   }
734 }
735
736 /// \brief Consume tokens and store them in the passed token container until
737 /// we've passed the try keyword and constructor initializers and have consumed
738 /// the opening brace of the function body. The opening brace will be consumed
739 /// if and only if there was no error.
740 ///
741 /// \return True on error.
742 bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
743   if (Tok.is(tok::kw_try)) {
744     Toks.push_back(Tok);
745     ConsumeToken();
746   }
747
748   if (Tok.isNot(tok::colon)) {
749     // Easy case, just a function body.
750
751     // Grab any remaining garbage to be diagnosed later. We stop when we reach a
752     // brace: an opening one is the function body, while a closing one probably
753     // means we've reached the end of the class.
754     ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
755                          /*StopAtSemi=*/true,
756                          /*ConsumeFinalToken=*/false);
757     if (Tok.isNot(tok::l_brace))
758       return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
759
760     Toks.push_back(Tok);
761     ConsumeBrace();
762     return false;
763   }
764
765   Toks.push_back(Tok);
766   ConsumeToken();
767
768   // We can't reliably skip over a mem-initializer-id, because it could be
769   // a template-id involving not-yet-declared names. Given:
770   //
771   //   S ( ) : a < b < c > ( e )
772   //
773   // 'e' might be an initializer or part of a template argument, depending
774   // on whether 'b' is a template.
775
776   // Track whether we might be inside a template argument. We can give
777   // significantly better diagnostics if we know that we're not.
778   bool MightBeTemplateArgument = false;
779
780   while (true) {
781     // Skip over the mem-initializer-id, if possible.
782     if (Tok.is(tok::kw_decltype)) {
783       Toks.push_back(Tok);
784       SourceLocation OpenLoc = ConsumeToken();
785       if (Tok.isNot(tok::l_paren))
786         return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
787                  << "decltype";
788       Toks.push_back(Tok);
789       ConsumeParen();
790       if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
791         Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
792         Diag(OpenLoc, diag::note_matching) << tok::l_paren;
793         return true;
794       }
795     }
796     do {
797       // Walk over a component of a nested-name-specifier.
798       if (Tok.is(tok::coloncolon)) {
799         Toks.push_back(Tok);
800         ConsumeToken();
801
802         if (Tok.is(tok::kw_template)) {
803           Toks.push_back(Tok);
804           ConsumeToken();
805         }
806       }
807
808       if (Tok.is(tok::identifier)) {
809         Toks.push_back(Tok);
810         ConsumeToken();
811       } else {
812         break;
813       }
814     } while (Tok.is(tok::coloncolon));
815
816     if (Tok.is(tok::code_completion)) {
817       Toks.push_back(Tok);
818       ConsumeCodeCompletionToken();
819       if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype)) {
820         // Could be the start of another member initializer (the ',' has not
821         // been written yet)
822         continue;
823       }
824     }
825
826     if (Tok.is(tok::comma)) {
827       // The initialization is missing, we'll diagnose it later.
828       Toks.push_back(Tok);
829       ConsumeToken();
830       continue;
831     }
832     if (Tok.is(tok::less))
833       MightBeTemplateArgument = true;
834
835     if (MightBeTemplateArgument) {
836       // We may be inside a template argument list. Grab up to the start of the
837       // next parenthesized initializer or braced-init-list. This *might* be the
838       // initializer, or it might be a subexpression in the template argument
839       // list.
840       // FIXME: Count angle brackets, and clear MightBeTemplateArgument
841       //        if all angles are closed.
842       if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
843                                 /*StopAtSemi=*/true,
844                                 /*ConsumeFinalToken=*/false)) {
845         // We're not just missing the initializer, we're also missing the
846         // function body!
847         return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
848       }
849     } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
850       // We found something weird in a mem-initializer-id.
851       if (getLangOpts().CPlusPlus11)
852         return Diag(Tok.getLocation(), diag::err_expected_either)
853                << tok::l_paren << tok::l_brace;
854       else
855         return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
856     }
857
858     tok::TokenKind kind = Tok.getKind();
859     Toks.push_back(Tok);
860     bool IsLParen = (kind == tok::l_paren);
861     SourceLocation OpenLoc = Tok.getLocation();
862
863     if (IsLParen) {
864       ConsumeParen();
865     } else {
866       assert(kind == tok::l_brace && "Must be left paren or brace here.");
867       ConsumeBrace();
868       // In C++03, this has to be the start of the function body, which
869       // means the initializer is malformed; we'll diagnose it later.
870       if (!getLangOpts().CPlusPlus11)
871         return false;
872
873       const Token &PreviousToken = Toks[Toks.size() - 2];
874       if (!MightBeTemplateArgument &&
875           !PreviousToken.isOneOf(tok::identifier, tok::greater,
876                                  tok::greatergreater)) {
877         // If the opening brace is not preceded by one of these tokens, we are
878         // missing the mem-initializer-id. In order to recover better, we need
879         // to use heuristics to determine if this '{' is most likely the
880         // beginning of a brace-init-list or the function body.
881         // Check the token after the corresponding '}'.
882         TentativeParsingAction PA(*this);
883         if (SkipUntil(tok::r_brace) &&
884             !Tok.isOneOf(tok::comma, tok::ellipsis, tok::l_brace)) {
885           // Consider there was a malformed initializer and this is the start
886           // of the function body. We'll diagnose it later.
887           PA.Revert();
888           return false;
889         }
890         PA.Revert();
891       }
892     }
893
894     // Grab the initializer (or the subexpression of the template argument).
895     // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
896     //        if we might be inside the braces of a lambda-expression.
897     tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
898     if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
899       Diag(Tok, diag::err_expected) << CloseKind;
900       Diag(OpenLoc, diag::note_matching) << kind;
901       return true;
902     }
903
904     // Grab pack ellipsis, if present.
905     if (Tok.is(tok::ellipsis)) {
906       Toks.push_back(Tok);
907       ConsumeToken();
908     }
909
910     // If we know we just consumed a mem-initializer, we must have ',' or '{'
911     // next.
912     if (Tok.is(tok::comma)) {
913       Toks.push_back(Tok);
914       ConsumeToken();
915     } else if (Tok.is(tok::l_brace)) {
916       // This is the function body if the ')' or '}' is immediately followed by
917       // a '{'. That cannot happen within a template argument, apart from the
918       // case where a template argument contains a compound literal:
919       //
920       //   S ( ) : a < b < c > ( d ) { }
921       //   // End of declaration, or still inside the template argument?
922       //
923       // ... and the case where the template argument contains a lambda:
924       //
925       //   S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
926       //     ( ) > ( ) { }
927       //
928       // FIXME: Disambiguate these cases. Note that the latter case is probably
929       //        going to be made ill-formed by core issue 1607.
930       Toks.push_back(Tok);
931       ConsumeBrace();
932       return false;
933     } else if (!MightBeTemplateArgument) {
934       return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
935                                                                 << tok::comma;
936     }
937   }
938 }
939
940 /// \brief Consume and store tokens from the '?' to the ':' in a conditional
941 /// expression.
942 bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
943   // Consume '?'.
944   assert(Tok.is(tok::question));
945   Toks.push_back(Tok);
946   ConsumeToken();
947
948   while (Tok.isNot(tok::colon)) {
949     if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
950                               /*StopAtSemi=*/true,
951                               /*ConsumeFinalToken=*/false))
952       return false;
953
954     // If we found a nested conditional, consume it.
955     if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
956       return false;
957   }
958
959   // Consume ':'.
960   Toks.push_back(Tok);
961   ConsumeToken();
962   return true;
963 }
964
965 /// \brief A tentative parsing action that can also revert token annotations.
966 class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
967 public:
968   explicit UnannotatedTentativeParsingAction(Parser &Self,
969                                              tok::TokenKind EndKind)
970       : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
971     // Stash away the old token stream, so we can restore it once the
972     // tentative parse is complete.
973     TentativeParsingAction Inner(Self);
974     Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
975     Inner.Revert();
976   }
977
978   void RevertAnnotations() {
979     Revert();
980
981     // Put back the original tokens.
982     Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
983     if (Toks.size()) {
984       auto Buffer = llvm::make_unique<Token[]>(Toks.size());
985       std::copy(Toks.begin() + 1, Toks.end(), Buffer.get());
986       Buffer[Toks.size() - 1] = Self.Tok;
987       Self.PP.EnterTokenStream(std::move(Buffer), Toks.size(), true);
988
989       Self.Tok = Toks.front();
990     }
991   }
992
993 private:
994   Parser &Self;
995   CachedTokens Toks;
996   tok::TokenKind EndKind;
997 };
998
999 /// ConsumeAndStoreInitializer - Consume and store the token at the passed token
1000 /// container until the end of the current initializer expression (either a
1001 /// default argument or an in-class initializer for a non-static data member).
1002 ///
1003 /// Returns \c true if we reached the end of something initializer-shaped,
1004 /// \c false if we bailed out.
1005 bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
1006                                         CachedInitKind CIK) {
1007   // We always want this function to consume at least one token if not at EOF.
1008   bool IsFirstToken = true;
1009
1010   // Number of possible unclosed <s we've seen so far. These might be templates,
1011   // and might not, but if there were none of them (or we know for sure that
1012   // we're within a template), we can avoid a tentative parse.
1013   unsigned AngleCount = 0;
1014   unsigned KnownTemplateCount = 0;
1015
1016   while (1) {
1017     switch (Tok.getKind()) {
1018     case tok::comma:
1019       // If we might be in a template, perform a tentative parse to check.
1020       if (!AngleCount)
1021         // Not a template argument: this is the end of the initializer.
1022         return true;
1023       if (KnownTemplateCount)
1024         goto consume_token;
1025
1026       // We hit a comma inside angle brackets. This is the hard case. The
1027       // rule we follow is:
1028       //  * For a default argument, if the tokens after the comma form a
1029       //    syntactically-valid parameter-declaration-clause, in which each
1030       //    parameter has an initializer, then this comma ends the default
1031       //    argument.
1032       //  * For a default initializer, if the tokens after the comma form a
1033       //    syntactically-valid init-declarator-list, then this comma ends
1034       //    the default initializer.
1035       {
1036         UnannotatedTentativeParsingAction PA(*this,
1037                                              CIK == CIK_DefaultInitializer
1038                                                ? tok::semi : tok::r_paren);
1039         Sema::TentativeAnalysisScope Scope(Actions);
1040
1041         TPResult Result = TPResult::Error;
1042         ConsumeToken();
1043         switch (CIK) {
1044         case CIK_DefaultInitializer:
1045           Result = TryParseInitDeclaratorList();
1046           // If we parsed a complete, ambiguous init-declarator-list, this
1047           // is only syntactically-valid if it's followed by a semicolon.
1048           if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1049             Result = TPResult::False;
1050           break;
1051
1052         case CIK_DefaultArgument:
1053           bool InvalidAsDeclaration = false;
1054           Result = TryParseParameterDeclarationClause(
1055               &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
1056           // If this is an expression or a declaration with a missing
1057           // 'typename', assume it's not a declaration.
1058           if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1059             Result = TPResult::False;
1060           break;
1061         }
1062
1063         // If what follows could be a declaration, it is a declaration.
1064         if (Result != TPResult::False && Result != TPResult::Error) {
1065           PA.Revert();
1066           return true;
1067         }
1068
1069         // In the uncommon case that we decide the following tokens are part
1070         // of a template argument, revert any annotations we've performed in
1071         // those tokens. We're not going to look them up until we've parsed
1072         // the rest of the class, and that might add more declarations.
1073         PA.RevertAnnotations();
1074       }
1075
1076       // Keep going. We know we're inside a template argument list now.
1077       ++KnownTemplateCount;
1078       goto consume_token;
1079
1080     case tok::eof:
1081     case tok::annot_module_begin:
1082     case tok::annot_module_end:
1083     case tok::annot_module_include:
1084       // Ran out of tokens.
1085       return false;
1086
1087     case tok::less:
1088       // FIXME: A '<' can only start a template-id if it's preceded by an
1089       // identifier, an operator-function-id, or a literal-operator-id.
1090       ++AngleCount;
1091       goto consume_token;
1092
1093     case tok::question:
1094       // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1095       // that is *never* the end of the initializer. Skip to the ':'.
1096       if (!ConsumeAndStoreConditional(Toks))
1097         return false;
1098       break;
1099
1100     case tok::greatergreatergreater:
1101       if (!getLangOpts().CPlusPlus11)
1102         goto consume_token;
1103       if (AngleCount) --AngleCount;
1104       if (KnownTemplateCount) --KnownTemplateCount;
1105       // Fall through.
1106     case tok::greatergreater:
1107       if (!getLangOpts().CPlusPlus11)
1108         goto consume_token;
1109       if (AngleCount) --AngleCount;
1110       if (KnownTemplateCount) --KnownTemplateCount;
1111       // Fall through.
1112     case tok::greater:
1113       if (AngleCount) --AngleCount;
1114       if (KnownTemplateCount) --KnownTemplateCount;
1115       goto consume_token;
1116
1117     case tok::kw_template:
1118       // 'template' identifier '<' is known to start a template argument list,
1119       // and can be used to disambiguate the parse.
1120       // FIXME: Support all forms of 'template' unqualified-id '<'.
1121       Toks.push_back(Tok);
1122       ConsumeToken();
1123       if (Tok.is(tok::identifier)) {
1124         Toks.push_back(Tok);
1125         ConsumeToken();
1126         if (Tok.is(tok::less)) {
1127           ++AngleCount;
1128           ++KnownTemplateCount;
1129           Toks.push_back(Tok);
1130           ConsumeToken();
1131         }
1132       }
1133       break;
1134
1135     case tok::kw_operator:
1136       // If 'operator' precedes other punctuation, that punctuation loses
1137       // its special behavior.
1138       Toks.push_back(Tok);
1139       ConsumeToken();
1140       switch (Tok.getKind()) {
1141       case tok::comma:
1142       case tok::greatergreatergreater:
1143       case tok::greatergreater:
1144       case tok::greater:
1145       case tok::less:
1146         Toks.push_back(Tok);
1147         ConsumeToken();
1148         break;
1149       default:
1150         break;
1151       }
1152       break;
1153
1154     case tok::l_paren:
1155       // Recursively consume properly-nested parens.
1156       Toks.push_back(Tok);
1157       ConsumeParen();
1158       ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1159       break;
1160     case tok::l_square:
1161       // Recursively consume properly-nested square brackets.
1162       Toks.push_back(Tok);
1163       ConsumeBracket();
1164       ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1165       break;
1166     case tok::l_brace:
1167       // Recursively consume properly-nested braces.
1168       Toks.push_back(Tok);
1169       ConsumeBrace();
1170       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1171       break;
1172
1173     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1174     // Since the user wasn't looking for this token (if they were, it would
1175     // already be handled), this isn't balanced.  If there is a LHS token at a
1176     // higher level, we will assume that this matches the unbalanced token
1177     // and return it.  Otherwise, this is a spurious RHS token, which we
1178     // consume and pass on to downstream code to diagnose.
1179     case tok::r_paren:
1180       if (CIK == CIK_DefaultArgument)
1181         return true; // End of the default argument.
1182       if (ParenCount && !IsFirstToken)
1183         return false;
1184       Toks.push_back(Tok);
1185       ConsumeParen();
1186       continue;
1187     case tok::r_square:
1188       if (BracketCount && !IsFirstToken)
1189         return false;
1190       Toks.push_back(Tok);
1191       ConsumeBracket();
1192       continue;
1193     case tok::r_brace:
1194       if (BraceCount && !IsFirstToken)
1195         return false;
1196       Toks.push_back(Tok);
1197       ConsumeBrace();
1198       continue;
1199
1200     case tok::code_completion:
1201       Toks.push_back(Tok);
1202       ConsumeCodeCompletionToken();
1203       break;
1204
1205     case tok::string_literal:
1206     case tok::wide_string_literal:
1207     case tok::utf8_string_literal:
1208     case tok::utf16_string_literal:
1209     case tok::utf32_string_literal:
1210       Toks.push_back(Tok);
1211       ConsumeStringToken();
1212       break;
1213     case tok::semi:
1214       if (CIK == CIK_DefaultInitializer)
1215         return true; // End of the default initializer.
1216       // FALL THROUGH.
1217     default:
1218     consume_token:
1219       Toks.push_back(Tok);
1220       ConsumeToken();
1221       break;
1222     }
1223     IsFirstToken = false;
1224   }
1225 }