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