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