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