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