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