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     // Introduce the parameter into scope.
00310     Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
00311                                            LM.DefaultArgs[I].Param);
00312     if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
00313       // Mark the end of the default argument so that we know when to stop when
00314       // we parse it later on.
00315       Token LastDefaultArgToken = Toks->back();
00316       Token DefArgEnd;
00317       DefArgEnd.startToken();
00318       DefArgEnd.setKind(tok::eof);
00319       DefArgEnd.setLocation(LastDefaultArgToken.getLocation().getLocWithOffset(
00320           LastDefaultArgToken.getLength()));
00321       DefArgEnd.setEofData(LM.DefaultArgs[I].Param);
00322       Toks->push_back(DefArgEnd);
00323 
00324       // Parse the default argument from its saved token stream.
00325       Toks->push_back(Tok); // So that the current token doesn't get lost
00326       PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
00327 
00328       // Consume the previously-pushed token.
00329       ConsumeAnyToken();
00330 
00331       // Consume the '='.
00332       assert(Tok.is(tok::equal) && "Default argument not starting with '='");
00333       SourceLocation EqualLoc = ConsumeToken();
00334 
00335       // The argument isn't actually potentially evaluated unless it is
00336       // used.
00337       EnterExpressionEvaluationContext Eval(Actions,
00338                                             Sema::PotentiallyEvaluatedIfUsed,
00339                                             LM.DefaultArgs[I].Param);
00340 
00341       ExprResult DefArgResult;
00342       if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
00343         Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
00344         DefArgResult = ParseBraceInitializer();
00345       } else
00346         DefArgResult = ParseAssignmentExpression();
00347       DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
00348       if (DefArgResult.isInvalid()) {
00349         Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param,
00350                                                EqualLoc);
00351       } else {
00352         if (Tok.isNot(tok::eof) ||
00353             Tok.getEofData() != LM.DefaultArgs[I].Param) {
00354           // The last two tokens are the terminator and the saved value of
00355           // Tok; the last token in the default argument is the one before
00356           // those.
00357           assert(Toks->size() >= 3 && "expected a token in default arg");
00358           Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
00359             << SourceRange(Tok.getLocation(),
00360                            (*Toks)[Toks->size() - 3].getLocation());
00361         }
00362         Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
00363                                           DefArgResult.get());
00364       }
00365 
00366       // There could be leftover tokens (e.g. because of an error).
00367       // Skip through until we reach the 'end of default argument' token.
00368       while (Tok.isNot(tok::eof))
00369         ConsumeAnyToken();
00370 
00371       if (Tok.is(tok::eof) && Tok.getEofData() == LM.DefaultArgs[I].Param)
00372         ConsumeAnyToken();
00373 
00374       delete Toks;
00375       LM.DefaultArgs[I].Toks = nullptr;
00376     }
00377   }
00378 
00379   // Parse a delayed exception-specification, if there is one.
00380   if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
00381     // Add the 'stop' token.
00382     Token LastExceptionSpecToken = Toks->back();
00383     Token ExceptionSpecEnd;
00384     ExceptionSpecEnd.startToken();
00385     ExceptionSpecEnd.setKind(tok::eof);
00386     ExceptionSpecEnd.setLocation(
00387         LastExceptionSpecToken.getLocation().getLocWithOffset(
00388             LastExceptionSpecToken.getLength()));
00389     ExceptionSpecEnd.setEofData(LM.Method);
00390     Toks->push_back(ExceptionSpecEnd);
00391 
00392     // Parse the default argument from its saved token stream.
00393     Toks->push_back(Tok); // So that the current token doesn't get lost
00394     PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
00395 
00396     // Consume the previously-pushed token.
00397     ConsumeAnyToken();
00398 
00399     // C++11 [expr.prim.general]p3:
00400     //   If a declaration declares a member function or member function
00401     //   template of a class X, the expression this is a prvalue of type
00402     //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
00403     //   and the end of the function-definition, member-declarator, or
00404     //   declarator.
00405     CXXMethodDecl *Method;
00406     if (FunctionTemplateDecl *FunTmpl
00407           = dyn_cast<FunctionTemplateDecl>(LM.Method))
00408       Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
00409     else
00410       Method = cast<CXXMethodDecl>(LM.Method);
00411 
00412     Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
00413                                      Method->getTypeQualifiers(),
00414                                      getLangOpts().CPlusPlus11);
00415 
00416     // Parse the exception-specification.
00417     SourceRange SpecificationRange;
00418     SmallVector<ParsedType, 4> DynamicExceptions;
00419     SmallVector<SourceRange, 4> DynamicExceptionRanges;
00420     ExprResult NoexceptExpr;
00421     CachedTokens *ExceptionSpecTokens;
00422 
00423     ExceptionSpecificationType EST
00424       = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
00425                                        DynamicExceptions,
00426                                        DynamicExceptionRanges, NoexceptExpr,
00427                                        ExceptionSpecTokens);
00428 
00429     if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
00430       Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
00431 
00432     // Attach the exception-specification to the method.
00433     Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
00434                                                SpecificationRange,
00435                                                DynamicExceptions,
00436                                                DynamicExceptionRanges,
00437                                                NoexceptExpr.isUsable()?
00438                                                  NoexceptExpr.get() : nullptr);
00439 
00440     // There could be leftover tokens (e.g. because of an error).
00441     // Skip through until we reach the original token position.
00442     while (Tok.isNot(tok::eof))
00443       ConsumeAnyToken();
00444 
00445     // Clean up the remaining EOF token.
00446     if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
00447       ConsumeAnyToken();
00448 
00449     delete Toks;
00450     LM.ExceptionSpecTokens = nullptr;
00451   }
00452 
00453   PrototypeScope.Exit();
00454 
00455   // Finish the delayed C++ method declaration.
00456   Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
00457 }
00458 
00459 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
00460 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
00461 /// collected during its parsing and parse them all.
00462 void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
00463   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
00464   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
00465   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
00466   if (HasTemplateScope) {
00467     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
00468     ++CurTemplateDepthTracker;
00469   }
00470   bool HasClassScope = !Class.TopLevelClass;
00471   ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
00472                         HasClassScope);
00473 
00474   for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
00475     Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
00476   }
00477 }
00478 
00479 void Parser::ParseLexedMethodDef(LexedMethod &LM) {
00480   // If this is a member template, introduce the template parameter scope.
00481   ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
00482   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
00483   if (LM.TemplateScope) {
00484     Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
00485     ++CurTemplateDepthTracker;
00486   }
00487 
00488   assert(!LM.Toks.empty() && "Empty body!");
00489   Token LastBodyToken = LM.Toks.back();
00490   Token BodyEnd;
00491   BodyEnd.startToken();
00492   BodyEnd.setKind(tok::eof);
00493   BodyEnd.setLocation(
00494       LastBodyToken.getLocation().getLocWithOffset(LastBodyToken.getLength()));
00495   BodyEnd.setEofData(LM.D);
00496   LM.Toks.push_back(BodyEnd);
00497   // Append the current token at the end of the new token stream so that it
00498   // doesn't get lost.
00499   LM.Toks.push_back(Tok);
00500   PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
00501 
00502   // Consume the previously pushed token.
00503   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
00504   assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
00505          && "Inline method not starting with '{', ':' or 'try'");
00506 
00507   // Parse the method body. Function body parsing code is similar enough
00508   // to be re-used for method bodies as well.
00509   ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
00510   Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
00511 
00512   if (Tok.is(tok::kw_try)) {
00513     ParseFunctionTryBlock(LM.D, FnScope);
00514 
00515     while (Tok.isNot(tok::eof))
00516       ConsumeAnyToken();
00517 
00518     if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
00519       ConsumeAnyToken();
00520     return;
00521   }
00522   if (Tok.is(tok::colon)) {
00523     ParseConstructorInitializer(LM.D);
00524 
00525     // Error recovery.
00526     if (!Tok.is(tok::l_brace)) {
00527       FnScope.Exit();
00528       Actions.ActOnFinishFunctionBody(LM.D, nullptr);
00529 
00530       while (Tok.isNot(tok::eof))
00531         ConsumeAnyToken();
00532 
00533       if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
00534         ConsumeAnyToken();
00535       return;
00536     }
00537   } else
00538     Actions.ActOnDefaultCtorInitializers(LM.D);
00539 
00540   assert((Actions.getDiagnostics().hasErrorOccurred() ||
00541           !isa<FunctionTemplateDecl>(LM.D) ||
00542           cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
00543             < TemplateParameterDepth) &&
00544          "TemplateParameterDepth should be greater than the depth of "
00545          "current template being instantiated!");
00546 
00547   ParseFunctionStatementBody(LM.D, FnScope);
00548 
00549   // Clear the late-template-parsed bit if we set it before.
00550   if (LM.D)
00551     LM.D->getAsFunction()->setLateTemplateParsed(false);
00552 
00553   while (Tok.isNot(tok::eof))
00554     ConsumeAnyToken();
00555 
00556   if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
00557     ConsumeAnyToken();
00558 
00559   if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
00560     Actions.ActOnFinishInlineMethodDef(MD);
00561 }
00562 
00563 /// ParseLexedMemberInitializers - We finished parsing the member specification
00564 /// of a top (non-nested) C++ class. Now go over the stack of lexed data member
00565 /// initializers that were collected during its parsing and parse them all.
00566 void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
00567   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
00568   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
00569                                 HasTemplateScope);
00570   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
00571   if (HasTemplateScope) {
00572     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
00573     ++CurTemplateDepthTracker;
00574   }
00575   // Set or update the scope flags.
00576   bool AlreadyHasClassScope = Class.TopLevelClass;
00577   unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
00578   ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
00579   ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
00580 
00581   if (!AlreadyHasClassScope)
00582     Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
00583                                                 Class.TagOrTemplate);
00584 
00585   if (!Class.LateParsedDeclarations.empty()) {
00586     // C++11 [expr.prim.general]p4:
00587     //   Otherwise, if a member-declarator declares a non-static data member 
00588     //  (9.2) of a class X, the expression this is a prvalue of type "pointer
00589     //  to X" within the optional brace-or-equal-initializer. It shall not 
00590     //  appear elsewhere in the member-declarator.
00591     Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
00592                                      /*TypeQuals=*/(unsigned)0);
00593 
00594     for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
00595       Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
00596     }
00597   }
00598   
00599   if (!AlreadyHasClassScope)
00600     Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
00601                                                  Class.TagOrTemplate);
00602 
00603   Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
00604 }
00605 
00606 void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
00607   if (!MI.Field || MI.Field->isInvalidDecl())
00608     return;
00609 
00610   // Append the current token at the end of the new token stream so that it
00611   // doesn't get lost.
00612   MI.Toks.push_back(Tok);
00613   PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
00614 
00615   // Consume the previously pushed token.
00616   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
00617 
00618   SourceLocation EqualLoc;
00619 
00620   Actions.ActOnStartCXXInClassMemberInitializer();
00621 
00622   ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false, 
00623                                               EqualLoc);
00624 
00625   Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
00626                                                  Init.get());
00627 
00628   // The next token should be our artificial terminating EOF token.
00629   if (Tok.isNot(tok::eof)) {
00630     if (!Init.isInvalid()) {
00631       SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
00632       if (!EndLoc.isValid())
00633         EndLoc = Tok.getLocation();
00634       // No fixit; we can't recover as if there were a semicolon here.
00635       Diag(EndLoc, diag::err_expected_semi_decl_list);
00636     }
00637 
00638     // Consume tokens until we hit the artificial EOF.
00639     while (Tok.isNot(tok::eof))
00640       ConsumeAnyToken();
00641   }
00642   // Make sure this is *our* artificial EOF token.
00643   if (Tok.getEofData() == MI.Field)
00644     ConsumeAnyToken();
00645 }
00646 
00647 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
00648 /// container until the token 'T' is reached (which gets
00649 /// consumed/stored too, if ConsumeFinalToken).
00650 /// If StopAtSemi is true, then we will stop early at a ';' character.
00651 /// Returns true if token 'T1' or 'T2' was found.
00652 /// NOTE: This is a specialized version of Parser::SkipUntil.
00653 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
00654                                   CachedTokens &Toks,
00655                                   bool StopAtSemi, bool ConsumeFinalToken) {
00656   // We always want this function to consume at least one token if the first
00657   // token isn't T and if not at EOF.
00658   bool isFirstTokenConsumed = true;
00659   while (1) {
00660     // If we found one of the tokens, stop and return true.
00661     if (Tok.is(T1) || Tok.is(T2)) {
00662       if (ConsumeFinalToken) {
00663         Toks.push_back(Tok);
00664         ConsumeAnyToken();
00665       }
00666       return true;
00667     }
00668 
00669     switch (Tok.getKind()) {
00670     case tok::eof:
00671     case tok::annot_module_begin:
00672     case tok::annot_module_end:
00673     case tok::annot_module_include:
00674       // Ran out of tokens.
00675       return false;
00676 
00677     case tok::l_paren:
00678       // Recursively consume properly-nested parens.
00679       Toks.push_back(Tok);
00680       ConsumeParen();
00681       ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
00682       break;
00683     case tok::l_square:
00684       // Recursively consume properly-nested square brackets.
00685       Toks.push_back(Tok);
00686       ConsumeBracket();
00687       ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
00688       break;
00689     case tok::l_brace:
00690       // Recursively consume properly-nested braces.
00691       Toks.push_back(Tok);
00692       ConsumeBrace();
00693       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
00694       break;
00695 
00696     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
00697     // Since the user wasn't looking for this token (if they were, it would
00698     // already be handled), this isn't balanced.  If there is a LHS token at a
00699     // higher level, we will assume that this matches the unbalanced token
00700     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
00701     case tok::r_paren:
00702       if (ParenCount && !isFirstTokenConsumed)
00703         return false;  // Matches something.
00704       Toks.push_back(Tok);
00705       ConsumeParen();
00706       break;
00707     case tok::r_square:
00708       if (BracketCount && !isFirstTokenConsumed)
00709         return false;  // Matches something.
00710       Toks.push_back(Tok);
00711       ConsumeBracket();
00712       break;
00713     case tok::r_brace:
00714       if (BraceCount && !isFirstTokenConsumed)
00715         return false;  // Matches something.
00716       Toks.push_back(Tok);
00717       ConsumeBrace();
00718       break;
00719 
00720     case tok::code_completion:
00721       Toks.push_back(Tok);
00722       ConsumeCodeCompletionToken();
00723       break;
00724 
00725     case tok::string_literal:
00726     case tok::wide_string_literal:
00727     case tok::utf8_string_literal:
00728     case tok::utf16_string_literal:
00729     case tok::utf32_string_literal:
00730       Toks.push_back(Tok);
00731       ConsumeStringToken();
00732       break;
00733     case tok::semi:
00734       if (StopAtSemi)
00735         return false;
00736       // FALL THROUGH.
00737     default:
00738       // consume this token.
00739       Toks.push_back(Tok);
00740       ConsumeToken();
00741       break;
00742     }
00743     isFirstTokenConsumed = false;
00744   }
00745 }
00746 
00747 /// \brief Consume tokens and store them in the passed token container until
00748 /// we've passed the try keyword and constructor initializers and have consumed
00749 /// the opening brace of the function body. The opening brace will be consumed
00750 /// if and only if there was no error.
00751 ///
00752 /// \return True on error.
00753 bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
00754   if (Tok.is(tok::kw_try)) {
00755     Toks.push_back(Tok);
00756     ConsumeToken();
00757   }
00758 
00759   if (Tok.isNot(tok::colon)) {
00760     // Easy case, just a function body.
00761 
00762     // Grab any remaining garbage to be diagnosed later. We stop when we reach a
00763     // brace: an opening one is the function body, while a closing one probably
00764     // means we've reached the end of the class.
00765     ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
00766                          /*StopAtSemi=*/true,
00767                          /*ConsumeFinalToken=*/false);
00768     if (Tok.isNot(tok::l_brace))
00769       return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
00770 
00771     Toks.push_back(Tok);
00772     ConsumeBrace();
00773     return false;
00774   }
00775 
00776   Toks.push_back(Tok);
00777   ConsumeToken();
00778 
00779   // We can't reliably skip over a mem-initializer-id, because it could be
00780   // a template-id involving not-yet-declared names. Given:
00781   //
00782   //   S ( ) : a < b < c > ( e )
00783   //
00784   // 'e' might be an initializer or part of a template argument, depending
00785   // on whether 'b' is a template.
00786 
00787   // Track whether we might be inside a template argument. We can give
00788   // significantly better diagnostics if we know that we're not.
00789   bool MightBeTemplateArgument = false;
00790 
00791   while (true) {
00792     // Skip over the mem-initializer-id, if possible.
00793     if (Tok.is(tok::kw_decltype)) {
00794       Toks.push_back(Tok);
00795       SourceLocation OpenLoc = ConsumeToken();
00796       if (Tok.isNot(tok::l_paren))
00797         return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
00798                  << "decltype";
00799       Toks.push_back(Tok);
00800       ConsumeParen();
00801       if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
00802         Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
00803         Diag(OpenLoc, diag::note_matching) << tok::l_paren;
00804         return true;
00805       }
00806     }
00807     do {
00808       // Walk over a component of a nested-name-specifier.
00809       if (Tok.is(tok::coloncolon)) {
00810         Toks.push_back(Tok);
00811         ConsumeToken();
00812 
00813         if (Tok.is(tok::kw_template)) {
00814           Toks.push_back(Tok);
00815           ConsumeToken();
00816         }
00817       }
00818 
00819       if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
00820         Toks.push_back(Tok);
00821         ConsumeToken();
00822       } else if (Tok.is(tok::code_completion)) {
00823         Toks.push_back(Tok);
00824         ConsumeCodeCompletionToken();
00825         // Consume the rest of the initializers permissively.
00826         // FIXME: We should be able to perform code-completion here even if
00827         //        there isn't a subsequent '{' token.
00828         MightBeTemplateArgument = true;
00829         break;
00830       } else {
00831         break;
00832       }
00833     } while (Tok.is(tok::coloncolon));
00834 
00835     if (Tok.is(tok::less))
00836       MightBeTemplateArgument = true;
00837 
00838     if (MightBeTemplateArgument) {
00839       // We may be inside a template argument list. Grab up to the start of the
00840       // next parenthesized initializer or braced-init-list. This *might* be the
00841       // initializer, or it might be a subexpression in the template argument
00842       // list.
00843       // FIXME: Count angle brackets, and clear MightBeTemplateArgument
00844       //        if all angles are closed.
00845       if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
00846                                 /*StopAtSemi=*/true,
00847                                 /*ConsumeFinalToken=*/false)) {
00848         // We're not just missing the initializer, we're also missing the
00849         // function body!
00850         return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
00851       }
00852     } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
00853       // We found something weird in a mem-initializer-id.
00854       if (getLangOpts().CPlusPlus11)
00855         return Diag(Tok.getLocation(), diag::err_expected_either)
00856                << tok::l_paren << tok::l_brace;
00857       else
00858         return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
00859     }
00860 
00861     tok::TokenKind kind = Tok.getKind();
00862     Toks.push_back(Tok);
00863     bool IsLParen = (kind == tok::l_paren);
00864     SourceLocation OpenLoc = Tok.getLocation();
00865 
00866     if (IsLParen) {
00867       ConsumeParen();
00868     } else {
00869       assert(kind == tok::l_brace && "Must be left paren or brace here.");
00870       ConsumeBrace();
00871       // In C++03, this has to be the start of the function body, which
00872       // means the initializer is malformed; we'll diagnose it later.
00873       if (!getLangOpts().CPlusPlus11)
00874         return false;
00875     }
00876 
00877     // Grab the initializer (or the subexpression of the template argument).
00878     // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
00879     //        if we might be inside the braces of a lambda-expression.
00880     tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
00881     if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
00882       Diag(Tok, diag::err_expected) << CloseKind;
00883       Diag(OpenLoc, diag::note_matching) << kind;
00884       return true;
00885     }
00886 
00887     // Grab pack ellipsis, if present.
00888     if (Tok.is(tok::ellipsis)) {
00889       Toks.push_back(Tok);
00890       ConsumeToken();
00891     }
00892 
00893     // If we know we just consumed a mem-initializer, we must have ',' or '{'
00894     // next.
00895     if (Tok.is(tok::comma)) {
00896       Toks.push_back(Tok);
00897       ConsumeToken();
00898     } else if (Tok.is(tok::l_brace)) {
00899       // This is the function body if the ')' or '}' is immediately followed by
00900       // a '{'. That cannot happen within a template argument, apart from the
00901       // case where a template argument contains a compound literal:
00902       //
00903       //   S ( ) : a < b < c > ( d ) { }
00904       //   // End of declaration, or still inside the template argument?
00905       //
00906       // ... and the case where the template argument contains a lambda:
00907       //
00908       //   S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
00909       //     ( ) > ( ) { }
00910       //
00911       // FIXME: Disambiguate these cases. Note that the latter case is probably
00912       //        going to be made ill-formed by core issue 1607.
00913       Toks.push_back(Tok);
00914       ConsumeBrace();
00915       return false;
00916     } else if (!MightBeTemplateArgument) {
00917       return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
00918                                                                 << tok::comma;
00919     }
00920   }
00921 }
00922 
00923 /// \brief Consume and store tokens from the '?' to the ':' in a conditional
00924 /// expression.
00925 bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
00926   // Consume '?'.
00927   assert(Tok.is(tok::question));
00928   Toks.push_back(Tok);
00929   ConsumeToken();
00930 
00931   while (Tok.isNot(tok::colon)) {
00932     if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
00933                               /*StopAtSemi=*/true,
00934                               /*ConsumeFinalToken=*/false))
00935       return false;
00936 
00937     // If we found a nested conditional, consume it.
00938     if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
00939       return false;
00940   }
00941 
00942   // Consume ':'.
00943   Toks.push_back(Tok);
00944   ConsumeToken();
00945   return true;
00946 }
00947 
00948 /// \brief A tentative parsing action that can also revert token annotations.
00949 class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
00950 public:
00951   explicit UnannotatedTentativeParsingAction(Parser &Self,
00952                                              tok::TokenKind EndKind)
00953       : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
00954     // Stash away the old token stream, so we can restore it once the
00955     // tentative parse is complete.
00956     TentativeParsingAction Inner(Self);
00957     Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
00958     Inner.Revert();
00959   }
00960 
00961   void RevertAnnotations() {
00962     Revert();
00963 
00964     // Put back the original tokens.
00965     Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
00966     if (Toks.size()) {
00967       Token *Buffer = new Token[Toks.size()];
00968       std::copy(Toks.begin() + 1, Toks.end(), Buffer);
00969       Buffer[Toks.size() - 1] = Self.Tok;
00970       Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
00971 
00972       Self.Tok = Toks.front();
00973     }
00974   }
00975 
00976 private:
00977   Parser &Self;
00978   CachedTokens Toks;
00979   tok::TokenKind EndKind;
00980 };
00981 
00982 /// ConsumeAndStoreInitializer - Consume and store the token at the passed token
00983 /// container until the end of the current initializer expression (either a
00984 /// default argument or an in-class initializer for a non-static data member).
00985 ///
00986 /// Returns \c true if we reached the end of something initializer-shaped,
00987 /// \c false if we bailed out.
00988 bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
00989                                         CachedInitKind CIK) {
00990   // We always want this function to consume at least one token if not at EOF.
00991   bool IsFirstToken = true;
00992 
00993   // Number of possible unclosed <s we've seen so far. These might be templates,
00994   // and might not, but if there were none of them (or we know for sure that
00995   // we're within a template), we can avoid a tentative parse.
00996   unsigned AngleCount = 0;
00997   unsigned KnownTemplateCount = 0;
00998 
00999   while (1) {
01000     switch (Tok.getKind()) {
01001     case tok::comma:
01002       // If we might be in a template, perform a tentative parse to check.
01003       if (!AngleCount)
01004         // Not a template argument: this is the end of the initializer.
01005         return true;
01006       if (KnownTemplateCount)
01007         goto consume_token;
01008 
01009       // We hit a comma inside angle brackets. This is the hard case. The
01010       // rule we follow is:
01011       //  * For a default argument, if the tokens after the comma form a
01012       //    syntactically-valid parameter-declaration-clause, in which each
01013       //    parameter has an initializer, then this comma ends the default
01014       //    argument.
01015       //  * For a default initializer, if the tokens after the comma form a
01016       //    syntactically-valid init-declarator-list, then this comma ends
01017       //    the default initializer.
01018       {
01019         UnannotatedTentativeParsingAction PA(*this,
01020                                              CIK == CIK_DefaultInitializer
01021                                                ? tok::semi : tok::r_paren);
01022         Sema::TentativeAnalysisScope Scope(Actions);
01023 
01024         TPResult Result = TPResult::Error;
01025         ConsumeToken();
01026         switch (CIK) {
01027         case CIK_DefaultInitializer:
01028           Result = TryParseInitDeclaratorList();
01029           // If we parsed a complete, ambiguous init-declarator-list, this
01030           // is only syntactically-valid if it's followed by a semicolon.
01031           if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
01032             Result = TPResult::False;
01033           break;
01034 
01035         case CIK_DefaultArgument:
01036           bool InvalidAsDeclaration = false;
01037           Result = TryParseParameterDeclarationClause(
01038               &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
01039           // If this is an expression or a declaration with a missing
01040           // 'typename', assume it's not a declaration.
01041           if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
01042             Result = TPResult::False;
01043           break;
01044         }
01045 
01046         // If what follows could be a declaration, it is a declaration.
01047         if (Result != TPResult::False && Result != TPResult::Error) {
01048           PA.Revert();
01049           return true;
01050         }
01051 
01052         // In the uncommon case that we decide the following tokens are part
01053         // of a template argument, revert any annotations we've performed in
01054         // those tokens. We're not going to look them up until we've parsed
01055         // the rest of the class, and that might add more declarations.
01056         PA.RevertAnnotations();
01057       }
01058 
01059       // Keep going. We know we're inside a template argument list now.
01060       ++KnownTemplateCount;
01061       goto consume_token;
01062 
01063     case tok::eof:
01064     case tok::annot_module_begin:
01065     case tok::annot_module_end:
01066     case tok::annot_module_include:
01067       // Ran out of tokens.
01068       return false;
01069 
01070     case tok::less:
01071       // FIXME: A '<' can only start a template-id if it's preceded by an
01072       // identifier, an operator-function-id, or a literal-operator-id.
01073       ++AngleCount;
01074       goto consume_token;
01075 
01076     case tok::question:
01077       // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
01078       // that is *never* the end of the initializer. Skip to the ':'.
01079       if (!ConsumeAndStoreConditional(Toks))
01080         return false;
01081       break;
01082 
01083     case tok::greatergreatergreater:
01084       if (!getLangOpts().CPlusPlus11)
01085         goto consume_token;
01086       if (AngleCount) --AngleCount;
01087       if (KnownTemplateCount) --KnownTemplateCount;
01088       // Fall through.
01089     case tok::greatergreater:
01090       if (!getLangOpts().CPlusPlus11)
01091         goto consume_token;
01092       if (AngleCount) --AngleCount;
01093       if (KnownTemplateCount) --KnownTemplateCount;
01094       // Fall through.
01095     case tok::greater:
01096       if (AngleCount) --AngleCount;
01097       if (KnownTemplateCount) --KnownTemplateCount;
01098       goto consume_token;
01099 
01100     case tok::kw_template:
01101       // 'template' identifier '<' is known to start a template argument list,
01102       // and can be used to disambiguate the parse.
01103       // FIXME: Support all forms of 'template' unqualified-id '<'.
01104       Toks.push_back(Tok);
01105       ConsumeToken();
01106       if (Tok.is(tok::identifier)) {
01107         Toks.push_back(Tok);
01108         ConsumeToken();
01109         if (Tok.is(tok::less)) {
01110           ++AngleCount;
01111           ++KnownTemplateCount;
01112           Toks.push_back(Tok);
01113           ConsumeToken();
01114         }
01115       }
01116       break;
01117 
01118     case tok::kw_operator:
01119       // If 'operator' precedes other punctuation, that punctuation loses
01120       // its special behavior.
01121       Toks.push_back(Tok);
01122       ConsumeToken();
01123       switch (Tok.getKind()) {
01124       case tok::comma:
01125       case tok::greatergreatergreater:
01126       case tok::greatergreater:
01127       case tok::greater:
01128       case tok::less:
01129         Toks.push_back(Tok);
01130         ConsumeToken();
01131         break;
01132       default:
01133         break;
01134       }
01135       break;
01136 
01137     case tok::l_paren:
01138       // Recursively consume properly-nested parens.
01139       Toks.push_back(Tok);
01140       ConsumeParen();
01141       ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
01142       break;
01143     case tok::l_square:
01144       // Recursively consume properly-nested square brackets.
01145       Toks.push_back(Tok);
01146       ConsumeBracket();
01147       ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
01148       break;
01149     case tok::l_brace:
01150       // Recursively consume properly-nested braces.
01151       Toks.push_back(Tok);
01152       ConsumeBrace();
01153       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
01154       break;
01155 
01156     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
01157     // Since the user wasn't looking for this token (if they were, it would
01158     // already be handled), this isn't balanced.  If there is a LHS token at a
01159     // higher level, we will assume that this matches the unbalanced token
01160     // and return it.  Otherwise, this is a spurious RHS token, which we
01161     // consume and pass on to downstream code to diagnose.
01162     case tok::r_paren:
01163       if (CIK == CIK_DefaultArgument)
01164         return true; // End of the default argument.
01165       if (ParenCount && !IsFirstToken)
01166         return false;
01167       Toks.push_back(Tok);
01168       ConsumeParen();
01169       continue;
01170     case tok::r_square:
01171       if (BracketCount && !IsFirstToken)
01172         return false;
01173       Toks.push_back(Tok);
01174       ConsumeBracket();
01175       continue;
01176     case tok::r_brace:
01177       if (BraceCount && !IsFirstToken)
01178         return false;
01179       Toks.push_back(Tok);
01180       ConsumeBrace();
01181       continue;
01182 
01183     case tok::code_completion:
01184       Toks.push_back(Tok);
01185       ConsumeCodeCompletionToken();
01186       break;
01187 
01188     case tok::string_literal:
01189     case tok::wide_string_literal:
01190     case tok::utf8_string_literal:
01191     case tok::utf16_string_literal:
01192     case tok::utf32_string_literal:
01193       Toks.push_back(Tok);
01194       ConsumeStringToken();
01195       break;
01196     case tok::semi:
01197       if (CIK == CIK_DefaultInitializer)
01198         return true; // End of the default initializer.
01199       // FALL THROUGH.
01200     default:
01201     consume_token:
01202       Toks.push_back(Tok);
01203       ConsumeToken();
01204       break;
01205     }
01206     IsFirstToken = false;
01207   }
01208 }