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