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