Home | History | Annotate | Download | only in Parse
      1 //===--- ParseCXXInlineMethods.cpp - C++ class inline methods parsing------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file implements parsing for C++ class inline methods.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Parse/Parser.h"
     15 #include "RAIIObjectsForParser.h"
     16 #include "clang/AST/DeclTemplate.h"
     17 #include "clang/Parse/ParseDiagnostic.h"
     18 #include "clang/Sema/DeclSpec.h"
     19 #include "clang/Sema/Scope.h"
     20 using namespace clang;
     21 
     22 /// Get the FunctionDecl for a function or function template decl.
     23 static FunctionDecl *getFunctionDecl(Decl *D) {
     24   if (FunctionDecl *fn = dyn_cast<FunctionDecl>(D))
     25     return fn;
     26   return cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
     27 }
     28 
     29 /// ParseCXXInlineMethodDef - We parsed and verified that the specified
     30 /// Declarator is a well formed C++ inline method definition. Now lex its body
     31 /// and store its tokens for parsing after the C++ class is complete.
     32 NamedDecl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS,
     33                                       AttributeList *AccessAttrs,
     34                                       ParsingDeclarator &D,
     35                                       const ParsedTemplateInfo &TemplateInfo,
     36                                       const VirtSpecifiers& VS,
     37                                       FunctionDefinitionKind DefinitionKind,
     38                                       ExprResult& Init) {
     39   assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
     40   assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try) ||
     41           Tok.is(tok::equal)) &&
     42          "Current token not a '{', ':', '=', or 'try'!");
     43 
     44   MultiTemplateParamsArg TemplateParams(
     45           TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() : 0,
     46           TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
     47 
     48   NamedDecl *FnD;
     49   D.setFunctionDefinitionKind(DefinitionKind);
     50   if (D.getDeclSpec().isFriendSpecified())
     51     FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
     52                                           TemplateParams);
     53   else {
     54     FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
     55                                            TemplateParams, 0,
     56                                            VS, ICIS_NoInit);
     57     if (FnD) {
     58       Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs, false,
     59                                        true);
     60       bool TypeSpecContainsAuto = D.getDeclSpec().containsPlaceholderType();
     61       if (Init.isUsable())
     62         Actions.AddInitializerToDecl(FnD, Init.get(), false,
     63                                      TypeSpecContainsAuto);
     64       else
     65         Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto);
     66     }
     67   }
     68 
     69   HandleMemberFunctionDeclDelays(D, FnD);
     70 
     71   D.complete(FnD);
     72 
     73   if (Tok.is(tok::equal)) {
     74     ConsumeToken();
     75 
     76     if (!FnD) {
     77       SkipUntil(tok::semi);
     78       return 0;
     79     }
     80 
     81     bool Delete = false;
     82     SourceLocation KWLoc;
     83     if (Tok.is(tok::kw_delete)) {
     84       Diag(Tok, getLangOpts().CPlusPlus11 ?
     85            diag::warn_cxx98_compat_deleted_function :
     86            diag::ext_deleted_function);
     87 
     88       KWLoc = ConsumeToken();
     89       Actions.SetDeclDeleted(FnD, KWLoc);
     90       Delete = true;
     91     } else if (Tok.is(tok::kw_default)) {
     92       Diag(Tok, getLangOpts().CPlusPlus11 ?
     93            diag::warn_cxx98_compat_defaulted_function :
     94            diag::ext_defaulted_function);
     95 
     96       KWLoc = ConsumeToken();
     97       Actions.SetDeclDefaulted(FnD, KWLoc);
     98     } else {
     99       llvm_unreachable("function definition after = not 'delete' or 'default'");
    100     }
    101 
    102     if (Tok.is(tok::comma)) {
    103       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
    104         << Delete;
    105       SkipUntil(tok::semi);
    106     } else {
    107       ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
    108                        Delete ? "delete" : "default", tok::semi);
    109     }
    110 
    111     return FnD;
    112   }
    113 
    114   // In delayed template parsing mode, if we are within a class template
    115   // or if we are about to parse function member template then consume
    116   // the tokens and store them for parsing at the end of the translation unit.
    117   if (getLangOpts().DelayedTemplateParsing &&
    118       DefinitionKind == FDK_Definition &&
    119       ((Actions.CurContext->isDependentContext() ||
    120         TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) &&
    121         !Actions.IsInsideALocalClassWithinATemplateFunction())) {
    122 
    123     if (FnD) {
    124       LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(FnD);
    125 
    126       FunctionDecl *FD = getFunctionDecl(FnD);
    127       Actions.CheckForFunctionRedefinition(FD);
    128 
    129       LateParsedTemplateMap[FD] = LPT;
    130       Actions.MarkAsLateParsedTemplate(FD);
    131       LexTemplateFunctionForLateParsing(LPT->Toks);
    132     } else {
    133       CachedTokens Toks;
    134       LexTemplateFunctionForLateParsing(Toks);
    135     }
    136 
    137     return FnD;
    138   }
    139 
    140   // Consume the tokens and store them for later parsing.
    141 
    142   LexedMethod* LM = new LexedMethod(this, FnD);
    143   getCurrentClass().LateParsedDeclarations.push_back(LM);
    144   LM->TemplateScope = getCurScope()->isTemplateParamScope();
    145   CachedTokens &Toks = LM->Toks;
    146 
    147   tok::TokenKind kind = Tok.getKind();
    148   // Consume everything up to (and including) the left brace of the
    149   // function body.
    150   if (ConsumeAndStoreFunctionPrologue(Toks)) {
    151     // We didn't find the left-brace we expected after the
    152     // constructor initializer; we already printed an error, and it's likely
    153     // impossible to recover, so don't try to parse this method later.
    154     // Skip over the rest of the decl and back to somewhere that looks
    155     // reasonable.
    156     SkipMalformedDecl();
    157     delete getCurrentClass().LateParsedDeclarations.back();
    158     getCurrentClass().LateParsedDeclarations.pop_back();
    159     return FnD;
    160   } else {
    161     // Consume everything up to (and including) the matching right brace.
    162     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
    163   }
    164 
    165   // If we're in a function-try-block, we need to store all the catch blocks.
    166   if (kind == tok::kw_try) {
    167     while (Tok.is(tok::kw_catch)) {
    168       ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
    169       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
    170     }
    171   }
    172 
    173   if (FnD) {
    174     // If this is a friend function, mark that it's late-parsed so that
    175     // it's still known to be a definition even before we attach the
    176     // parsed body.  Sema needs to treat friend function definitions
    177     // differently during template instantiation, and it's possible for
    178     // the containing class to be instantiated before all its member
    179     // function definitions are parsed.
    180     //
    181     // If you remove this, you can remove the code that clears the flag
    182     // after parsing the member.
    183     if (D.getDeclSpec().isFriendSpecified()) {
    184       getFunctionDecl(FnD)->setLateTemplateParsed(true);
    185     }
    186   } else {
    187     // If semantic analysis could not build a function declaration,
    188     // just throw away the late-parsed declaration.
    189     delete getCurrentClass().LateParsedDeclarations.back();
    190     getCurrentClass().LateParsedDeclarations.pop_back();
    191   }
    192 
    193   return FnD;
    194 }
    195 
    196 /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
    197 /// specified Declarator is a well formed C++ non-static data member
    198 /// declaration. Now lex its initializer and store its tokens for parsing
    199 /// after the class is complete.
    200 void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
    201   assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
    202          "Current token not a '{' or '='!");
    203 
    204   LateParsedMemberInitializer *MI =
    205     new LateParsedMemberInitializer(this, VarD);
    206   getCurrentClass().LateParsedDeclarations.push_back(MI);
    207   CachedTokens &Toks = MI->Toks;
    208 
    209   tok::TokenKind kind = Tok.getKind();
    210   if (kind == tok::equal) {
    211     Toks.push_back(Tok);
    212     ConsumeToken();
    213   }
    214 
    215   if (kind == tok::l_brace) {
    216     // Begin by storing the '{' token.
    217     Toks.push_back(Tok);
    218     ConsumeBrace();
    219 
    220     // Consume everything up to (and including) the matching right brace.
    221     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
    222   } else {
    223     // Consume everything up to (but excluding) the comma or semicolon.
    224     ConsumeAndStoreUntil(tok::comma, Toks, /*StopAtSemi=*/true,
    225                          /*ConsumeFinalToken=*/false);
    226   }
    227 
    228   // Store an artificial EOF token to ensure that we don't run off the end of
    229   // the initializer when we come to parse it.
    230   Token Eof;
    231   Eof.startToken();
    232   Eof.setKind(tok::eof);
    233   Eof.setLocation(Tok.getLocation());
    234   Toks.push_back(Eof);
    235 }
    236 
    237 Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
    238 void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
    239 void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
    240 void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
    241 
    242 Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
    243   : Self(P), Class(C) {}
    244 
    245 Parser::LateParsedClass::~LateParsedClass() {
    246   Self->DeallocateParsedClasses(Class);
    247 }
    248 
    249 void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
    250   Self->ParseLexedMethodDeclarations(*Class);
    251 }
    252 
    253 void Parser::LateParsedClass::ParseLexedMemberInitializers() {
    254   Self->ParseLexedMemberInitializers(*Class);
    255 }
    256 
    257 void Parser::LateParsedClass::ParseLexedMethodDefs() {
    258   Self->ParseLexedMethodDefs(*Class);
    259 }
    260 
    261 void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
    262   Self->ParseLexedMethodDeclaration(*this);
    263 }
    264 
    265 void Parser::LexedMethod::ParseLexedMethodDefs() {
    266   Self->ParseLexedMethodDef(*this);
    267 }
    268 
    269 void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
    270   Self->ParseLexedMemberInitializer(*this);
    271 }
    272 
    273 /// ParseLexedMethodDeclarations - We finished parsing the member
    274 /// specification of a top (non-nested) C++ class. Now go over the
    275 /// stack of method declarations with some parts for which parsing was
    276 /// delayed (such as default arguments) and parse them.
    277 void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
    278   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
    279   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
    280   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
    281   if (HasTemplateScope) {
    282     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
    283     ++CurTemplateDepthTracker;
    284   }
    285 
    286   // The current scope is still active if we're the top-level class.
    287   // Otherwise we'll need to push and enter a new scope.
    288   bool HasClassScope = !Class.TopLevelClass;
    289   ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
    290                         HasClassScope);
    291   if (HasClassScope)
    292     Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
    293 
    294   for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
    295     Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
    296   }
    297 
    298   if (HasClassScope)
    299     Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
    300 }
    301 
    302 void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
    303   // If this is a member template, introduce the template parameter scope.
    304   ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
    305   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
    306   if (LM.TemplateScope) {
    307     Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
    308     ++CurTemplateDepthTracker;
    309   }
    310   // Start the delayed C++ method declaration
    311   Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
    312 
    313   // Introduce the parameters into scope and parse their default
    314   // arguments.
    315   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
    316                             Scope::FunctionDeclarationScope | Scope::DeclScope);
    317   for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
    318     // Introduce the parameter into scope.
    319     Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
    320                                            LM.DefaultArgs[I].Param);
    321 
    322     if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
    323       // Save the current token position.
    324       SourceLocation origLoc = Tok.getLocation();
    325 
    326       // Parse the default argument from its saved token stream.
    327       Toks->push_back(Tok); // So that the current token doesn't get lost
    328       PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
    329 
    330       // Consume the previously-pushed token.
    331       ConsumeAnyToken();
    332 
    333       // Consume the '='.
    334       assert(Tok.is(tok::equal) && "Default argument not starting with '='");
    335       SourceLocation EqualLoc = ConsumeToken();
    336 
    337       // The argument isn't actually potentially evaluated unless it is
    338       // used.
    339       EnterExpressionEvaluationContext Eval(Actions,
    340                                             Sema::PotentiallyEvaluatedIfUsed,
    341                                             LM.DefaultArgs[I].Param);
    342 
    343       ExprResult DefArgResult;
    344       if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
    345         Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
    346         DefArgResult = ParseBraceInitializer();
    347       } else
    348         DefArgResult = ParseAssignmentExpression();
    349       if (DefArgResult.isInvalid())
    350         Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
    351       else {
    352         if (Tok.is(tok::cxx_defaultarg_end))
    353           ConsumeToken();
    354         else
    355           Diag(Tok.getLocation(), diag::err_default_arg_unparsed);
    356         Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
    357                                           DefArgResult.take());
    358       }
    359 
    360       assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
    361                                                          Tok.getLocation()) &&
    362              "ParseAssignmentExpression went over the default arg tokens!");
    363       // There could be leftover tokens (e.g. because of an error).
    364       // Skip through until we reach the original token position.
    365       while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
    366         ConsumeAnyToken();
    367 
    368       delete Toks;
    369       LM.DefaultArgs[I].Toks = 0;
    370     }
    371   }
    372 
    373   PrototypeScope.Exit();
    374 
    375   // Finish the delayed C++ method declaration.
    376   Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
    377 }
    378 
    379 /// ParseLexedMethodDefs - We finished parsing the member specification of a top
    380 /// (non-nested) C++ class. Now go over the stack of lexed methods that were
    381 /// collected during its parsing and parse them all.
    382 void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
    383   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
    384   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
    385   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
    386   if (HasTemplateScope) {
    387     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
    388     ++CurTemplateDepthTracker;
    389   }
    390   bool HasClassScope = !Class.TopLevelClass;
    391   ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
    392                         HasClassScope);
    393 
    394   for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
    395     Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
    396   }
    397 }
    398 
    399 void Parser::ParseLexedMethodDef(LexedMethod &LM) {
    400   // If this is a member template, introduce the template parameter scope.
    401   ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
    402   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
    403   if (LM.TemplateScope) {
    404     Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
    405     ++CurTemplateDepthTracker;
    406   }
    407   // Save the current token position.
    408   SourceLocation origLoc = Tok.getLocation();
    409 
    410   assert(!LM.Toks.empty() && "Empty body!");
    411   // Append the current token at the end of the new token stream so that it
    412   // doesn't get lost.
    413   LM.Toks.push_back(Tok);
    414   PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
    415 
    416   // Consume the previously pushed token.
    417   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
    418   assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
    419          && "Inline method not starting with '{', ':' or 'try'");
    420 
    421   // Parse the method body. Function body parsing code is similar enough
    422   // to be re-used for method bodies as well.
    423   ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
    424   Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
    425 
    426   if (Tok.is(tok::kw_try)) {
    427     ParseFunctionTryBlock(LM.D, FnScope);
    428     assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
    429                                                          Tok.getLocation()) &&
    430            "ParseFunctionTryBlock went over the cached tokens!");
    431     // There could be leftover tokens (e.g. because of an error).
    432     // Skip through until we reach the original token position.
    433     while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
    434       ConsumeAnyToken();
    435     return;
    436   }
    437   if (Tok.is(tok::colon)) {
    438     ParseConstructorInitializer(LM.D);
    439 
    440     // Error recovery.
    441     if (!Tok.is(tok::l_brace)) {
    442       FnScope.Exit();
    443       Actions.ActOnFinishFunctionBody(LM.D, 0);
    444       while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
    445         ConsumeAnyToken();
    446       return;
    447     }
    448   } else
    449     Actions.ActOnDefaultCtorInitializers(LM.D);
    450 
    451   assert((Actions.getDiagnostics().hasErrorOccurred() ||
    452           !isa<FunctionTemplateDecl>(LM.D) ||
    453           cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
    454             < TemplateParameterDepth) &&
    455          "TemplateParameterDepth should be greater than the depth of "
    456          "current template being instantiated!");
    457 
    458   ParseFunctionStatementBody(LM.D, FnScope);
    459 
    460   // Clear the late-template-parsed bit if we set it before.
    461   if (LM.D) getFunctionDecl(LM.D)->setLateTemplateParsed(false);
    462 
    463   if (Tok.getLocation() != origLoc) {
    464     // Due to parsing error, we either went over the cached tokens or
    465     // there are still cached tokens left. If it's the latter case skip the
    466     // leftover tokens.
    467     // Since this is an uncommon situation that should be avoided, use the
    468     // expensive isBeforeInTranslationUnit call.
    469     if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
    470                                                         origLoc))
    471       while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
    472         ConsumeAnyToken();
    473   }
    474 }
    475 
    476 /// ParseLexedMemberInitializers - We finished parsing the member specification
    477 /// of a top (non-nested) C++ class. Now go over the stack of lexed data member
    478 /// initializers that were collected during its parsing and parse them all.
    479 void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
    480   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
    481   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
    482                                 HasTemplateScope);
    483   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
    484   if (HasTemplateScope) {
    485     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
    486     ++CurTemplateDepthTracker;
    487   }
    488   // Set or update the scope flags.
    489   bool AlreadyHasClassScope = Class.TopLevelClass;
    490   unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
    491   ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
    492   ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
    493 
    494   if (!AlreadyHasClassScope)
    495     Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
    496                                                 Class.TagOrTemplate);
    497 
    498   if (!Class.LateParsedDeclarations.empty()) {
    499     // C++11 [expr.prim.general]p4:
    500     //   Otherwise, if a member-declarator declares a non-static data member
    501     //  (9.2) of a class X, the expression this is a prvalue of type "pointer
    502     //  to X" within the optional brace-or-equal-initializer. It shall not
    503     //  appear elsewhere in the member-declarator.
    504     Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
    505                                      /*TypeQuals=*/(unsigned)0);
    506 
    507     for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
    508       Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
    509     }
    510   }
    511 
    512   if (!AlreadyHasClassScope)
    513     Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
    514                                                  Class.TagOrTemplate);
    515 
    516   Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
    517 }
    518 
    519 void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
    520   if (!MI.Field || MI.Field->isInvalidDecl())
    521     return;
    522 
    523   // Append the current token at the end of the new token stream so that it
    524   // doesn't get lost.
    525   MI.Toks.push_back(Tok);
    526   PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
    527 
    528   // Consume the previously pushed token.
    529   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
    530 
    531   SourceLocation EqualLoc;
    532 
    533   ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
    534                                               EqualLoc);
    535 
    536   Actions.ActOnCXXInClassMemberInitializer(MI.Field, EqualLoc, Init.release());
    537 
    538   // The next token should be our artificial terminating EOF token.
    539   if (Tok.isNot(tok::eof)) {
    540     SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
    541     if (!EndLoc.isValid())
    542       EndLoc = Tok.getLocation();
    543     // No fixit; we can't recover as if there were a semicolon here.
    544     Diag(EndLoc, diag::err_expected_semi_decl_list);
    545 
    546     // Consume tokens until we hit the artificial EOF.
    547     while (Tok.isNot(tok::eof))
    548       ConsumeAnyToken();
    549   }
    550   ConsumeAnyToken();
    551 }
    552 
    553 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
    554 /// container until the token 'T' is reached (which gets
    555 /// consumed/stored too, if ConsumeFinalToken).
    556 /// If StopAtSemi is true, then we will stop early at a ';' character.
    557 /// Returns true if token 'T1' or 'T2' was found.
    558 /// NOTE: This is a specialized version of Parser::SkipUntil.
    559 bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
    560                                   CachedTokens &Toks,
    561                                   bool StopAtSemi, bool ConsumeFinalToken) {
    562   // We always want this function to consume at least one token if the first
    563   // token isn't T and if not at EOF.
    564   bool isFirstTokenConsumed = true;
    565   while (1) {
    566     // If we found one of the tokens, stop and return true.
    567     if (Tok.is(T1) || Tok.is(T2)) {
    568       if (ConsumeFinalToken) {
    569         Toks.push_back(Tok);
    570         ConsumeAnyToken();
    571       }
    572       return true;
    573     }
    574 
    575     switch (Tok.getKind()) {
    576     case tok::eof:
    577       // Ran out of tokens.
    578       return false;
    579 
    580     case tok::l_paren:
    581       // Recursively consume properly-nested parens.
    582       Toks.push_back(Tok);
    583       ConsumeParen();
    584       ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
    585       break;
    586     case tok::l_square:
    587       // Recursively consume properly-nested square brackets.
    588       Toks.push_back(Tok);
    589       ConsumeBracket();
    590       ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
    591       break;
    592     case tok::l_brace:
    593       // Recursively consume properly-nested braces.
    594       Toks.push_back(Tok);
    595       ConsumeBrace();
    596       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
    597       break;
    598 
    599     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
    600     // Since the user wasn't looking for this token (if they were, it would
    601     // already be handled), this isn't balanced.  If there is a LHS token at a
    602     // higher level, we will assume that this matches the unbalanced token
    603     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
    604     case tok::r_paren:
    605       if (ParenCount && !isFirstTokenConsumed)
    606         return false;  // Matches something.
    607       Toks.push_back(Tok);
    608       ConsumeParen();
    609       break;
    610     case tok::r_square:
    611       if (BracketCount && !isFirstTokenConsumed)
    612         return false;  // Matches something.
    613       Toks.push_back(Tok);
    614       ConsumeBracket();
    615       break;
    616     case tok::r_brace:
    617       if (BraceCount && !isFirstTokenConsumed)
    618         return false;  // Matches something.
    619       Toks.push_back(Tok);
    620       ConsumeBrace();
    621       break;
    622 
    623     case tok::code_completion:
    624       Toks.push_back(Tok);
    625       ConsumeCodeCompletionToken();
    626       break;
    627 
    628     case tok::string_literal:
    629     case tok::wide_string_literal:
    630     case tok::utf8_string_literal:
    631     case tok::utf16_string_literal:
    632     case tok::utf32_string_literal:
    633       Toks.push_back(Tok);
    634       ConsumeStringToken();
    635       break;
    636     case tok::semi:
    637       if (StopAtSemi)
    638         return false;
    639       // FALL THROUGH.
    640     default:
    641       // consume this token.
    642       Toks.push_back(Tok);
    643       ConsumeToken();
    644       break;
    645     }
    646     isFirstTokenConsumed = false;
    647   }
    648 }
    649 
    650 /// \brief Consume tokens and store them in the passed token container until
    651 /// we've passed the try keyword and constructor initializers and have consumed
    652 /// the opening brace of the function body. The opening brace will be consumed
    653 /// if and only if there was no error.
    654 ///
    655 /// \return True on error.
    656 bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
    657   if (Tok.is(tok::kw_try)) {
    658     Toks.push_back(Tok);
    659     ConsumeToken();
    660   }
    661 
    662   if (Tok.isNot(tok::colon)) {
    663     // Easy case, just a function body.
    664 
    665     // Grab any remaining garbage to be diagnosed later. We stop when we reach a
    666     // brace: an opening one is the function body, while a closing one probably
    667     // means we've reached the end of the class.
    668     ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
    669                          /*StopAtSemi=*/true,
    670                          /*ConsumeFinalToken=*/false);
    671     if (Tok.isNot(tok::l_brace))
    672       return Diag(Tok.getLocation(), diag::err_expected_lbrace);
    673 
    674     Toks.push_back(Tok);
    675     ConsumeBrace();
    676     return false;
    677   }
    678 
    679   Toks.push_back(Tok);
    680   ConsumeToken();
    681 
    682   // We can't reliably skip over a mem-initializer-id, because it could be
    683   // a template-id involving not-yet-declared names. Given:
    684   //
    685   //   S ( ) : a < b < c > ( e )
    686   //
    687   // 'e' might be an initializer or part of a template argument, depending
    688   // on whether 'b' is a template.
    689 
    690   // Track whether we might be inside a template argument. We can give
    691   // significantly better diagnostics if we know that we're not.
    692   bool MightBeTemplateArgument = false;
    693 
    694   while (true) {
    695     // Skip over the mem-initializer-id, if possible.
    696     if (Tok.is(tok::kw_decltype)) {
    697       Toks.push_back(Tok);
    698       SourceLocation OpenLoc = ConsumeToken();
    699       if (Tok.isNot(tok::l_paren))
    700         return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
    701                  << "decltype";
    702       Toks.push_back(Tok);
    703       ConsumeParen();
    704       if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
    705         Diag(Tok.getLocation(), diag::err_expected_rparen);
    706         Diag(OpenLoc, diag::note_matching) << "(";
    707         return true;
    708       }
    709     }
    710     do {
    711       // Walk over a component of a nested-name-specifier.
    712       if (Tok.is(tok::coloncolon)) {
    713         Toks.push_back(Tok);
    714         ConsumeToken();
    715 
    716         if (Tok.is(tok::kw_template)) {
    717           Toks.push_back(Tok);
    718           ConsumeToken();
    719         }
    720       }
    721 
    722       if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
    723         Toks.push_back(Tok);
    724         ConsumeToken();
    725       } else if (Tok.is(tok::code_completion)) {
    726         Toks.push_back(Tok);
    727         ConsumeCodeCompletionToken();
    728         // Consume the rest of the initializers permissively.
    729         // FIXME: We should be able to perform code-completion here even if
    730         //        there isn't a subsequent '{' token.
    731         MightBeTemplateArgument = true;
    732         break;
    733       } else {
    734         break;
    735       }
    736     } while (Tok.is(tok::coloncolon));
    737 
    738     if (Tok.is(tok::less))
    739       MightBeTemplateArgument = true;
    740 
    741     if (MightBeTemplateArgument) {
    742       // We may be inside a template argument list. Grab up to the start of the
    743       // next parenthesized initializer or braced-init-list. This *might* be the
    744       // initializer, or it might be a subexpression in the template argument
    745       // list.
    746       // FIXME: Count angle brackets, and clear MightBeTemplateArgument
    747       //        if all angles are closed.
    748       if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
    749                                 /*StopAtSemi=*/true,
    750                                 /*ConsumeFinalToken=*/false)) {
    751         // We're not just missing the initializer, we're also missing the
    752         // function body!
    753         return Diag(Tok.getLocation(), diag::err_expected_lbrace);
    754       }
    755     } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
    756       // We found something weird in a mem-initializer-id.
    757       return Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
    758                                          ? diag::err_expected_lparen_or_lbrace
    759                                          : diag::err_expected_lparen);
    760     }
    761 
    762     tok::TokenKind kind = Tok.getKind();
    763     Toks.push_back(Tok);
    764     bool IsLParen = (kind == tok::l_paren);
    765     SourceLocation OpenLoc = Tok.getLocation();
    766 
    767     if (IsLParen) {
    768       ConsumeParen();
    769     } else {
    770       assert(kind == tok::l_brace && "Must be left paren or brace here.");
    771       ConsumeBrace();
    772       // In C++03, this has to be the start of the function body, which
    773       // means the initializer is malformed; we'll diagnose it later.
    774       if (!getLangOpts().CPlusPlus11)
    775         return false;
    776     }
    777 
    778     // Grab the initializer (or the subexpression of the template argument).
    779     // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
    780     //        if we might be inside the braces of a lambda-expression.
    781     if (!ConsumeAndStoreUntil(IsLParen ? tok::r_paren : tok::r_brace,
    782                               Toks, /*StopAtSemi=*/true)) {
    783       Diag(Tok, IsLParen ? diag::err_expected_rparen :
    784                            diag::err_expected_rbrace);
    785       Diag(OpenLoc, diag::note_matching) << (IsLParen ? "(" : "{");
    786       return true;
    787     }
    788 
    789     // Grab pack ellipsis, if present.
    790     if (Tok.is(tok::ellipsis)) {
    791       Toks.push_back(Tok);
    792       ConsumeToken();
    793     }
    794 
    795     // If we know we just consumed a mem-initializer, we must have ',' or '{'
    796     // next.
    797     if (Tok.is(tok::comma)) {
    798       Toks.push_back(Tok);
    799       ConsumeToken();
    800     } else if (Tok.is(tok::l_brace)) {
    801       // This is the function body if the ')' or '}' is immediately followed by
    802       // a '{'. That cannot happen within a template argument, apart from the
    803       // case where a template argument contains a compound literal:
    804       //
    805       //   S ( ) : a < b < c > ( d ) { }
    806       //   // End of declaration, or still inside the template argument?
    807       //
    808       // ... and the case where the template argument contains a lambda:
    809       //
    810       //   S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
    811       //     ( ) > ( ) { }
    812       //
    813       // FIXME: Disambiguate these cases. Note that the latter case is probably
    814       //        going to be made ill-formed by core issue 1607.
    815       Toks.push_back(Tok);
    816       ConsumeBrace();
    817       return false;
    818     } else if (!MightBeTemplateArgument) {
    819       return Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
    820     }
    821   }
    822 }
    823