clang API Documentation

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