clang  mainline
ParseTemplate.cpp
Go to the documentation of this file.
00001 //===--- ParseTemplate.cpp - Template 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 of C++ templates.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Parse/Parser.h"
00015 #include "RAIIObjectsForParser.h"
00016 #include "clang/AST/ASTConsumer.h"
00017 #include "clang/AST/ASTContext.h"
00018 #include "clang/AST/DeclTemplate.h"
00019 #include "clang/Parse/ParseDiagnostic.h"
00020 #include "clang/Sema/DeclSpec.h"
00021 #include "clang/Sema/ParsedTemplate.h"
00022 #include "clang/Sema/Scope.h"
00023 using namespace clang;
00024 
00025 /// \brief Parse a template declaration, explicit instantiation, or
00026 /// explicit specialization.
00027 Decl *
00028 Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
00029                                              SourceLocation &DeclEnd,
00030                                              AccessSpecifier AS,
00031                                              AttributeList *AccessAttrs) {
00032   ObjCDeclContextSwitch ObjCDC(*this);
00033   
00034   if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
00035     return ParseExplicitInstantiation(Context,
00036                                       SourceLocation(), ConsumeToken(),
00037                                       DeclEnd, AS);
00038   }
00039   return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
00040                                                   AccessAttrs);
00041 }
00042 
00043 
00044 
00045 /// \brief Parse a template declaration or an explicit specialization.
00046 ///
00047 /// Template declarations include one or more template parameter lists
00048 /// and either the function or class template declaration. Explicit
00049 /// specializations contain one or more 'template < >' prefixes
00050 /// followed by a (possibly templated) declaration. Since the
00051 /// syntactic form of both features is nearly identical, we parse all
00052 /// of the template headers together and let semantic analysis sort
00053 /// the declarations from the explicit specializations.
00054 ///
00055 ///       template-declaration: [C++ temp]
00056 ///         'export'[opt] 'template' '<' template-parameter-list '>' declaration
00057 ///
00058 ///       explicit-specialization: [ C++ temp.expl.spec]
00059 ///         'template' '<' '>' declaration
00060 Decl *
00061 Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
00062                                                  SourceLocation &DeclEnd,
00063                                                  AccessSpecifier AS,
00064                                                  AttributeList *AccessAttrs) {
00065   assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
00066          "Token does not start a template declaration.");
00067 
00068   // Enter template-parameter scope.
00069   ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
00070 
00071   // Tell the action that names should be checked in the context of
00072   // the declaration to come.
00073   ParsingDeclRAIIObject
00074     ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
00075 
00076   // Parse multiple levels of template headers within this template
00077   // parameter scope, e.g.,
00078   //
00079   //   template<typename T>
00080   //     template<typename U>
00081   //       class A<T>::B { ... };
00082   //
00083   // We parse multiple levels non-recursively so that we can build a
00084   // single data structure containing all of the template parameter
00085   // lists to easily differentiate between the case above and:
00086   //
00087   //   template<typename T>
00088   //   class A {
00089   //     template<typename U> class B;
00090   //   };
00091   //
00092   // In the first case, the action for declaring A<T>::B receives
00093   // both template parameter lists. In the second case, the action for
00094   // defining A<T>::B receives just the inner template parameter list
00095   // (and retrieves the outer template parameter list from its
00096   // context).
00097   bool isSpecialization = true;
00098   bool LastParamListWasEmpty = false;
00099   TemplateParameterLists ParamLists;
00100   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
00101 
00102   do {
00103     // Consume the 'export', if any.
00104     SourceLocation ExportLoc;
00105     TryConsumeToken(tok::kw_export, ExportLoc);
00106 
00107     // Consume the 'template', which should be here.
00108     SourceLocation TemplateLoc;
00109     if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
00110       Diag(Tok.getLocation(), diag::err_expected_template);
00111       return nullptr;
00112     }
00113 
00114     // Parse the '<' template-parameter-list '>'
00115     SourceLocation LAngleLoc, RAngleLoc;
00116     SmallVector<Decl*, 4> TemplateParams;
00117     if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
00118                                 TemplateParams, LAngleLoc, RAngleLoc)) {
00119       // Skip until the semi-colon or a }.
00120       SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
00121       TryConsumeToken(tok::semi);
00122       return nullptr;
00123     }
00124 
00125     ParamLists.push_back(
00126       Actions.ActOnTemplateParameterList(CurTemplateDepthTracker.getDepth(), 
00127                                          ExportLoc,
00128                                          TemplateLoc, LAngleLoc,
00129                                          TemplateParams.data(),
00130                                          TemplateParams.size(), RAngleLoc));
00131 
00132     if (!TemplateParams.empty()) {
00133       isSpecialization = false;
00134       ++CurTemplateDepthTracker;
00135     } else {
00136       LastParamListWasEmpty = true;
00137     }
00138   } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
00139 
00140   // Parse the actual template declaration.
00141   return ParseSingleDeclarationAfterTemplate(Context,
00142                                              ParsedTemplateInfo(&ParamLists,
00143                                                              isSpecialization,
00144                                                          LastParamListWasEmpty),
00145                                              ParsingTemplateParams,
00146                                              DeclEnd, AS, AccessAttrs);
00147 }
00148 
00149 /// \brief Parse a single declaration that declares a template,
00150 /// template specialization, or explicit instantiation of a template.
00151 ///
00152 /// \param DeclEnd will receive the source location of the last token
00153 /// within this declaration.
00154 ///
00155 /// \param AS the access specifier associated with this
00156 /// declaration. Will be AS_none for namespace-scope declarations.
00157 ///
00158 /// \returns the new declaration.
00159 Decl *
00160 Parser::ParseSingleDeclarationAfterTemplate(
00161                                        unsigned Context,
00162                                        const ParsedTemplateInfo &TemplateInfo,
00163                                        ParsingDeclRAIIObject &DiagsFromTParams,
00164                                        SourceLocation &DeclEnd,
00165                                        AccessSpecifier AS,
00166                                        AttributeList *AccessAttrs) {
00167   assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
00168          "Template information required");
00169 
00170   if (Tok.is(tok::kw_static_assert)) {
00171     // A static_assert declaration may not be templated.
00172     Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
00173       << TemplateInfo.getSourceRange();
00174     // Parse the static_assert declaration to improve error recovery.
00175     return ParseStaticAssertDeclaration(DeclEnd);
00176   }
00177 
00178   if (Context == Declarator::MemberContext) {
00179     // We are parsing a member template.
00180     ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
00181                                    &DiagsFromTParams);
00182     return nullptr;
00183   }
00184 
00185   ParsedAttributesWithRange prefixAttrs(AttrFactory);
00186   MaybeParseCXX11Attributes(prefixAttrs);
00187 
00188   if (Tok.is(tok::kw_using))
00189     return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
00190                                             prefixAttrs);
00191 
00192   // Parse the declaration specifiers, stealing any diagnostics from
00193   // the template parameters.
00194   ParsingDeclSpec DS(*this, &DiagsFromTParams);
00195 
00196   ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
00197                              getDeclSpecContextFromDeclaratorContext(Context));
00198 
00199   if (Tok.is(tok::semi)) {
00200     ProhibitAttributes(prefixAttrs);
00201     DeclEnd = ConsumeToken();
00202     Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
00203         getCurScope(), AS, DS,
00204         TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
00205                                     : MultiTemplateParamsArg(),
00206         TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
00207     DS.complete(Decl);
00208     return Decl;
00209   }
00210 
00211   // Move the attributes from the prefix into the DS.
00212   if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
00213     ProhibitAttributes(prefixAttrs);
00214   else
00215     DS.takeAttributesFrom(prefixAttrs);
00216 
00217   // Parse the declarator.
00218   ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
00219   ParseDeclarator(DeclaratorInfo);
00220   // Error parsing the declarator?
00221   if (!DeclaratorInfo.hasName()) {
00222     // If so, skip until the semi-colon or a }.
00223     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
00224     if (Tok.is(tok::semi))
00225       ConsumeToken();
00226     return nullptr;
00227   }
00228 
00229   LateParsedAttrList LateParsedAttrs(true);
00230   if (DeclaratorInfo.isFunctionDeclarator())
00231     MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
00232 
00233   if (DeclaratorInfo.isFunctionDeclarator() &&
00234       isStartOfFunctionDefinition(DeclaratorInfo)) {
00235 
00236     // Function definitions are only allowed at file scope and in C++ classes.
00237     // The C++ inline method definition case is handled elsewhere, so we only
00238     // need to handle the file scope definition case.
00239     if (Context != Declarator::FileContext) {
00240       Diag(Tok, diag::err_function_definition_not_allowed);
00241       SkipMalformedDecl();
00242       return nullptr;
00243     }
00244 
00245     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
00246       // Recover by ignoring the 'typedef'. This was probably supposed to be
00247       // the 'typename' keyword, which we should have already suggested adding
00248       // if it's appropriate.
00249       Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
00250         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
00251       DS.ClearStorageClassSpecs();
00252     }
00253 
00254     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
00255       if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
00256         // If the declarator-id is not a template-id, issue a diagnostic and
00257         // recover by ignoring the 'template' keyword.
00258         Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
00259         return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
00260                                        &LateParsedAttrs);
00261       } else {
00262         SourceLocation LAngleLoc
00263           = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
00264         Diag(DeclaratorInfo.getIdentifierLoc(),
00265              diag::err_explicit_instantiation_with_definition)
00266             << SourceRange(TemplateInfo.TemplateLoc)
00267             << FixItHint::CreateInsertion(LAngleLoc, "<>");
00268 
00269         // Recover as if it were an explicit specialization.
00270         TemplateParameterLists FakedParamLists;
00271         FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
00272             0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
00273             0, LAngleLoc));
00274 
00275         return ParseFunctionDefinition(
00276             DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
00277                                                /*isSpecialization=*/true,
00278                                                /*LastParamListWasEmpty=*/true),
00279             &LateParsedAttrs);
00280       }
00281     }
00282     return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
00283                                    &LateParsedAttrs);
00284   }
00285 
00286   // Parse this declaration.
00287   Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
00288                                                    TemplateInfo);
00289 
00290   if (Tok.is(tok::comma)) {
00291     Diag(Tok, diag::err_multiple_template_declarators)
00292       << (int)TemplateInfo.Kind;
00293     SkipUntil(tok::semi);
00294     return ThisDecl;
00295   }
00296 
00297   // Eat the semi colon after the declaration.
00298   ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
00299   if (LateParsedAttrs.size() > 0)
00300     ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
00301   DeclaratorInfo.complete(ThisDecl);
00302   return ThisDecl;
00303 }
00304 
00305 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
00306 /// angle brackets. Depth is the depth of this template-parameter-list, which
00307 /// is the number of template headers directly enclosing this template header.
00308 /// TemplateParams is the current list of template parameters we're building.
00309 /// The template parameter we parse will be added to this list. LAngleLoc and
00310 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
00311 /// that enclose this template parameter list.
00312 ///
00313 /// \returns true if an error occurred, false otherwise.
00314 bool Parser::ParseTemplateParameters(unsigned Depth,
00315                                SmallVectorImpl<Decl*> &TemplateParams,
00316                                      SourceLocation &LAngleLoc,
00317                                      SourceLocation &RAngleLoc) {
00318   // Get the template parameter list.
00319   if (!TryConsumeToken(tok::less, LAngleLoc)) {
00320     Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
00321     return true;
00322   }
00323 
00324   // Try to parse the template parameter list.
00325   bool Failed = false;
00326   if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
00327     Failed = ParseTemplateParameterList(Depth, TemplateParams);
00328 
00329   if (Tok.is(tok::greatergreater)) {
00330     // No diagnostic required here: a template-parameter-list can only be
00331     // followed by a declaration or, for a template template parameter, the
00332     // 'class' keyword. Therefore, the second '>' will be diagnosed later.
00333     // This matters for elegant diagnosis of:
00334     //   template<template<typename>> struct S;
00335     Tok.setKind(tok::greater);
00336     RAngleLoc = Tok.getLocation();
00337     Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
00338   } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
00339     Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
00340     return true;
00341   }
00342   return false;
00343 }
00344 
00345 /// ParseTemplateParameterList - Parse a template parameter list. If
00346 /// the parsing fails badly (i.e., closing bracket was left out), this
00347 /// will try to put the token stream in a reasonable position (closing
00348 /// a statement, etc.) and return false.
00349 ///
00350 ///       template-parameter-list:    [C++ temp]
00351 ///         template-parameter
00352 ///         template-parameter-list ',' template-parameter
00353 bool
00354 Parser::ParseTemplateParameterList(unsigned Depth,
00355                              SmallVectorImpl<Decl*> &TemplateParams) {
00356   while (1) {
00357     if (Decl *TmpParam
00358           = ParseTemplateParameter(Depth, TemplateParams.size())) {
00359       TemplateParams.push_back(TmpParam);
00360     } else {
00361       // If we failed to parse a template parameter, skip until we find
00362       // a comma or closing brace.
00363       SkipUntil(tok::comma, tok::greater, tok::greatergreater,
00364                 StopAtSemi | StopBeforeMatch);
00365     }
00366 
00367     // Did we find a comma or the end of the template parameter list?
00368     if (Tok.is(tok::comma)) {
00369       ConsumeToken();
00370     } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
00371       // Don't consume this... that's done by template parser.
00372       break;
00373     } else {
00374       // Somebody probably forgot to close the template. Skip ahead and
00375       // try to get out of the expression. This error is currently
00376       // subsumed by whatever goes on in ParseTemplateParameter.
00377       Diag(Tok.getLocation(), diag::err_expected_comma_greater);
00378       SkipUntil(tok::comma, tok::greater, tok::greatergreater,
00379                 StopAtSemi | StopBeforeMatch);
00380       return false;
00381     }
00382   }
00383   return true;
00384 }
00385 
00386 /// \brief Determine whether the parser is at the start of a template
00387 /// type parameter.
00388 bool Parser::isStartOfTemplateTypeParameter() {
00389   if (Tok.is(tok::kw_class)) {
00390     // "class" may be the start of an elaborated-type-specifier or a
00391     // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
00392     switch (NextToken().getKind()) {
00393     case tok::equal:
00394     case tok::comma:
00395     case tok::greater:
00396     case tok::greatergreater:
00397     case tok::ellipsis:
00398       return true;
00399         
00400     case tok::identifier:
00401       // This may be either a type-parameter or an elaborated-type-specifier. 
00402       // We have to look further.
00403       break;
00404         
00405     default:
00406       return false;
00407     }
00408     
00409     switch (GetLookAheadToken(2).getKind()) {
00410     case tok::equal:
00411     case tok::comma:
00412     case tok::greater:
00413     case tok::greatergreater:
00414       return true;
00415       
00416     default:
00417       return false;
00418     }
00419   }
00420 
00421   if (Tok.isNot(tok::kw_typename))
00422     return false;
00423 
00424   // C++ [temp.param]p2:
00425   //   There is no semantic difference between class and typename in a
00426   //   template-parameter. typename followed by an unqualified-id
00427   //   names a template type parameter. typename followed by a
00428   //   qualified-id denotes the type in a non-type
00429   //   parameter-declaration.
00430   Token Next = NextToken();
00431 
00432   // If we have an identifier, skip over it.
00433   if (Next.getKind() == tok::identifier)
00434     Next = GetLookAheadToken(2);
00435 
00436   switch (Next.getKind()) {
00437   case tok::equal:
00438   case tok::comma:
00439   case tok::greater:
00440   case tok::greatergreater:
00441   case tok::ellipsis:
00442     return true;
00443 
00444   default:
00445     return false;
00446   }
00447 }
00448 
00449 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
00450 ///
00451 ///       template-parameter: [C++ temp.param]
00452 ///         type-parameter
00453 ///         parameter-declaration
00454 ///
00455 ///       type-parameter: (see below)
00456 ///         'class' ...[opt] identifier[opt]
00457 ///         'class' identifier[opt] '=' type-id
00458 ///         'typename' ...[opt] identifier[opt]
00459 ///         'typename' identifier[opt] '=' type-id
00460 ///         'template' '<' template-parameter-list '>' 
00461 ///               'class' ...[opt] identifier[opt]
00462 ///         'template' '<' template-parameter-list '>' 'class' identifier[opt]
00463 ///               = id-expression
00464 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
00465   if (isStartOfTemplateTypeParameter())
00466     return ParseTypeParameter(Depth, Position);
00467 
00468   if (Tok.is(tok::kw_template))
00469     return ParseTemplateTemplateParameter(Depth, Position);
00470 
00471   // If it's none of the above, then it must be a parameter declaration.
00472   // NOTE: This will pick up errors in the closure of the template parameter
00473   // list (e.g., template < ; Check here to implement >> style closures.
00474   return ParseNonTypeTemplateParameter(Depth, Position);
00475 }
00476 
00477 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
00478 /// Other kinds of template parameters are parsed in
00479 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
00480 ///
00481 ///       type-parameter:     [C++ temp.param]
00482 ///         'class' ...[opt][C++0x] identifier[opt]
00483 ///         'class' identifier[opt] '=' type-id
00484 ///         'typename' ...[opt][C++0x] identifier[opt]
00485 ///         'typename' identifier[opt] '=' type-id
00486 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
00487   assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
00488          "A type-parameter starts with 'class' or 'typename'");
00489 
00490   // Consume the 'class' or 'typename' keyword.
00491   bool TypenameKeyword = Tok.is(tok::kw_typename);
00492   SourceLocation KeyLoc = ConsumeToken();
00493 
00494   // Grab the ellipsis (if given).
00495   SourceLocation EllipsisLoc;
00496   if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
00497     Diag(EllipsisLoc,
00498          getLangOpts().CPlusPlus11
00499            ? diag::warn_cxx98_compat_variadic_templates
00500            : diag::ext_variadic_templates);
00501   }
00502 
00503   // Grab the template parameter name (if given)
00504   SourceLocation NameLoc;
00505   IdentifierInfo *ParamName = nullptr;
00506   if (Tok.is(tok::identifier)) {
00507     ParamName = Tok.getIdentifierInfo();
00508     NameLoc = ConsumeToken();
00509   } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
00510              Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
00511     // Unnamed template parameter. Don't have to do anything here, just
00512     // don't consume this token.
00513   } else {
00514     Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
00515     return nullptr;
00516   }
00517 
00518   // Recover from misplaced ellipsis.
00519   bool AlreadyHasEllipsis = EllipsisLoc.isValid();
00520   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
00521     DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
00522 
00523   // Grab a default argument (if available).
00524   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
00525   // we introduce the type parameter into the local scope.
00526   SourceLocation EqualLoc;
00527   ParsedType DefaultArg;
00528   if (TryConsumeToken(tok::equal, EqualLoc))
00529     DefaultArg = ParseTypeName(/*Range=*/nullptr,
00530                                Declarator::TemplateTypeArgContext).get();
00531 
00532   return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
00533                                     KeyLoc, ParamName, NameLoc, Depth, Position,
00534                                     EqualLoc, DefaultArg);
00535 }
00536 
00537 /// ParseTemplateTemplateParameter - Handle the parsing of template
00538 /// template parameters.
00539 ///
00540 ///       type-parameter:    [C++ temp.param]
00541 ///         'template' '<' template-parameter-list '>' type-parameter-key
00542 ///                  ...[opt] identifier[opt]
00543 ///         'template' '<' template-parameter-list '>' type-parameter-key
00544 ///                  identifier[opt] = id-expression
00545 ///       type-parameter-key:
00546 ///         'class'
00547 ///         'typename'       [C++1z]
00548 Decl *
00549 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
00550   assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
00551 
00552   // Handle the template <...> part.
00553   SourceLocation TemplateLoc = ConsumeToken();
00554   SmallVector<Decl*,8> TemplateParams;
00555   SourceLocation LAngleLoc, RAngleLoc;
00556   {
00557     ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
00558     if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
00559                                RAngleLoc)) {
00560       return nullptr;
00561     }
00562   }
00563 
00564   // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
00565   // Generate a meaningful error if the user forgot to put class before the
00566   // identifier, comma, or greater. Provide a fixit if the identifier, comma,
00567   // or greater appear immediately or after 'struct'. In the latter case,
00568   // replace the keyword with 'class'.
00569   if (!TryConsumeToken(tok::kw_class)) {
00570     bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
00571     const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
00572     if (Tok.is(tok::kw_typename)) {
00573       Diag(Tok.getLocation(),
00574            getLangOpts().CPlusPlus1z
00575                ? diag::warn_cxx14_compat_template_template_param_typename
00576                : diag::ext_template_template_param_typename)
00577         << (!getLangOpts().CPlusPlus1z
00578                 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
00579                 : FixItHint());
00580     } else if (Next.is(tok::identifier) || Next.is(tok::comma) ||
00581                Next.is(tok::greater) || Next.is(tok::greatergreater) ||
00582                Next.is(tok::ellipsis)) {
00583       Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
00584         << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
00585                     : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
00586     } else
00587       Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
00588 
00589     if (Replace)
00590       ConsumeToken();
00591   }
00592 
00593   // Parse the ellipsis, if given.
00594   SourceLocation EllipsisLoc;
00595   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
00596     Diag(EllipsisLoc,
00597          getLangOpts().CPlusPlus11
00598            ? diag::warn_cxx98_compat_variadic_templates
00599            : diag::ext_variadic_templates);
00600       
00601   // Get the identifier, if given.
00602   SourceLocation NameLoc;
00603   IdentifierInfo *ParamName = nullptr;
00604   if (Tok.is(tok::identifier)) {
00605     ParamName = Tok.getIdentifierInfo();
00606     NameLoc = ConsumeToken();
00607   } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
00608              Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
00609     // Unnamed template parameter. Don't have to do anything here, just
00610     // don't consume this token.
00611   } else {
00612     Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
00613     return nullptr;
00614   }
00615 
00616   // Recover from misplaced ellipsis.
00617   bool AlreadyHasEllipsis = EllipsisLoc.isValid();
00618   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
00619     DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
00620 
00621   TemplateParameterList *ParamList =
00622     Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
00623                                        TemplateLoc, LAngleLoc,
00624                                        TemplateParams.data(),
00625                                        TemplateParams.size(),
00626                                        RAngleLoc);
00627 
00628   // Grab a default argument (if available).
00629   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
00630   // we introduce the template parameter into the local scope.
00631   SourceLocation EqualLoc;
00632   ParsedTemplateArgument DefaultArg;
00633   if (TryConsumeToken(tok::equal, EqualLoc)) {
00634     DefaultArg = ParseTemplateTemplateArgument();
00635     if (DefaultArg.isInvalid()) {
00636       Diag(Tok.getLocation(), 
00637            diag::err_default_template_template_parameter_not_template);
00638       SkipUntil(tok::comma, tok::greater, tok::greatergreater,
00639                 StopAtSemi | StopBeforeMatch);
00640     }
00641   }
00642   
00643   return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
00644                                                 ParamList, EllipsisLoc, 
00645                                                 ParamName, NameLoc, Depth, 
00646                                                 Position, EqualLoc, DefaultArg);
00647 }
00648 
00649 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
00650 /// template parameters (e.g., in "template<int Size> class array;").
00651 ///
00652 ///       template-parameter:
00653 ///         ...
00654 ///         parameter-declaration
00655 Decl *
00656 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
00657   // Parse the declaration-specifiers (i.e., the type).
00658   // FIXME: The type should probably be restricted in some way... Not all
00659   // declarators (parts of declarators?) are accepted for parameters.
00660   DeclSpec DS(AttrFactory);
00661   ParseDeclarationSpecifiers(DS);
00662 
00663   // Parse this as a typename.
00664   Declarator ParamDecl(DS, Declarator::TemplateParamContext);
00665   ParseDeclarator(ParamDecl);
00666   if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
00667     Diag(Tok.getLocation(), diag::err_expected_template_parameter);
00668     return nullptr;
00669   }
00670 
00671   // Recover from misplaced ellipsis.
00672   SourceLocation EllipsisLoc;
00673   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
00674     DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
00675 
00676   // If there is a default value, parse it.
00677   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
00678   // we introduce the template parameter into the local scope.
00679   SourceLocation EqualLoc;
00680   ExprResult DefaultArg;
00681   if (TryConsumeToken(tok::equal, EqualLoc)) {
00682     // C++ [temp.param]p15:
00683     //   When parsing a default template-argument for a non-type
00684     //   template-parameter, the first non-nested > is taken as the
00685     //   end of the template-parameter-list rather than a greater-than
00686     //   operator.
00687     GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
00688     EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
00689 
00690     DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
00691     if (DefaultArg.isInvalid())
00692       SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
00693   }
00694 
00695   // Create the parameter.
00696   return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl, 
00697                                                Depth, Position, EqualLoc, 
00698                                                DefaultArg.get());
00699 }
00700 
00701 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
00702                                        SourceLocation CorrectLoc,
00703                                        bool AlreadyHasEllipsis,
00704                                        bool IdentifierHasName) {
00705   FixItHint Insertion;
00706   if (!AlreadyHasEllipsis)
00707     Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
00708   Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
00709       << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
00710       << !IdentifierHasName;
00711 }
00712 
00713 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
00714                                                    Declarator &D) {
00715   assert(EllipsisLoc.isValid());
00716   bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
00717   if (!AlreadyHasEllipsis)
00718     D.setEllipsisLoc(EllipsisLoc);
00719   DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
00720                             AlreadyHasEllipsis, D.hasName());
00721 }
00722 
00723 /// \brief Parses a '>' at the end of a template list.
00724 ///
00725 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
00726 /// to determine if these tokens were supposed to be a '>' followed by
00727 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
00728 ///
00729 /// \param RAngleLoc the location of the consumed '>'.
00730 ///
00731 /// \param ConsumeLastToken if true, the '>' is not consumed.
00732 ///
00733 /// \returns true, if current token does not start with '>', false otherwise.
00734 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
00735                                             bool ConsumeLastToken) {
00736   // What will be left once we've consumed the '>'.
00737   tok::TokenKind RemainingToken;
00738   const char *ReplacementStr = "> >";
00739 
00740   switch (Tok.getKind()) {
00741   default:
00742     Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
00743     return true;
00744 
00745   case tok::greater:
00746     // Determine the location of the '>' token. Only consume this token
00747     // if the caller asked us to.
00748     RAngleLoc = Tok.getLocation();
00749     if (ConsumeLastToken)
00750       ConsumeToken();
00751     return false;
00752 
00753   case tok::greatergreater:
00754     RemainingToken = tok::greater;
00755     break;
00756 
00757   case tok::greatergreatergreater:
00758     RemainingToken = tok::greatergreater;
00759     break;
00760 
00761   case tok::greaterequal:
00762     RemainingToken = tok::equal;
00763     ReplacementStr = "> =";
00764     break;
00765 
00766   case tok::greatergreaterequal:
00767     RemainingToken = tok::greaterequal;
00768     break;
00769   }
00770 
00771   // This template-id is terminated by a token which starts with a '>'. Outside
00772   // C++11, this is now error recovery, and in C++11, this is error recovery if
00773   // the token isn't '>>' or '>>>'.
00774   // '>>>' is for CUDA, where this sequence of characters is parsed into
00775   // tok::greatergreatergreater, rather than two separate tokens.
00776 
00777   RAngleLoc = Tok.getLocation();
00778 
00779   // The source range of the '>>' or '>=' at the start of the token.
00780   CharSourceRange ReplacementRange =
00781       CharSourceRange::getCharRange(RAngleLoc,
00782           Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
00783                                          getLangOpts()));
00784 
00785   // A hint to put a space between the '>>'s. In order to make the hint as
00786   // clear as possible, we include the characters either side of the space in
00787   // the replacement, rather than just inserting a space at SecondCharLoc.
00788   FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
00789                                                  ReplacementStr);
00790 
00791   // A hint to put another space after the token, if it would otherwise be
00792   // lexed differently.
00793   FixItHint Hint2;
00794   Token Next = NextToken();
00795   if ((RemainingToken == tok::greater ||
00796        RemainingToken == tok::greatergreater) &&
00797       (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
00798        Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
00799        Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
00800        Next.is(tok::equalequal)) &&
00801       areTokensAdjacent(Tok, Next))
00802     Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
00803 
00804   unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
00805   if (getLangOpts().CPlusPlus11 &&
00806       (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
00807     DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
00808   else if (Tok.is(tok::greaterequal))
00809     DiagId = diag::err_right_angle_bracket_equal_needs_space;
00810   Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
00811 
00812   // Strip the initial '>' from the token.
00813   if (RemainingToken == tok::equal && Next.is(tok::equal) &&
00814       areTokensAdjacent(Tok, Next)) {
00815     // Join two adjacent '=' tokens into one, for cases like:
00816     //   void (*p)() = f<int>;
00817     //   return f<int>==p;
00818     ConsumeToken();
00819     Tok.setKind(tok::equalequal);
00820     Tok.setLength(Tok.getLength() + 1);
00821   } else {
00822     Tok.setKind(RemainingToken);
00823     Tok.setLength(Tok.getLength() - 1);
00824   }
00825   Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
00826                                                  PP.getSourceManager(),
00827                                                  getLangOpts()));
00828 
00829   if (!ConsumeLastToken) {
00830     // Since we're not supposed to consume the '>' token, we need to push
00831     // this token and revert the current token back to the '>'.
00832     PP.EnterToken(Tok);
00833     Tok.setKind(tok::greater);
00834     Tok.setLength(1);
00835     Tok.setLocation(RAngleLoc);
00836   }
00837   return false;
00838 }
00839 
00840 
00841 /// \brief Parses a template-id that after the template name has
00842 /// already been parsed.
00843 ///
00844 /// This routine takes care of parsing the enclosed template argument
00845 /// list ('<' template-parameter-list [opt] '>') and placing the
00846 /// results into a form that can be transferred to semantic analysis.
00847 ///
00848 /// \param Template the template declaration produced by isTemplateName
00849 ///
00850 /// \param TemplateNameLoc the source location of the template name
00851 ///
00852 /// \param SS if non-NULL, the nested-name-specifier preceding the
00853 /// template name.
00854 ///
00855 /// \param ConsumeLastToken if true, then we will consume the last
00856 /// token that forms the template-id. Otherwise, we will leave the
00857 /// last token in the stream (e.g., so that it can be replaced with an
00858 /// annotation token).
00859 bool
00860 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
00861                                          SourceLocation TemplateNameLoc,
00862                                          const CXXScopeSpec &SS,
00863                                          bool ConsumeLastToken,
00864                                          SourceLocation &LAngleLoc,
00865                                          TemplateArgList &TemplateArgs,
00866                                          SourceLocation &RAngleLoc) {
00867   assert(Tok.is(tok::less) && "Must have already parsed the template-name");
00868 
00869   // Consume the '<'.
00870   LAngleLoc = ConsumeToken();
00871 
00872   // Parse the optional template-argument-list.
00873   bool Invalid = false;
00874   {
00875     GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
00876     if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
00877       Invalid = ParseTemplateArgumentList(TemplateArgs);
00878 
00879     if (Invalid) {
00880       // Try to find the closing '>'.
00881       if (ConsumeLastToken)
00882         SkipUntil(tok::greater, StopAtSemi);
00883       else
00884         SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
00885       return true;
00886     }
00887   }
00888 
00889   return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
00890 }
00891 
00892 /// \brief Replace the tokens that form a simple-template-id with an
00893 /// annotation token containing the complete template-id.
00894 ///
00895 /// The first token in the stream must be the name of a template that
00896 /// is followed by a '<'. This routine will parse the complete
00897 /// simple-template-id and replace the tokens with a single annotation
00898 /// token with one of two different kinds: if the template-id names a
00899 /// type (and \p AllowTypeAnnotation is true), the annotation token is
00900 /// a type annotation that includes the optional nested-name-specifier
00901 /// (\p SS). Otherwise, the annotation token is a template-id
00902 /// annotation that does not include the optional
00903 /// nested-name-specifier.
00904 ///
00905 /// \param Template  the declaration of the template named by the first
00906 /// token (an identifier), as returned from \c Action::isTemplateName().
00907 ///
00908 /// \param TNK the kind of template that \p Template
00909 /// refers to, as returned from \c Action::isTemplateName().
00910 ///
00911 /// \param SS if non-NULL, the nested-name-specifier that precedes
00912 /// this template name.
00913 ///
00914 /// \param TemplateKWLoc if valid, specifies that this template-id
00915 /// annotation was preceded by the 'template' keyword and gives the
00916 /// location of that keyword. If invalid (the default), then this
00917 /// template-id was not preceded by a 'template' keyword.
00918 ///
00919 /// \param AllowTypeAnnotation if true (the default), then a
00920 /// simple-template-id that refers to a class template, template
00921 /// template parameter, or other template that produces a type will be
00922 /// replaced with a type annotation token. Otherwise, the
00923 /// simple-template-id is always replaced with a template-id
00924 /// annotation token.
00925 ///
00926 /// If an unrecoverable parse error occurs and no annotation token can be
00927 /// formed, this function returns true.
00928 ///
00929 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
00930                                      CXXScopeSpec &SS,
00931                                      SourceLocation TemplateKWLoc,
00932                                      UnqualifiedId &TemplateName,
00933                                      bool AllowTypeAnnotation) {
00934   assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
00935   assert(Template && Tok.is(tok::less) &&
00936          "Parser isn't at the beginning of a template-id");
00937 
00938   // Consume the template-name.
00939   SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
00940 
00941   // Parse the enclosed template argument list.
00942   SourceLocation LAngleLoc, RAngleLoc;
00943   TemplateArgList TemplateArgs;
00944   bool Invalid = ParseTemplateIdAfterTemplateName(Template, 
00945                                                   TemplateNameLoc,
00946                                                   SS, false, LAngleLoc,
00947                                                   TemplateArgs,
00948                                                   RAngleLoc);
00949 
00950   if (Invalid) {
00951     // If we failed to parse the template ID but skipped ahead to a >, we're not
00952     // going to be able to form a token annotation.  Eat the '>' if present.
00953     TryConsumeToken(tok::greater);
00954     return true;
00955   }
00956 
00957   ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
00958 
00959   // Build the annotation token.
00960   if (TNK == TNK_Type_template && AllowTypeAnnotation) {
00961     TypeResult Type
00962       = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
00963                                     Template, TemplateNameLoc,
00964                                     LAngleLoc, TemplateArgsPtr, RAngleLoc);
00965     if (Type.isInvalid()) {
00966       // If we failed to parse the template ID but skipped ahead to a >, we're not
00967       // going to be able to form a token annotation.  Eat the '>' if present.
00968       TryConsumeToken(tok::greater);
00969       return true;
00970     }
00971 
00972     Tok.setKind(tok::annot_typename);
00973     setTypeAnnotation(Tok, Type.get());
00974     if (SS.isNotEmpty())
00975       Tok.setLocation(SS.getBeginLoc());
00976     else if (TemplateKWLoc.isValid())
00977       Tok.setLocation(TemplateKWLoc);
00978     else
00979       Tok.setLocation(TemplateNameLoc);
00980   } else {
00981     // Build a template-id annotation token that can be processed
00982     // later.
00983     Tok.setKind(tok::annot_template_id);
00984     TemplateIdAnnotation *TemplateId
00985       = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
00986     TemplateId->TemplateNameLoc = TemplateNameLoc;
00987     if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
00988       TemplateId->Name = TemplateName.Identifier;
00989       TemplateId->Operator = OO_None;
00990     } else {
00991       TemplateId->Name = nullptr;
00992       TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
00993     }
00994     TemplateId->SS = SS;
00995     TemplateId->TemplateKWLoc = TemplateKWLoc;
00996     TemplateId->Template = Template;
00997     TemplateId->Kind = TNK;
00998     TemplateId->LAngleLoc = LAngleLoc;
00999     TemplateId->RAngleLoc = RAngleLoc;
01000     ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
01001     for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
01002       Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
01003     Tok.setAnnotationValue(TemplateId);
01004     if (TemplateKWLoc.isValid())
01005       Tok.setLocation(TemplateKWLoc);
01006     else
01007       Tok.setLocation(TemplateNameLoc);
01008   }
01009 
01010   // Common fields for the annotation token
01011   Tok.setAnnotationEndLoc(RAngleLoc);
01012 
01013   // In case the tokens were cached, have Preprocessor replace them with the
01014   // annotation token.
01015   PP.AnnotateCachedTokens(Tok);
01016   return false;
01017 }
01018 
01019 /// \brief Replaces a template-id annotation token with a type
01020 /// annotation token.
01021 ///
01022 /// If there was a failure when forming the type from the template-id,
01023 /// a type annotation token will still be created, but will have a
01024 /// NULL type pointer to signify an error.
01025 void Parser::AnnotateTemplateIdTokenAsType() {
01026   assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
01027 
01028   TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
01029   assert((TemplateId->Kind == TNK_Type_template ||
01030           TemplateId->Kind == TNK_Dependent_template_name) &&
01031          "Only works for type and dependent templates");
01032 
01033   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
01034                                      TemplateId->NumArgs);
01035 
01036   TypeResult Type
01037     = Actions.ActOnTemplateIdType(TemplateId->SS,
01038                                   TemplateId->TemplateKWLoc,
01039                                   TemplateId->Template,
01040                                   TemplateId->TemplateNameLoc,
01041                                   TemplateId->LAngleLoc,
01042                                   TemplateArgsPtr,
01043                                   TemplateId->RAngleLoc);
01044   // Create the new "type" annotation token.
01045   Tok.setKind(tok::annot_typename);
01046   setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
01047   if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
01048     Tok.setLocation(TemplateId->SS.getBeginLoc());
01049   // End location stays the same
01050 
01051   // Replace the template-id annotation token, and possible the scope-specifier
01052   // that precedes it, with the typename annotation token.
01053   PP.AnnotateCachedTokens(Tok);
01054 }
01055 
01056 /// \brief Determine whether the given token can end a template argument.
01057 static bool isEndOfTemplateArgument(Token Tok) {
01058   return Tok.is(tok::comma) || Tok.is(tok::greater) || 
01059          Tok.is(tok::greatergreater);
01060 }
01061 
01062 /// \brief Parse a C++ template template argument.
01063 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
01064   if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
01065       !Tok.is(tok::annot_cxxscope))
01066     return ParsedTemplateArgument();
01067 
01068   // C++0x [temp.arg.template]p1:
01069   //   A template-argument for a template template-parameter shall be the name
01070   //   of a class template or an alias template, expressed as id-expression.
01071   //   
01072   // We parse an id-expression that refers to a class template or alias
01073   // template. The grammar we parse is:
01074   //
01075   //   nested-name-specifier[opt] template[opt] identifier ...[opt]
01076   //
01077   // followed by a token that terminates a template argument, such as ',', 
01078   // '>', or (in some cases) '>>'.
01079   CXXScopeSpec SS; // nested-name-specifier, if present
01080   ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
01081                                  /*EnteringContext=*/false);
01082   
01083   ParsedTemplateArgument Result;
01084   SourceLocation EllipsisLoc;
01085   if (SS.isSet() && Tok.is(tok::kw_template)) {
01086     // Parse the optional 'template' keyword following the 
01087     // nested-name-specifier.
01088     SourceLocation TemplateKWLoc = ConsumeToken();
01089     
01090     if (Tok.is(tok::identifier)) {
01091       // We appear to have a dependent template name.
01092       UnqualifiedId Name;
01093       Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
01094       ConsumeToken(); // the identifier
01095 
01096       TryConsumeToken(tok::ellipsis, EllipsisLoc);
01097 
01098       // If the next token signals the end of a template argument,
01099       // then we have a dependent template name that could be a template
01100       // template argument.
01101       TemplateTy Template;
01102       if (isEndOfTemplateArgument(Tok) &&
01103           Actions.ActOnDependentTemplateName(getCurScope(),
01104                                              SS, TemplateKWLoc, Name,
01105                                              /*ObjectType=*/ ParsedType(),
01106                                              /*EnteringContext=*/false,
01107                                              Template))
01108         Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
01109     }
01110   } else if (Tok.is(tok::identifier)) {
01111     // We may have a (non-dependent) template name.
01112     TemplateTy Template;
01113     UnqualifiedId Name;
01114     Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
01115     ConsumeToken(); // the identifier
01116 
01117     TryConsumeToken(tok::ellipsis, EllipsisLoc);
01118 
01119     if (isEndOfTemplateArgument(Tok)) {
01120       bool MemberOfUnknownSpecialization;
01121       TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
01122                                                /*hasTemplateKeyword=*/false,
01123                                                     Name,
01124                                                /*ObjectType=*/ ParsedType(), 
01125                                                     /*EnteringContext=*/false, 
01126                                                     Template,
01127                                                 MemberOfUnknownSpecialization);
01128       if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
01129         // We have an id-expression that refers to a class template or
01130         // (C++0x) alias template. 
01131         Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
01132       }
01133     }
01134   }
01135   
01136   // If this is a pack expansion, build it as such.
01137   if (EllipsisLoc.isValid() && !Result.isInvalid())
01138     Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
01139   
01140   return Result;
01141 }
01142 
01143 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
01144 ///
01145 ///       template-argument: [C++ 14.2]
01146 ///         constant-expression
01147 ///         type-id
01148 ///         id-expression
01149 ParsedTemplateArgument Parser::ParseTemplateArgument() {
01150   // C++ [temp.arg]p2:
01151   //   In a template-argument, an ambiguity between a type-id and an
01152   //   expression is resolved to a type-id, regardless of the form of
01153   //   the corresponding template-parameter.
01154   //
01155   // Therefore, we initially try to parse a type-id.  
01156   if (isCXXTypeId(TypeIdAsTemplateArgument)) {
01157     SourceLocation Loc = Tok.getLocation();
01158     TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
01159                                        Declarator::TemplateTypeArgContext);
01160     if (TypeArg.isInvalid())
01161       return ParsedTemplateArgument();
01162     
01163     return ParsedTemplateArgument(ParsedTemplateArgument::Type,
01164                                   TypeArg.get().getAsOpaquePtr(), 
01165                                   Loc);
01166   }
01167   
01168   // Try to parse a template template argument.
01169   {
01170     TentativeParsingAction TPA(*this);
01171 
01172     ParsedTemplateArgument TemplateTemplateArgument
01173       = ParseTemplateTemplateArgument();
01174     if (!TemplateTemplateArgument.isInvalid()) {
01175       TPA.Commit();
01176       return TemplateTemplateArgument;
01177     }
01178     
01179     // Revert this tentative parse to parse a non-type template argument.
01180     TPA.Revert();
01181   }
01182   
01183   // Parse a non-type template argument. 
01184   SourceLocation Loc = Tok.getLocation();
01185   ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
01186   if (ExprArg.isInvalid() || !ExprArg.get())
01187     return ParsedTemplateArgument();
01188 
01189   return ParsedTemplateArgument(ParsedTemplateArgument::NonType, 
01190                                 ExprArg.get(), Loc);
01191 }
01192 
01193 /// \brief Determine whether the current tokens can only be parsed as a 
01194 /// template argument list (starting with the '<') and never as a '<' 
01195 /// expression.
01196 bool Parser::IsTemplateArgumentList(unsigned Skip) {
01197   struct AlwaysRevertAction : TentativeParsingAction {
01198     AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
01199     ~AlwaysRevertAction() { Revert(); }
01200   } Tentative(*this);
01201   
01202   while (Skip) {
01203     ConsumeToken();
01204     --Skip;
01205   }
01206   
01207   // '<'
01208   if (!TryConsumeToken(tok::less))
01209     return false;
01210 
01211   // An empty template argument list.
01212   if (Tok.is(tok::greater))
01213     return true;
01214   
01215   // See whether we have declaration specifiers, which indicate a type.
01216   while (isCXXDeclarationSpecifier() == TPResult::True)
01217     ConsumeToken();
01218   
01219   // If we have a '>' or a ',' then this is a template argument list.
01220   return Tok.is(tok::greater) || Tok.is(tok::comma);
01221 }
01222 
01223 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
01224 /// (C++ [temp.names]). Returns true if there was an error.
01225 ///
01226 ///       template-argument-list: [C++ 14.2]
01227 ///         template-argument
01228 ///         template-argument-list ',' template-argument
01229 bool
01230 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
01231   // Template argument lists are constant-evaluation contexts.
01232   EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
01233   ColonProtectionRAIIObject ColonProtection(*this, false);
01234 
01235   do {
01236     ParsedTemplateArgument Arg = ParseTemplateArgument();
01237     SourceLocation EllipsisLoc;
01238     if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
01239       Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
01240 
01241     if (Arg.isInvalid()) {
01242       SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
01243       return true;
01244     }
01245 
01246     // Save this template argument.
01247     TemplateArgs.push_back(Arg);
01248       
01249     // If the next token is a comma, consume it and keep reading
01250     // arguments.
01251   } while (TryConsumeToken(tok::comma));
01252 
01253   return false;
01254 }
01255 
01256 /// \brief Parse a C++ explicit template instantiation
01257 /// (C++ [temp.explicit]).
01258 ///
01259 ///       explicit-instantiation:
01260 ///         'extern' [opt] 'template' declaration
01261 ///
01262 /// Note that the 'extern' is a GNU extension and C++11 feature.
01263 Decl *Parser::ParseExplicitInstantiation(unsigned Context,
01264                                          SourceLocation ExternLoc,
01265                                          SourceLocation TemplateLoc,
01266                                          SourceLocation &DeclEnd,
01267                                          AccessSpecifier AS) {
01268   // This isn't really required here.
01269   ParsingDeclRAIIObject
01270     ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
01271 
01272   return ParseSingleDeclarationAfterTemplate(Context,
01273                                              ParsedTemplateInfo(ExternLoc,
01274                                                                 TemplateLoc),
01275                                              ParsingTemplateParams,
01276                                              DeclEnd, AS);
01277 }
01278 
01279 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
01280   if (TemplateParams)
01281     return getTemplateParamsRange(TemplateParams->data(),
01282                                   TemplateParams->size());
01283 
01284   SourceRange R(TemplateLoc);
01285   if (ExternLoc.isValid())
01286     R.setBegin(ExternLoc);
01287   return R;
01288 }
01289 
01290 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
01291   ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
01292 }
01293 
01294 /// \brief Late parse a C++ function template in Microsoft mode.
01295 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
01296   if (!LPT.D)
01297      return;
01298 
01299   // Get the FunctionDecl.
01300   FunctionDecl *FunD = LPT.D->getAsFunction();
01301   // Track template parameter depth.
01302   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
01303 
01304   // To restore the context after late parsing.
01305   Sema::ContextRAII GlobalSavedContext(
01306       Actions, Actions.Context.getTranslationUnitDecl());
01307 
01308   SmallVector<ParseScope*, 4> TemplateParamScopeStack;
01309 
01310   // Get the list of DeclContexts to reenter.
01311   SmallVector<DeclContext*, 4> DeclContextsToReenter;
01312   DeclContext *DD = FunD;
01313   while (DD && !DD->isTranslationUnit()) {
01314     DeclContextsToReenter.push_back(DD);
01315     DD = DD->getLexicalParent();
01316   }
01317 
01318   // Reenter template scopes from outermost to innermost.
01319   SmallVectorImpl<DeclContext *>::reverse_iterator II =
01320       DeclContextsToReenter.rbegin();
01321   for (; II != DeclContextsToReenter.rend(); ++II) {
01322     TemplateParamScopeStack.push_back(new ParseScope(this,
01323           Scope::TemplateParamScope));
01324     unsigned NumParamLists =
01325       Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
01326     CurTemplateDepthTracker.addDepth(NumParamLists);
01327     if (*II != FunD) {
01328       TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
01329       Actions.PushDeclContext(Actions.getCurScope(), *II);
01330     }
01331   }
01332 
01333   assert(!LPT.Toks.empty() && "Empty body!");
01334 
01335   // Append the current token at the end of the new token stream so that it
01336   // doesn't get lost.
01337   LPT.Toks.push_back(Tok);
01338   PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
01339 
01340   // Consume the previously pushed token.
01341   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
01342   assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
01343          && "Inline method not starting with '{', ':' or 'try'");
01344 
01345   // Parse the method body. Function body parsing code is similar enough
01346   // to be re-used for method bodies as well.
01347   ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
01348 
01349   // Recreate the containing function DeclContext.
01350   Sema::ContextRAII FunctionSavedContext(Actions,
01351                                          Actions.getContainingDC(FunD));
01352 
01353   Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
01354 
01355   if (Tok.is(tok::kw_try)) {
01356     ParseFunctionTryBlock(LPT.D, FnScope);
01357   } else {
01358     if (Tok.is(tok::colon))
01359       ParseConstructorInitializer(LPT.D);
01360     else
01361       Actions.ActOnDefaultCtorInitializers(LPT.D);
01362 
01363     if (Tok.is(tok::l_brace)) {
01364       assert((!isa<FunctionTemplateDecl>(LPT.D) ||
01365               cast<FunctionTemplateDecl>(LPT.D)
01366                       ->getTemplateParameters()
01367                       ->getDepth() == TemplateParameterDepth - 1) &&
01368              "TemplateParameterDepth should be greater than the depth of "
01369              "current template being instantiated!");
01370       ParseFunctionStatementBody(LPT.D, FnScope);
01371       Actions.UnmarkAsLateParsedTemplate(FunD);
01372     } else
01373       Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
01374   }
01375 
01376   // Exit scopes.
01377   FnScope.Exit();
01378   SmallVectorImpl<ParseScope *>::reverse_iterator I =
01379    TemplateParamScopeStack.rbegin();
01380   for (; I != TemplateParamScopeStack.rend(); ++I)
01381     delete *I;
01382 }
01383 
01384 /// \brief Lex a delayed template function for late parsing.
01385 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
01386   tok::TokenKind kind = Tok.getKind();
01387   if (!ConsumeAndStoreFunctionPrologue(Toks)) {
01388     // Consume everything up to (and including) the matching right brace.
01389     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
01390   }
01391 
01392   // If we're in a function-try-block, we need to store all the catch blocks.
01393   if (kind == tok::kw_try) {
01394     while (Tok.is(tok::kw_catch)) {
01395       ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
01396       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
01397     }
01398   }
01399 }