clang API Documentation

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