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