clang API Documentation

ParseCXXInlineMethods.cpp
Go to the documentation of this file.
00001 //===--- ParseCXXInlineMethods.cpp - C++ class inline methods parsing------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements parsing for C++ class inline methods.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Parse/Parser.h"
00015 #include "RAIIObjectsForParser.h"
00016 #include "clang/AST/DeclTemplate.h"
00017 #include "clang/Parse/ParseDiagnostic.h"
00018 #include "clang/Sema/DeclSpec.h"
00019 #include "clang/Sema/Scope.h"
00020 using namespace clang;
00021 
00022 /// ParseCXXInlineMethodDef - We parsed and verified that the specified
00023 /// Declarator is a well formed C++ inline method definition. Now lex its body
00024 /// and store its tokens for parsing after the C++ class is complete.
00025 NamedDecl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS,
00026                                       AttributeList *AccessAttrs,
00027                                       ParsingDeclarator &D,
00028                                       const ParsedTemplateInfo &TemplateInfo,
00029                                       const VirtSpecifiers& VS, 
00030                                       FunctionDefinitionKind DefinitionKind,
00031                                       ExprResult& Init) {
00032   assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
00033   assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try) ||
00034           Tok.is(tok::equal)) &&
00035          "Current token not a '{', ':', '=', or 'try'!");
00036 
00037   MultiTemplateParamsArg TemplateParams(
00038       TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
00039                                   : nullptr,
00040       TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
00041 
00042   NamedDecl *FnD;
00043   D.setFunctionDefinitionKind(DefinitionKind);
00044   if (D.getDeclSpec().isFriendSpecified())
00045     FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
00046                                           TemplateParams);
00047   else {
00048     FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
00049                                            TemplateParams, nullptr,
00050                                            VS, ICIS_NoInit);
00051     if (FnD) {
00052       Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
00053       bool TypeSpecContainsAuto = D.getDeclSpec().containsPlaceholderType();
00054       if (Init.isUsable())
00055         Actions.AddInitializerToDecl(FnD, Init.get(), false,
00056                                      TypeSpecContainsAuto);
00057       else
00058         Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto);
00059     }
00060   }
00061 
00062   HandleMemberFunctionDeclDelays(D, FnD);
00063 
00064   D.complete(FnD);
00065 
00066   if (TryConsumeToken(tok::equal)) {
00067     if (!FnD) {
00068       SkipUntil(tok::semi);
00069       return nullptr;
00070     }
00071 
00072     bool Delete = false;
00073     SourceLocation KWLoc;
00074     if (TryConsumeToken(tok::kw_delete, KWLoc)) {
00075       Diag(KWLoc, getLangOpts().CPlusPlus11
00076                       ? diag::warn_cxx98_compat_deleted_function
00077                       : diag::ext_deleted_function);
00078       Actions.SetDeclDeleted(FnD, KWLoc);
00079       Delete = true;
00080     } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
00081       Diag(KWLoc, getLangOpts().CPlusPlus11
00082                       ? diag::warn_cxx98_compat_defaulted_function
00083                       : diag::ext_defaulted_function);
00084       Actions.SetDeclDefaulted(FnD, KWLoc);
00085     } else {
00086       llvm_unreachable("function definition after = not 'delete' or 'default'");
00087     }
00088 
00089     if (Tok.is(tok::comma)) {
00090       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
00091         << Delete;
00092       SkipUntil(tok::semi);
00093     } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
00094                                 Delete ? "delete" : "default")) {
00095       SkipUntil(tok::semi);
00096     }
00097 
00098     return FnD;
00099   }
00100   
00101   // In delayed template parsing mode, if we are within a class template
00102   // or if we are about to parse function member template then consume
00103   // the tokens and store them for parsing at the end of the translation unit.
00104   if (getLangOpts().DelayedTemplateParsing &&
00105       DefinitionKind == FDK_Definition &&
00106       !D.getDeclSpec().isConstexprSpecified() &&
00107       !(FnD && FnD->getAsFunction() &&
00108         FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
00109       ((Actions.CurContext->isDependentContext() ||
00110         (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
00111          TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
00112        !Actions.IsInsideALocalClassWithinATemplateFunction())) {
00113 
00114     CachedTokens Toks;
00115     LexTemplateFunctionForLateParsing(Toks);
00116 
00117     if (FnD) {
00118       FunctionDecl *FD = FnD->getAsFunction();
00119       Actions.CheckForFunctionRedefinition(FD);
00120       Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
00121     }
00122 
00123     return FnD;
00124   }
00125 
00126   // Consume the tokens and store them for later parsing.
00127 
00128   LexedMethod* LM = new LexedMethod(this, FnD);
00129   getCurrentClass().LateParsedDeclarations.push_back(LM);
00130   LM->TemplateScope = getCurScope()->isTemplateParamScope();
00131   CachedTokens &Toks = LM->Toks;
00132 
00133   tok::TokenKind kind = Tok.getKind();
00134   // Consume everything up to (and including) the left brace of the
00135   // function body.
00136   if (ConsumeAndStoreFunctionPrologue(Toks)) {
00137     // We didn't find the left-brace we expected after the
00138     // constructor initializer; we already printed an error, and it's likely
00139     // impossible to recover, so don't try to parse this method later.
00140     // Skip over the rest of the decl and back to somewhere that looks
00141     // reasonable.
00142     SkipMalformedDecl();
00143     delete getCurrentClass().LateParsedDeclarations.back();
00144     getCurrentClass().LateParsedDeclarations.pop_back();
00145     return FnD;
00146   } else {
00147     // Consume everything up to (and including) the matching right brace.
00148     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
00149   }
00150 
00151   // If we're in a function-try-block, we need to store all the catch blocks.
00152   if (kind == tok::kw_try) {
00153     while (Tok.is(tok::kw_catch)) {
00154       ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
00155       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
00156     }
00157   }
00158 
00159   if (FnD) {
00160     // If this is a friend function, mark that it's late-parsed so that
00161     // it's still known to be a definition even before we attach the
00162     // parsed body.  Sema needs to treat friend function definitions
00163     // differently during template instantiation, and it's possible for
00164     // the containing class to be instantiated before all its member
00165     // function definitions are parsed.
00166     //
00167     // If you remove this, you can remove the code that clears the flag
00168     // after parsing the member.
00169     if (D.getDeclSpec().isFriendSpecified()) {
00170       FunctionDecl *FD = FnD->getAsFunction();
00171       Actions.CheckForFunctionRedefinition(FD);
00172       FD->setLateTemplateParsed(true);
00173     }
00174   } else {
00175     // If semantic analysis could not build a function declaration,
00176     // just throw away the late-parsed declaration.
00177     delete getCurrentClass().LateParsedDeclarations.back();
00178     getCurrentClass().LateParsedDeclarations.pop_back();
00179   }
00180 
00181   return FnD;
00182 }
00183 
00184 /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
00185 /// specified Declarator is a well formed C++ non-static data member
00186 /// declaration. Now lex its initializer and store its tokens for parsing
00187 /// after the class is complete.
00188 void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
00189   assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
00190          "Current token not a '{' or '='!");
00191 
00192   LateParsedMemberInitializer *MI =
00193     new LateParsedMemberInitializer(this, VarD);
00194   getCurrentClass().LateParsedDeclarations.push_back(MI);
00195   CachedTokens &Toks = MI->Toks;
00196 
00197   tok::TokenKind kind = Tok.getKind();
00198   if (kind == tok::equal) {
00199     Toks.push_back(Tok);
00200     ConsumeToken();
00201   }
00202 
00203   if (kind == tok::l_brace) {
00204     // Begin by storing the '{' token.
00205     Toks.push_back(Tok);
00206     ConsumeBrace();
00207 
00208     // Consume everything up to (and including) the matching right brace.
00209     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
00210   } else {
00211     // Consume everything up to (but excluding) the comma or semicolon.
00212     ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
00213   }
00214 
00215   // Store an artificial EOF token to ensure that we don't run off the end of
00216   // the initializer when we come to parse it.
00217   Token Eof;
00218   Eof.startToken();
00219   Eof.setKind(tok::eof);
00220   Eof.setLocation(Tok.getLocation());
00221   Eof.setEofData(VarD);
00222   Toks.push_back(Eof);
00223 }
00224 
00225 Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
00226 void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
00227 void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
00228 void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
00229 
00230 Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
00231   : Self(P), Class(C) {}
00232 
00233 Parser::LateParsedClass::~LateParsedClass() {
00234   Self->DeallocateParsedClasses(Class);
00235 }
00236 
00237 void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
00238   Self->ParseLexedMethodDeclarations(*Class);
00239 }
00240 
00241 void Parser::LateParsedClass::ParseLexedMemberInitializers() {
00242   Self->ParseLexedMemberInitializers(*Class);
00243 }
00244 
00245 void Parser::LateParsedClass::ParseLexedMethodDefs() {
00246   Self->ParseLexedMethodDefs(*Class);
00247 }
00248 
00249 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
00250   Self->ParseLexedMethodDeclaration(*this);
00251 }
00252 
00253 void Parser::LexedMethod::ParseLexedMethodDefs() {
00254   Self->ParseLexedMethodDef(*this);
00255 }
00256 
00257 void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
00258   Self->ParseLexedMemberInitializer(*this);
00259 }
00260 
00261 /// ParseLexedMethodDeclarations - We finished parsing the member
00262 /// specification of a top (non-nested) C++ class. Now go over the
00263 /// stack of method declarations with some parts for which parsing was
00264 /// delayed (such as default arguments) and parse them.
00265 void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
00266   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
00267   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
00268                                 HasTemplateScope);
00269   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
00270   if (HasTemplateScope) {
00271     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
00272     ++CurTemplateDepthTracker;
00273   }
00274 
00275   // The current scope is still active if we're the top-level class.
00276   // Otherwise we'll need to push and enter a new scope.
00277   bool HasClassScope = !Class.TopLevelClass;
00278   ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
00279                         HasClassScope);
00280   if (HasClassScope)
00281     Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
00282                                                 Class.TagOrTemplate);
00283 
00284   for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
00285     Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
00286   }
00287 
00288   if (HasClassScope)
00289     Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
00290                                                  Class.TagOrTemplate);
00291 }
00292 
00293 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
00294   // If this is a member template, introduce the template parameter scope.
00295   ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
00296   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
00297   if (LM.TemplateScope) {
00298     Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
00299     ++CurTemplateDepthTracker;
00300   }
00301   // Start the delayed C++ method declaration
00302   Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
00303 
00304   // Introduce the parameters into scope and parse their default
00305   // arguments.
00306   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
00307                             Scope::FunctionDeclarationScope | Scope::DeclScope);
00308   for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
00309     auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
00310     // Introduce the parameter into scope.
00311     bool HasUnparsed = Param->hasUnparsedDefaultArg();
00312     Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
00313     if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
00314       // Mark the end of the default argument so that we know when to stop when
00315       // we parse it later on.
00316       Token LastDefaultArgToken = Toks->back();
00317       Token DefArgEnd;
00318       DefArgEnd.startToken();
00319       DefArgEnd.setKind(tok::eof);
00320       DefArgEnd.setLocation(LastDefaultArgToken.getLocation().getLocWithOffset(
00321           LastDefaultArgToken.getLength()));
00322       DefArgEnd.setEofData(Param);
00323       Toks->push_back(DefArgEnd);
00324 
00325       // Parse the default argument from its saved token stream.
00326       Toks->push_back(Tok); // So that the current token doesn't get lost
00327       PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
00328 
00329       // Consume the previously-pushed token.
00330       ConsumeAnyToken();
00331 
00332       // Consume the '='.
00333       assert(Tok.is(tok::equal) && "Default argument not starting with '='");
00334       SourceLocation EqualLoc = ConsumeToken();
00335 
00336       // The argument isn't actually potentially evaluated unless it is
00337       // used.
00338       EnterExpressionEvaluationContext Eval(Actions,
00339                                             Sema::PotentiallyEvaluatedIfUsed,
00340                                             Param);
00341 
00342       ExprResult DefArgResult;
00343       if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
00344         Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
00345         DefArgResult = ParseBraceInitializer();
00346       } else
00347         DefArgResult = ParseAssignmentExpression();
00348       DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
00349       if (DefArgResult.isInvalid()) {
00350         Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
00351       } else {
00352         if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
00353           // The last two tokens are the terminator and the saved value of
00354           // Tok; the last token in the default argument is the one before
00355           // those.
00356           assert(Toks->size() >= 3 && "expected a token in default arg");
00357           Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
00358             << SourceRange(Tok.getLocation(),
00359                            (*Toks)[Toks->size() - 3].getLocation());
00360         }
00361         Actions.ActOnParamDefaultArgument(Param, EqualLoc,
00362                                           DefArgResult.get());
00363       }
00364 
00365       // There could be leftover tokens (e.g. because of an error).
00366       // Skip through until we reach the 'end of default argument' token.
00367       while (Tok.isNot(tok::eof))
00368         ConsumeAnyToken();
00369 
00370       if (Tok.is(tok::eof) && Tok.getEofData() == Param)
00371         ConsumeAnyToken();
00372 
00373       delete Toks;
00374       LM.DefaultArgs[I].Toks = nullptr;
00375     } else if (HasUnparsed) {
00376       assert(Param->hasInheritedDefaultArg());
00377       FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
00378       ParmVarDecl *OldParam = Old->getParamDecl(I);
00379       assert (!OldParam->hasUnparsedDefaultArg());
00380       if (OldParam->hasUninstantiatedDefaultArg())
00381         Param->setUninstantiatedDefaultArg(
00382                                       Param->getUninstantiatedDefaultArg());
00383       else
00384         Param->setDefaultArg(OldParam->getInit());
00385     }
00386   }
00387 
00388   // Parse a delayed exception-specification, if there is one.
00389   if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
00390     // Add the 'stop' token.
00391     Token LastExceptionSpecToken = Toks->back();
00392     Token ExceptionSpecEnd;
00393     ExceptionSpecEnd.startToken();
00394     ExceptionSpecEnd.setKind(tok::eof);
00395     ExceptionSpecEnd.setLocation(
00396         LastExceptionSpecToken.getLocation().getLocWithOffset(
00397             LastExceptionSpecToken.getLength()));
00398     ExceptionSpecEnd.setEofData(LM.Method);
00399     Toks->push_back(ExceptionSpecEnd);
00400 
00401     // Parse the default argument from its saved token stream.
00402     Toks->push_back(Tok); // So that the current token doesn't get lost
00403     PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
00404 
00405     // Consume the previously-pushed token.
00406     ConsumeAnyToken();
00407 
00408     // C++11 [expr.prim.general]p3:
00409     //   If a declaration declares a member function or member function
00410     //   template of a class X, the expression this is a prvalue of type
00411     //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
00412     //   and the end of the function-definition, member-declarator, or
00413     //   declarator.
00414     CXXMethodDecl *Method;
00415     if (FunctionTemplateDecl *FunTmpl
00416           = dyn_cast<FunctionTemplateDecl>(LM.Method))
00417       Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
00418     else
00419       Method = cast<CXXMethodDecl>(LM.Method);
00420 
00421     Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
00422                                      Method->getTypeQualifiers(),
00423                                      getLangOpts().CPlusPlus11);
00424 
00425     // Parse the exception-specification.
00426     SourceRange SpecificationRange;
00427     SmallVector<ParsedType, 4> DynamicExceptions;
00428     SmallVector<SourceRange, 4> DynamicExceptionRanges;
00429     ExprResult NoexceptExpr;
00430     CachedTokens *ExceptionSpecTokens;
00431 
00432     ExceptionSpecificationType EST
00433       = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
00434                                        DynamicExceptions,
00435                                        DynamicExceptionRanges, NoexceptExpr,
00436                                        ExceptionSpecTokens);
00437 
00438     if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
00439       Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
00440 
00441     // Attach the exception-specification to the method.
00442     Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
00443                                                SpecificationRange,
00444                                                DynamicExceptions,
00445                                                DynamicExceptionRanges,
00446                                                NoexceptExpr.isUsable()?
00447                                                  NoexceptExpr.get() : nullptr);
00448 
00449     // There could be leftover tokens (e.g. because of an error).
00450     // Skip through until we reach the original token position.
00451     while (Tok.isNot(tok::eof))
00452       ConsumeAnyToken();
00453 
00454     // Clean up the remaining EOF token.
00455     if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
00456       ConsumeAnyToken();
00457 
00458     delete Toks;
00459     LM.ExceptionSpecTokens = nullptr;
00460   }
00461 
00462   PrototypeScope.Exit();
00463 
00464   // Finish the delayed C++ method declaration.
00465   Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
00466 }
00467 
00468 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
00469 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
00470 /// collected during its parsing and parse them all.
00471 void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
00472   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
00473   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
00474   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
00475   if (HasTemplateScope) {
00476     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
00477     ++CurTemplateDepthTracker;
00478   }
00479   bool HasClassScope = !Class.TopLevelClass;
00480   ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
00481                         HasClassScope);
00482 
00483   for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
00484     Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
00485   }
00486 }
00487 
00488 void Parser::ParseLexedMethodDef(LexedMethod &LM) {
00489   // If this is a member template, introduce the template parameter scope.
00490   ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
00491   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
00492   if (LM.TemplateScope) {
00493     Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
00494     ++CurTemplateDepthTracker;
00495   }
00496 
00497   assert(!LM.Toks.empty() && "Empty body!");
00498   Token LastBodyToken = LM.Toks.back();
00499   Token BodyEnd;
00500   BodyEnd.startToken();
00501   BodyEnd.setKind(tok::eof);
00502   BodyEnd.setLocation(
00503       LastBodyToken.getLocation().getLocWithOffset(LastBodyToken.getLength()));
00504   BodyEnd.setEofData(LM.D);
00505   LM.Toks.push_back(BodyEnd);
00506   // Append the current token at the end of the new token stream so that it
00507   // doesn't get lost.
00508   LM.Toks.push_back(Tok);
00509   PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
00510 
00511   // Consume the previously pushed token.
00512   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
00513   assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
00514          && "Inline method not starting with '{', ':' or 'try'");
00515 
00516   // Parse the method body. Function body parsing code is similar enough
00517   // to be re-used for method bodies as well.
00518   ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
00519   Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
00520 
00521   if (Tok.is(tok::kw_try)) {
00522     ParseFunctionTryBlock(LM.D, FnScope);
00523 
00524     while (Tok.isNot(tok::eof))
00525       ConsumeAnyToken();
00526 
00527     if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
00528       ConsumeAnyToken();
00529     return;
00530   }
00531   if (Tok.is(tok::colon)) {
00532     ParseConstructorInitializer(LM.D);
00533 
00534     // Error recovery.
00535     if (!Tok.is(tok::l_brace)) {
00536       FnScope.Exit();
00537       Actions.ActOnFinishFunctionBody(LM.D, nullptr);
00538 
00539       while (Tok.isNot(tok::eof))
00540         ConsumeAnyToken();
00541 
00542       if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
00543         ConsumeAnyToken();
00544       return;
00545     }
00546   } else
00547     Actions.ActOnDefaultCtorInitializers(LM.D);
00548 
00549   assert((Actions.getDiagnostics().hasErrorOccurred() ||
00550           !isa<FunctionTemplateDecl>(LM.D) ||
00551           cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
00552             < TemplateParameterDepth) &&
00553          "TemplateParameterDepth should be greater than the depth of "
00554          "current template being instantiated!");
00555 
00556   ParseFunctionStatementBody(LM.D, FnScope);
00557 
00558   // Clear the late-template-parsed bit if we set it before.
00559   if (LM.D)
00560     LM.D->getAsFunction()->setLateTemplateParsed(false);
00561 
00562   while (Tok.isNot(tok::eof))
00563     ConsumeAnyToken();
00564 
00565   if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
00566     ConsumeAnyToken();
00567 
00568   if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
00569     Actions.ActOnFinishInlineMethodDef(MD);
00570 }
00571 
00572 /// ParseLexedMemberInitializers - We finished parsing the member specification
00573 /// of a top (non-nested) C++ class. Now go over the stack of lexed data member
00574 /// initializers that were collected during its parsing and parse them all.
00575 void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
00576   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
00577   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
00578                                 HasTemplateScope);
00579   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
00580   if (HasTemplateScope) {
00581     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
00582     ++CurTemplateDepthTracker;
00583   }
00584   // Set or update the scope flags.
00585   bool AlreadyHasClassScope = Class.TopLevelClass;
00586   unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
00587   ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
00588   ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
00589 
00590   if (!AlreadyHasClassScope)
00591     Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
00592                                                 Class.TagOrTemplate);
00593 
00594   if (!Class.LateParsedDeclarations.empty()) {
00595     // C++11 [expr.prim.general]p4:
00596     //   Otherwise, if a member-declarator declares a non-static data member 
00597     //  (9.2) of a class X, the expression this is a prvalue of type "pointer
00598     //  to X" within the optional brace-or-equal-initializer. It shall not 
00599     //  appear elsewhere in the member-declarator.
00600     Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
00601                                      /*TypeQuals=*/(unsigned)0);
00602 
00603     for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
00604       Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
00605     }
00606   }
00607   
00608   if (!AlreadyHasClassScope)
00609     Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
00610                                                  Class.TagOrTemplate);
00611 
00612   Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
00613 }
00614 
00615 void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
00616   if (!MI.Field || MI.Field->isInvalidDecl())
00617     return;
00618 
00619   // Append the current token at the end of the new token stream so that it
00620   // doesn't get lost.
00621   MI.Toks.push_back(Tok);
00622   PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
00623 
00624   // Consume the previously pushed token.
00625   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
00626 
00627   SourceLocation EqualLoc;
00628 
00629   Actions.ActOnStartCXXInClassMemberInitializer();
00630 
00631   ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false, 
00632                                               EqualLoc);
00633 
00634   Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
00635                                                  Init.get());
00636 
00637   // The next token should be our artificial terminating EOF token.
00638   if (Tok.isNot(tok::eof)) {
00639     if (!Init.isInvalid()) {
00640       SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
00641       if (!EndLoc.isValid())
00642         EndLoc = Tok.getLocation();
00643       // No fixit; we can't recover as if there were a semicolon here.
00644       Diag(EndLoc, diag::err_expected_semi_decl_list);
00645     }
00646 
00647     // Consume tokens until we hit the artificial EOF.
00648     while (Tok.isNot(tok::eof))
00649       ConsumeAnyToken();
00650   }
00651   // Make sure this is *our* artificial EOF token.
00652   if (Tok.getEofData() == MI.Field)
00653     ConsumeAnyToken();
00654 }
00655 
00656 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
00657 /// container until the token 'T' is reached (which gets
00658 /// consumed/stored too, if ConsumeFinalToken).
00659 /// If StopAtSemi is true, then we will stop early at a ';' character.
00660 /// Returns true if token 'T1' or 'T2' was found.
00661 /// NOTE: This is a specialized version of Parser::SkipUntil.
00662 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
00663                                   CachedTokens &Toks,
00664                                   bool StopAtSemi, bool ConsumeFinalToken) {
00665   // We always want this function to consume at least one token if the first
00666   // token isn't T and if not at EOF.
00667   bool isFirstTokenConsumed = true;
00668   while (1) {
00669     // If we found one of the tokens, stop and return true.
00670     if (Tok.is(T1) || Tok.is(T2)) {
00671       if (ConsumeFinalToken) {
00672         Toks.push_back(Tok);
00673         ConsumeAnyToken();
00674       }
00675       return true;
00676     }
00677 
00678     switch (Tok.getKind()) {
00679     case tok::eof:
00680     case tok::annot_module_begin:
00681     case tok::annot_module_end:
00682     case tok::annot_module_include:
00683       // Ran out of tokens.
00684       return false;
00685 
00686     case tok::l_paren:
00687       // Recursively consume properly-nested parens.
00688       Toks.push_back(Tok);
00689       ConsumeParen();
00690       ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
00691       break;
00692     case tok::l_square:
00693       // Recursively consume properly-nested square brackets.
00694       Toks.push_back(Tok);
00695       ConsumeBracket();
00696       ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
00697       break;
00698     case tok::l_brace:
00699       // Recursively consume properly-nested braces.
00700       Toks.push_back(Tok);
00701       ConsumeBrace();
00702       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
00703       break;
00704 
00705     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
00706     // Since the user wasn't looking for this token (if they were, it would
00707     // already be handled), this isn't balanced.  If there is a LHS token at a
00708     // higher level, we will assume that this matches the unbalanced token
00709     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
00710     case tok::r_paren:
00711       if (ParenCount && !isFirstTokenConsumed)
00712         return false;  // Matches something.
00713       Toks.push_back(Tok);
00714       ConsumeParen();
00715       break;
00716     case tok::r_square:
00717       if (BracketCount && !isFirstTokenConsumed)
00718         return false;  // Matches something.
00719       Toks.push_back(Tok);
00720       ConsumeBracket();
00721       break;
00722     case tok::r_brace:
00723       if (BraceCount && !isFirstTokenConsumed)
00724         return false;  // Matches something.
00725       Toks.push_back(Tok);
00726       ConsumeBrace();
00727       break;
00728 
00729     case tok::code_completion:
00730       Toks.push_back(Tok);
00731       ConsumeCodeCompletionToken();
00732       break;
00733 
00734     case tok::string_literal:
00735     case tok::wide_string_literal:
00736     case tok::utf8_string_literal:
00737     case tok::utf16_string_literal:
00738     case tok::utf32_string_literal:
00739       Toks.push_back(Tok);
00740       ConsumeStringToken();
00741       break;
00742     case tok::semi:
00743       if (StopAtSemi)
00744         return false;
00745       // FALL THROUGH.
00746     default:
00747       // consume this token.
00748       Toks.push_back(Tok);
00749       ConsumeToken();
00750       break;
00751     }
00752     isFirstTokenConsumed = false;
00753   }
00754 }
00755 
00756 /// \brief Consume tokens and store them in the passed token container until
00757 /// we've passed the try keyword and constructor initializers and have consumed
00758 /// the opening brace of the function body. The opening brace will be consumed
00759 /// if and only if there was no error.
00760 ///
00761 /// \return True on error.
00762 bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
00763   if (Tok.is(tok::kw_try)) {
00764     Toks.push_back(Tok);
00765     ConsumeToken();
00766   }
00767 
00768   if (Tok.isNot(tok::colon)) {
00769     // Easy case, just a function body.
00770 
00771     // Grab any remaining garbage to be diagnosed later. We stop when we reach a
00772     // brace: an opening one is the function body, while a closing one probably
00773     // means we've reached the end of the class.
00774     ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
00775                          /*StopAtSemi=*/true,
00776                          /*ConsumeFinalToken=*/false);
00777     if (Tok.isNot(tok::l_brace))
00778       return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
00779 
00780     Toks.push_back(Tok);
00781     ConsumeBrace();
00782     return false;
00783   }
00784 
00785   Toks.push_back(Tok);
00786   ConsumeToken();
00787 
00788   // We can't reliably skip over a mem-initializer-id, because it could be
00789   // a template-id involving not-yet-declared names. Given:
00790   //
00791   //   S ( ) : a < b < c > ( e )
00792   //
00793   // 'e' might be an initializer or part of a template argument, depending
00794   // on whether 'b' is a template.
00795 
00796   // Track whether we might be inside a template argument. We can give
00797   // significantly better diagnostics if we know that we're not.
00798   bool MightBeTemplateArgument = false;
00799 
00800   while (true) {
00801     // Skip over the mem-initializer-id, if possible.
00802     if (Tok.is(tok::kw_decltype)) {
00803       Toks.push_back(Tok);
00804       SourceLocation OpenLoc = ConsumeToken();
00805       if (Tok.isNot(tok::l_paren))
00806         return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
00807                  << "decltype";
00808       Toks.push_back(Tok);
00809       ConsumeParen();
00810       if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
00811         Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
00812         Diag(OpenLoc, diag::note_matching) << tok::l_paren;
00813         return true;
00814       }
00815     }
00816     do {
00817       // Walk over a component of a nested-name-specifier.
00818       if (Tok.is(tok::coloncolon)) {
00819         Toks.push_back(Tok);
00820         ConsumeToken();
00821 
00822         if (Tok.is(tok::kw_template)) {
00823           Toks.push_back(Tok);
00824           ConsumeToken();
00825         }
00826       }
00827 
00828       if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
00829         Toks.push_back(Tok);
00830         ConsumeToken();
00831       } else if (Tok.is(tok::code_completion)) {
00832         Toks.push_back(Tok);
00833         ConsumeCodeCompletionToken();
00834         // Consume the rest of the initializers permissively.
00835         // FIXME: We should be able to perform code-completion here even if
00836         //        there isn't a subsequent '{' token.
00837         MightBeTemplateArgument = true;
00838         break;
00839       } else {
00840         break;
00841       }
00842     } while (Tok.is(tok::coloncolon));
00843 
00844     if (Tok.is(tok::less))
00845       MightBeTemplateArgument = true;
00846 
00847     if (MightBeTemplateArgument) {
00848       // We may be inside a template argument list. Grab up to the start of the
00849       // next parenthesized initializer or braced-init-list. This *might* be the
00850       // initializer, or it might be a subexpression in the template argument
00851       // list.
00852       // FIXME: Count angle brackets, and clear MightBeTemplateArgument
00853       //        if all angles are closed.
00854       if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
00855                                 /*StopAtSemi=*/true,
00856                                 /*ConsumeFinalToken=*/false)) {
00857         // We're not just missing the initializer, we're also missing the
00858         // function body!
00859         return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
00860       }
00861     } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
00862       // We found something weird in a mem-initializer-id.
00863       if (getLangOpts().CPlusPlus11)
00864         return Diag(Tok.getLocation(), diag::err_expected_either)
00865                << tok::l_paren << tok::l_brace;
00866       else
00867         return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
00868     }
00869 
00870     tok::TokenKind kind = Tok.getKind();
00871     Toks.push_back(Tok);
00872     bool IsLParen = (kind == tok::l_paren);
00873     SourceLocation OpenLoc = Tok.getLocation();
00874 
00875     if (IsLParen) {
00876       ConsumeParen();
00877     } else {
00878       assert(kind == tok::l_brace && "Must be left paren or brace here.");
00879       ConsumeBrace();
00880       // In C++03, this has to be the start of the function body, which
00881       // means the initializer is malformed; we'll diagnose it later.
00882       if (!getLangOpts().CPlusPlus11)
00883         return false;
00884     }
00885 
00886     // Grab the initializer (or the subexpression of the template argument).
00887     // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
00888     //        if we might be inside the braces of a lambda-expression.
00889     tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
00890     if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
00891       Diag(Tok, diag::err_expected) << CloseKind;
00892       Diag(OpenLoc, diag::note_matching) << kind;
00893       return true;
00894     }
00895 
00896     // Grab pack ellipsis, if present.
00897     if (Tok.is(tok::ellipsis)) {
00898       Toks.push_back(Tok);
00899       ConsumeToken();
00900     }
00901 
00902     // If we know we just consumed a mem-initializer, we must have ',' or '{'
00903     // next.
00904     if (Tok.is(tok::comma)) {
00905       Toks.push_back(Tok);
00906       ConsumeToken();
00907     } else if (Tok.is(tok::l_brace)) {
00908       // This is the function body if the ')' or '}' is immediately followed by
00909       // a '{'. That cannot happen within a template argument, apart from the
00910       // case where a template argument contains a compound literal:
00911       //
00912       //   S ( ) : a < b < c > ( d ) { }
00913       //   // End of declaration, or still inside the template argument?
00914       //
00915       // ... and the case where the template argument contains a lambda:
00916       //
00917       //   S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
00918       //     ( ) > ( ) { }
00919       //
00920       // FIXME: Disambiguate these cases. Note that the latter case is probably
00921       //        going to be made ill-formed by core issue 1607.
00922       Toks.push_back(Tok);
00923       ConsumeBrace();
00924       return false;
00925     } else if (!MightBeTemplateArgument) {
00926       return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
00927                                                                 << tok::comma;
00928     }
00929   }
00930 }
00931 
00932 /// \brief Consume and store tokens from the '?' to the ':' in a conditional
00933 /// expression.
00934 bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
00935   // Consume '?'.
00936   assert(Tok.is(tok::question));
00937   Toks.push_back(Tok);
00938   ConsumeToken();
00939 
00940   while (Tok.isNot(tok::colon)) {
00941     if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
00942                               /*StopAtSemi=*/true,
00943                               /*ConsumeFinalToken=*/false))
00944       return false;
00945 
00946     // If we found a nested conditional, consume it.
00947     if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
00948       return false;
00949   }
00950 
00951   // Consume ':'.
00952   Toks.push_back(Tok);
00953   ConsumeToken();
00954   return true;
00955 }
00956 
00957 /// \brief A tentative parsing action that can also revert token annotations.
00958 class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
00959 public:
00960   explicit UnannotatedTentativeParsingAction(Parser &Self,
00961                                              tok::TokenKind EndKind)
00962       : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
00963     // Stash away the old token stream, so we can restore it once the
00964     // tentative parse is complete.
00965     TentativeParsingAction Inner(Self);
00966     Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
00967     Inner.Revert();
00968   }
00969 
00970   void RevertAnnotations() {
00971     Revert();
00972 
00973     // Put back the original tokens.
00974     Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
00975     if (Toks.size()) {
00976       Token *Buffer = new Token[Toks.size()];
00977       std::copy(Toks.begin() + 1, Toks.end(), Buffer);
00978       Buffer[Toks.size() - 1] = Self.Tok;
00979       Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
00980 
00981       Self.Tok = Toks.front();
00982     }
00983   }
00984 
00985 private:
00986   Parser &Self;
00987   CachedTokens Toks;
00988   tok::TokenKind EndKind;
00989 };
00990 
00991 /// ConsumeAndStoreInitializer - Consume and store the token at the passed token
00992 /// container until the end of the current initializer expression (either a
00993 /// default argument or an in-class initializer for a non-static data member).
00994 ///
00995 /// Returns \c true if we reached the end of something initializer-shaped,
00996 /// \c false if we bailed out.
00997 bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
00998                                         CachedInitKind CIK) {
00999   // We always want this function to consume at least one token if not at EOF.
01000   bool IsFirstToken = true;
01001 
01002   // Number of possible unclosed <s we've seen so far. These might be templates,
01003   // and might not, but if there were none of them (or we know for sure that
01004   // we're within a template), we can avoid a tentative parse.
01005   unsigned AngleCount = 0;
01006   unsigned KnownTemplateCount = 0;
01007 
01008   while (1) {
01009     switch (Tok.getKind()) {
01010     case tok::comma:
01011       // If we might be in a template, perform a tentative parse to check.
01012       if (!AngleCount)
01013         // Not a template argument: this is the end of the initializer.
01014         return true;
01015       if (KnownTemplateCount)
01016         goto consume_token;
01017 
01018       // We hit a comma inside angle brackets. This is the hard case. The
01019       // rule we follow is:
01020       //  * For a default argument, if the tokens after the comma form a
01021       //    syntactically-valid parameter-declaration-clause, in which each
01022       //    parameter has an initializer, then this comma ends the default
01023       //    argument.
01024       //  * For a default initializer, if the tokens after the comma form a
01025       //    syntactically-valid init-declarator-list, then this comma ends
01026       //    the default initializer.
01027       {
01028         UnannotatedTentativeParsingAction PA(*this,
01029                                              CIK == CIK_DefaultInitializer
01030                                                ? tok::semi : tok::r_paren);
01031         Sema::TentativeAnalysisScope Scope(Actions);
01032 
01033         TPResult Result = TPResult::Error;
01034         ConsumeToken();
01035         switch (CIK) {
01036         case CIK_DefaultInitializer:
01037           Result = TryParseInitDeclaratorList();
01038           // If we parsed a complete, ambiguous init-declarator-list, this
01039           // is only syntactically-valid if it's followed by a semicolon.
01040           if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
01041             Result = TPResult::False;
01042           break;
01043 
01044         case CIK_DefaultArgument:
01045           bool InvalidAsDeclaration = false;
01046           Result = TryParseParameterDeclarationClause(
01047               &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
01048           // If this is an expression or a declaration with a missing
01049           // 'typename', assume it's not a declaration.
01050           if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
01051             Result = TPResult::False;
01052           break;
01053         }
01054 
01055         // If what follows could be a declaration, it is a declaration.
01056         if (Result != TPResult::False && Result != TPResult::Error) {
01057           PA.Revert();
01058           return true;
01059         }
01060 
01061         // In the uncommon case that we decide the following tokens are part
01062         // of a template argument, revert any annotations we've performed in
01063         // those tokens. We're not going to look them up until we've parsed
01064         // the rest of the class, and that might add more declarations.
01065         PA.RevertAnnotations();
01066       }
01067 
01068       // Keep going. We know we're inside a template argument list now.
01069       ++KnownTemplateCount;
01070       goto consume_token;
01071 
01072     case tok::eof:
01073     case tok::annot_module_begin:
01074     case tok::annot_module_end:
01075     case tok::annot_module_include:
01076       // Ran out of tokens.
01077       return false;
01078 
01079     case tok::less:
01080       // FIXME: A '<' can only start a template-id if it's preceded by an
01081       // identifier, an operator-function-id, or a literal-operator-id.
01082       ++AngleCount;
01083       goto consume_token;
01084 
01085     case tok::question:
01086       // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
01087       // that is *never* the end of the initializer. Skip to the ':'.
01088       if (!ConsumeAndStoreConditional(Toks))
01089         return false;
01090       break;
01091 
01092     case tok::greatergreatergreater:
01093       if (!getLangOpts().CPlusPlus11)
01094         goto consume_token;
01095       if (AngleCount) --AngleCount;
01096       if (KnownTemplateCount) --KnownTemplateCount;
01097       // Fall through.
01098     case tok::greatergreater:
01099       if (!getLangOpts().CPlusPlus11)
01100         goto consume_token;
01101       if (AngleCount) --AngleCount;
01102       if (KnownTemplateCount) --KnownTemplateCount;
01103       // Fall through.
01104     case tok::greater:
01105       if (AngleCount) --AngleCount;
01106       if (KnownTemplateCount) --KnownTemplateCount;
01107       goto consume_token;
01108 
01109     case tok::kw_template:
01110       // 'template' identifier '<' is known to start a template argument list,
01111       // and can be used to disambiguate the parse.
01112       // FIXME: Support all forms of 'template' unqualified-id '<'.
01113       Toks.push_back(Tok);
01114       ConsumeToken();
01115       if (Tok.is(tok::identifier)) {
01116         Toks.push_back(Tok);
01117         ConsumeToken();
01118         if (Tok.is(tok::less)) {
01119           ++AngleCount;
01120           ++KnownTemplateCount;
01121           Toks.push_back(Tok);
01122           ConsumeToken();
01123         }
01124       }
01125       break;
01126 
01127     case tok::kw_operator:
01128       // If 'operator' precedes other punctuation, that punctuation loses
01129       // its special behavior.
01130       Toks.push_back(Tok);
01131       ConsumeToken();
01132       switch (Tok.getKind()) {
01133       case tok::comma:
01134       case tok::greatergreatergreater:
01135       case tok::greatergreater:
01136       case tok::greater:
01137       case tok::less:
01138         Toks.push_back(Tok);
01139         ConsumeToken();
01140         break;
01141       default:
01142         break;
01143       }
01144       break;
01145 
01146     case tok::l_paren:
01147       // Recursively consume properly-nested parens.
01148       Toks.push_back(Tok);
01149       ConsumeParen();
01150       ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
01151       break;
01152     case tok::l_square:
01153       // Recursively consume properly-nested square brackets.
01154       Toks.push_back(Tok);
01155       ConsumeBracket();
01156       ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
01157       break;
01158     case tok::l_brace:
01159       // Recursively consume properly-nested braces.
01160       Toks.push_back(Tok);
01161       ConsumeBrace();
01162       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
01163       break;
01164 
01165     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
01166     // Since the user wasn't looking for this token (if they were, it would
01167     // already be handled), this isn't balanced.  If there is a LHS token at a
01168     // higher level, we will assume that this matches the unbalanced token
01169     // and return it.  Otherwise, this is a spurious RHS token, which we
01170     // consume and pass on to downstream code to diagnose.
01171     case tok::r_paren:
01172       if (CIK == CIK_DefaultArgument)
01173         return true; // End of the default argument.
01174       if (ParenCount && !IsFirstToken)
01175         return false;
01176       Toks.push_back(Tok);
01177       ConsumeParen();
01178       continue;
01179     case tok::r_square:
01180       if (BracketCount && !IsFirstToken)
01181         return false;
01182       Toks.push_back(Tok);
01183       ConsumeBracket();
01184       continue;
01185     case tok::r_brace:
01186       if (BraceCount && !IsFirstToken)
01187         return false;
01188       Toks.push_back(Tok);
01189       ConsumeBrace();
01190       continue;
01191 
01192     case tok::code_completion:
01193       Toks.push_back(Tok);
01194       ConsumeCodeCompletionToken();
01195       break;
01196 
01197     case tok::string_literal:
01198     case tok::wide_string_literal:
01199     case tok::utf8_string_literal:
01200     case tok::utf16_string_literal:
01201     case tok::utf32_string_literal:
01202       Toks.push_back(Tok);
01203       ConsumeStringToken();
01204       break;
01205     case tok::semi:
01206       if (CIK == CIK_DefaultInitializer)
01207         return true; // End of the default initializer.
01208       // FALL THROUGH.
01209     default:
01210     consume_token:
01211       Toks.push_back(Tok);
01212       ConsumeToken();
01213       break;
01214     }
01215     IsFirstToken = false;
01216   }
01217 }