clang API Documentation

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