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