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