Home | History | Annotate | Download | only in Parse
      1 //===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file implements parsing of C++ templates.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Parse/Parser.h"
     15 #include "clang/Parse/ParseDiagnostic.h"
     16 #include "clang/Sema/DeclSpec.h"
     17 #include "clang/Sema/ParsedTemplate.h"
     18 #include "clang/Sema/Scope.h"
     19 #include "RAIIObjectsForParser.h"
     20 #include "clang/AST/DeclTemplate.h"
     21 #include "clang/AST/ASTConsumer.h"
     22 using namespace clang;
     23 
     24 /// \brief Parse a template declaration, explicit instantiation, or
     25 /// explicit specialization.
     26 Decl *
     27 Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
     28                                              SourceLocation &DeclEnd,
     29                                              AccessSpecifier AS,
     30                                              AttributeList *AccessAttrs) {
     31   ObjCDeclContextSwitch ObjCDC(*this);
     32 
     33   if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
     34     return ParseExplicitInstantiation(Context,
     35                                       SourceLocation(), ConsumeToken(),
     36                                       DeclEnd, AS);
     37   }
     38   return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
     39                                                   AccessAttrs);
     40 }
     41 
     42 /// \brief RAII class that manages the template parameter depth.
     43 namespace {
     44   class TemplateParameterDepthCounter {
     45     unsigned &Depth;
     46     unsigned AddedLevels;
     47 
     48   public:
     49     explicit TemplateParameterDepthCounter(unsigned &Depth)
     50       : Depth(Depth), AddedLevels(0) { }
     51 
     52     ~TemplateParameterDepthCounter() {
     53       Depth -= AddedLevels;
     54     }
     55 
     56     void operator++() {
     57       ++Depth;
     58       ++AddedLevels;
     59     }
     60 
     61     operator unsigned() const { return Depth; }
     62   };
     63 }
     64 
     65 /// \brief Parse a template declaration or an explicit specialization.
     66 ///
     67 /// Template declarations include one or more template parameter lists
     68 /// and either the function or class template declaration. Explicit
     69 /// specializations contain one or more 'template < >' prefixes
     70 /// followed by a (possibly templated) declaration. Since the
     71 /// syntactic form of both features is nearly identical, we parse all
     72 /// of the template headers together and let semantic analysis sort
     73 /// the declarations from the explicit specializations.
     74 ///
     75 ///       template-declaration: [C++ temp]
     76 ///         'export'[opt] 'template' '<' template-parameter-list '>' declaration
     77 ///
     78 ///       explicit-specialization: [ C++ temp.expl.spec]
     79 ///         'template' '<' '>' declaration
     80 Decl *
     81 Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
     82                                                  SourceLocation &DeclEnd,
     83                                                  AccessSpecifier AS,
     84                                                  AttributeList *AccessAttrs) {
     85   assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
     86          "Token does not start a template declaration.");
     87 
     88   // Enter template-parameter scope.
     89   ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
     90 
     91   // Tell the action that names should be checked in the context of
     92   // the declaration to come.
     93   ParsingDeclRAIIObject
     94     ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
     95 
     96   // Parse multiple levels of template headers within this template
     97   // parameter scope, e.g.,
     98   //
     99   //   template<typename T>
    100   //     template<typename U>
    101   //       class A<T>::B { ... };
    102   //
    103   // We parse multiple levels non-recursively so that we can build a
    104   // single data structure containing all of the template parameter
    105   // lists to easily differentiate between the case above and:
    106   //
    107   //   template<typename T>
    108   //   class A {
    109   //     template<typename U> class B;
    110   //   };
    111   //
    112   // In the first case, the action for declaring A<T>::B receives
    113   // both template parameter lists. In the second case, the action for
    114   // defining A<T>::B receives just the inner template parameter list
    115   // (and retrieves the outer template parameter list from its
    116   // context).
    117   bool isSpecialization = true;
    118   bool LastParamListWasEmpty = false;
    119   TemplateParameterLists ParamLists;
    120   TemplateParameterDepthCounter Depth(TemplateParameterDepth);
    121   do {
    122     // Consume the 'export', if any.
    123     SourceLocation ExportLoc;
    124     if (Tok.is(tok::kw_export)) {
    125       ExportLoc = ConsumeToken();
    126     }
    127 
    128     // Consume the 'template', which should be here.
    129     SourceLocation TemplateLoc;
    130     if (Tok.is(tok::kw_template)) {
    131       TemplateLoc = ConsumeToken();
    132     } else {
    133       Diag(Tok.getLocation(), diag::err_expected_template);
    134       return 0;
    135     }
    136 
    137     // Parse the '<' template-parameter-list '>'
    138     SourceLocation LAngleLoc, RAngleLoc;
    139     SmallVector<Decl*, 4> TemplateParams;
    140     if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
    141                                 RAngleLoc)) {
    142       // Skip until the semi-colon or a }.
    143       SkipUntil(tok::r_brace, true, true);
    144       if (Tok.is(tok::semi))
    145         ConsumeToken();
    146       return 0;
    147     }
    148 
    149     ParamLists.push_back(
    150       Actions.ActOnTemplateParameterList(Depth, ExportLoc,
    151                                          TemplateLoc, LAngleLoc,
    152                                          TemplateParams.data(),
    153                                          TemplateParams.size(), RAngleLoc));
    154 
    155     if (!TemplateParams.empty()) {
    156       isSpecialization = false;
    157       ++Depth;
    158     } else {
    159       LastParamListWasEmpty = true;
    160     }
    161   } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
    162 
    163   // Parse the actual template declaration.
    164   return ParseSingleDeclarationAfterTemplate(Context,
    165                                              ParsedTemplateInfo(&ParamLists,
    166                                                              isSpecialization,
    167                                                          LastParamListWasEmpty),
    168                                              ParsingTemplateParams,
    169                                              DeclEnd, AS, AccessAttrs);
    170 }
    171 
    172 /// \brief Parse a single declaration that declares a template,
    173 /// template specialization, or explicit instantiation of a template.
    174 ///
    175 /// \param TemplateParams if non-NULL, the template parameter lists
    176 /// that preceded this declaration. In this case, the declaration is a
    177 /// template declaration, out-of-line definition of a template, or an
    178 /// explicit template specialization. When NULL, the declaration is an
    179 /// explicit template instantiation.
    180 ///
    181 /// \param TemplateLoc when TemplateParams is NULL, the location of
    182 /// the 'template' keyword that indicates that we have an explicit
    183 /// template instantiation.
    184 ///
    185 /// \param DeclEnd will receive the source location of the last token
    186 /// within this declaration.
    187 ///
    188 /// \param AS the access specifier associated with this
    189 /// declaration. Will be AS_none for namespace-scope declarations.
    190 ///
    191 /// \returns the new declaration.
    192 Decl *
    193 Parser::ParseSingleDeclarationAfterTemplate(
    194                                        unsigned Context,
    195                                        const ParsedTemplateInfo &TemplateInfo,
    196                                        ParsingDeclRAIIObject &DiagsFromTParams,
    197                                        SourceLocation &DeclEnd,
    198                                        AccessSpecifier AS,
    199                                        AttributeList *AccessAttrs) {
    200   assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
    201          "Template information required");
    202 
    203   if (Context == Declarator::MemberContext) {
    204     // We are parsing a member template.
    205     ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
    206                                    &DiagsFromTParams);
    207     return 0;
    208   }
    209 
    210   ParsedAttributesWithRange prefixAttrs(AttrFactory);
    211   MaybeParseCXX0XAttributes(prefixAttrs);
    212 
    213   if (Tok.is(tok::kw_using))
    214     return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
    215                                             prefixAttrs);
    216 
    217   // Parse the declaration specifiers, stealing any diagnostics from
    218   // the template parameters.
    219   ParsingDeclSpec DS(*this, &DiagsFromTParams);
    220 
    221   // Move the attributes from the prefix into the DS.
    222   if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
    223     ProhibitAttributes(prefixAttrs);
    224   else
    225     DS.takeAttributesFrom(prefixAttrs);
    226 
    227   ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
    228                              getDeclSpecContextFromDeclaratorContext(Context));
    229 
    230   if (Tok.is(tok::semi)) {
    231     DeclEnd = ConsumeToken();
    232     Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
    233     DS.complete(Decl);
    234     return Decl;
    235   }
    236 
    237   // Parse the declarator.
    238   ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
    239   ParseDeclarator(DeclaratorInfo);
    240   // Error parsing the declarator?
    241   if (!DeclaratorInfo.hasName()) {
    242     // If so, skip until the semi-colon or a }.
    243     SkipUntil(tok::r_brace, true, true);
    244     if (Tok.is(tok::semi))
    245       ConsumeToken();
    246     return 0;
    247   }
    248 
    249   LateParsedAttrList LateParsedAttrs;
    250   if (DeclaratorInfo.isFunctionDeclarator())
    251     MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
    252 
    253   // If we have a declaration or declarator list, handle it.
    254   if (isDeclarationAfterDeclarator()) {
    255     // Parse this declaration.
    256     Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
    257                                                      TemplateInfo);
    258 
    259     if (Tok.is(tok::comma)) {
    260       Diag(Tok, diag::err_multiple_template_declarators)
    261         << (int)TemplateInfo.Kind;
    262       SkipUntil(tok::semi, true, false);
    263       return ThisDecl;
    264     }
    265 
    266     // Eat the semi colon after the declaration.
    267     ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
    268     if (LateParsedAttrs.size() > 0)
    269       ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
    270     DeclaratorInfo.complete(ThisDecl);
    271     return ThisDecl;
    272   }
    273 
    274   if (DeclaratorInfo.isFunctionDeclarator() &&
    275       isStartOfFunctionDefinition(DeclaratorInfo)) {
    276     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
    277       // Recover by ignoring the 'typedef'. This was probably supposed to be
    278       // the 'typename' keyword, which we should have already suggested adding
    279       // if it's appropriate.
    280       Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
    281         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
    282       DS.ClearStorageClassSpecs();
    283     }
    284     return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
    285                                    &LateParsedAttrs);
    286   }
    287 
    288   if (DeclaratorInfo.isFunctionDeclarator())
    289     Diag(Tok, diag::err_expected_fn_body);
    290   else
    291     Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
    292   SkipUntil(tok::semi);
    293   return 0;
    294 }
    295 
    296 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
    297 /// angle brackets. Depth is the depth of this template-parameter-list, which
    298 /// is the number of template headers directly enclosing this template header.
    299 /// TemplateParams is the current list of template parameters we're building.
    300 /// The template parameter we parse will be added to this list. LAngleLoc and
    301 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
    302 /// that enclose this template parameter list.
    303 ///
    304 /// \returns true if an error occurred, false otherwise.
    305 bool Parser::ParseTemplateParameters(unsigned Depth,
    306                                SmallVectorImpl<Decl*> &TemplateParams,
    307                                      SourceLocation &LAngleLoc,
    308                                      SourceLocation &RAngleLoc) {
    309   // Get the template parameter list.
    310   if (!Tok.is(tok::less)) {
    311     Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
    312     return true;
    313   }
    314   LAngleLoc = ConsumeToken();
    315 
    316   // Try to parse the template parameter list.
    317   bool Failed = false;
    318   if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
    319     Failed = ParseTemplateParameterList(Depth, TemplateParams);
    320 
    321   if (Tok.is(tok::greatergreater)) {
    322     // No diagnostic required here: a template-parameter-list can only be
    323     // followed by a declaration or, for a template template parameter, the
    324     // 'class' keyword. Therefore, the second '>' will be diagnosed later.
    325     // This matters for elegant diagnosis of:
    326     //   template<template<typename>> struct S;
    327     Tok.setKind(tok::greater);
    328     RAngleLoc = Tok.getLocation();
    329     Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
    330   } else if (Tok.is(tok::greater))
    331     RAngleLoc = ConsumeToken();
    332   else if (Failed) {
    333     Diag(Tok.getLocation(), diag::err_expected_greater);
    334     return true;
    335   }
    336   return false;
    337 }
    338 
    339 /// ParseTemplateParameterList - Parse a template parameter list. If
    340 /// the parsing fails badly (i.e., closing bracket was left out), this
    341 /// will try to put the token stream in a reasonable position (closing
    342 /// a statement, etc.) and return false.
    343 ///
    344 ///       template-parameter-list:    [C++ temp]
    345 ///         template-parameter
    346 ///         template-parameter-list ',' template-parameter
    347 bool
    348 Parser::ParseTemplateParameterList(unsigned Depth,
    349                              SmallVectorImpl<Decl*> &TemplateParams) {
    350   while (1) {
    351     if (Decl *TmpParam
    352           = ParseTemplateParameter(Depth, TemplateParams.size())) {
    353       TemplateParams.push_back(TmpParam);
    354     } else {
    355       // If we failed to parse a template parameter, skip until we find
    356       // a comma or closing brace.
    357       SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
    358     }
    359 
    360     // Did we find a comma or the end of the template parmeter list?
    361     if (Tok.is(tok::comma)) {
    362       ConsumeToken();
    363     } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
    364       // Don't consume this... that's done by template parser.
    365       break;
    366     } else {
    367       // Somebody probably forgot to close the template. Skip ahead and
    368       // try to get out of the expression. This error is currently
    369       // subsumed by whatever goes on in ParseTemplateParameter.
    370       Diag(Tok.getLocation(), diag::err_expected_comma_greater);
    371       SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
    372       return false;
    373     }
    374   }
    375   return true;
    376 }
    377 
    378 /// \brief Determine whether the parser is at the start of a template
    379 /// type parameter.
    380 bool Parser::isStartOfTemplateTypeParameter() {
    381   if (Tok.is(tok::kw_class)) {
    382     // "class" may be the start of an elaborated-type-specifier or a
    383     // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
    384     switch (NextToken().getKind()) {
    385     case tok::equal:
    386     case tok::comma:
    387     case tok::greater:
    388     case tok::greatergreater:
    389     case tok::ellipsis:
    390       return true;
    391 
    392     case tok::identifier:
    393       // This may be either a type-parameter or an elaborated-type-specifier.
    394       // We have to look further.
    395       break;
    396 
    397     default:
    398       return false;
    399     }
    400 
    401     switch (GetLookAheadToken(2).getKind()) {
    402     case tok::equal:
    403     case tok::comma:
    404     case tok::greater:
    405     case tok::greatergreater:
    406       return true;
    407 
    408     default:
    409       return false;
    410     }
    411   }
    412 
    413   if (Tok.isNot(tok::kw_typename))
    414     return false;
    415 
    416   // C++ [temp.param]p2:
    417   //   There is no semantic difference between class and typename in a
    418   //   template-parameter. typename followed by an unqualified-id
    419   //   names a template type parameter. typename followed by a
    420   //   qualified-id denotes the type in a non-type
    421   //   parameter-declaration.
    422   Token Next = NextToken();
    423 
    424   // If we have an identifier, skip over it.
    425   if (Next.getKind() == tok::identifier)
    426     Next = GetLookAheadToken(2);
    427 
    428   switch (Next.getKind()) {
    429   case tok::equal:
    430   case tok::comma:
    431   case tok::greater:
    432   case tok::greatergreater:
    433   case tok::ellipsis:
    434     return true;
    435 
    436   default:
    437     return false;
    438   }
    439 }
    440 
    441 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
    442 ///
    443 ///       template-parameter: [C++ temp.param]
    444 ///         type-parameter
    445 ///         parameter-declaration
    446 ///
    447 ///       type-parameter: (see below)
    448 ///         'class' ...[opt] identifier[opt]
    449 ///         'class' identifier[opt] '=' type-id
    450 ///         'typename' ...[opt] identifier[opt]
    451 ///         'typename' identifier[opt] '=' type-id
    452 ///         'template' '<' template-parameter-list '>'
    453 ///               'class' ...[opt] identifier[opt]
    454 ///         'template' '<' template-parameter-list '>' 'class' identifier[opt]
    455 ///               = id-expression
    456 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
    457   if (isStartOfTemplateTypeParameter())
    458     return ParseTypeParameter(Depth, Position);
    459 
    460   if (Tok.is(tok::kw_template))
    461     return ParseTemplateTemplateParameter(Depth, Position);
    462 
    463   // If it's none of the above, then it must be a parameter declaration.
    464   // NOTE: This will pick up errors in the closure of the template parameter
    465   // list (e.g., template < ; Check here to implement >> style closures.
    466   return ParseNonTypeTemplateParameter(Depth, Position);
    467 }
    468 
    469 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
    470 /// Other kinds of template parameters are parsed in
    471 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
    472 ///
    473 ///       type-parameter:     [C++ temp.param]
    474 ///         'class' ...[opt][C++0x] identifier[opt]
    475 ///         'class' identifier[opt] '=' type-id
    476 ///         'typename' ...[opt][C++0x] identifier[opt]
    477 ///         'typename' identifier[opt] '=' type-id
    478 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
    479   assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
    480          "A type-parameter starts with 'class' or 'typename'");
    481 
    482   // Consume the 'class' or 'typename' keyword.
    483   bool TypenameKeyword = Tok.is(tok::kw_typename);
    484   SourceLocation KeyLoc = ConsumeToken();
    485 
    486   // Grab the ellipsis (if given).
    487   bool Ellipsis = false;
    488   SourceLocation EllipsisLoc;
    489   if (Tok.is(tok::ellipsis)) {
    490     Ellipsis = true;
    491     EllipsisLoc = ConsumeToken();
    492 
    493     Diag(EllipsisLoc,
    494          getLangOpts().CPlusPlus0x
    495            ? diag::warn_cxx98_compat_variadic_templates
    496            : diag::ext_variadic_templates);
    497   }
    498 
    499   // Grab the template parameter name (if given)
    500   SourceLocation NameLoc;
    501   IdentifierInfo* ParamName = 0;
    502   if (Tok.is(tok::identifier)) {
    503     ParamName = Tok.getIdentifierInfo();
    504     NameLoc = ConsumeToken();
    505   } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
    506              Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
    507     // Unnamed template parameter. Don't have to do anything here, just
    508     // don't consume this token.
    509   } else {
    510     Diag(Tok.getLocation(), diag::err_expected_ident);
    511     return 0;
    512   }
    513 
    514   // Grab a default argument (if available).
    515   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
    516   // we introduce the type parameter into the local scope.
    517   SourceLocation EqualLoc;
    518   ParsedType DefaultArg;
    519   if (Tok.is(tok::equal)) {
    520     EqualLoc = ConsumeToken();
    521     DefaultArg = ParseTypeName(/*Range=*/0,
    522                                Declarator::TemplateTypeArgContext).get();
    523   }
    524 
    525   return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
    526                                     EllipsisLoc, KeyLoc, ParamName, NameLoc,
    527                                     Depth, Position, EqualLoc, DefaultArg);
    528 }
    529 
    530 /// ParseTemplateTemplateParameter - Handle the parsing of template
    531 /// template parameters.
    532 ///
    533 ///       type-parameter:    [C++ temp.param]
    534 ///         'template' '<' template-parameter-list '>' 'class'
    535 ///                  ...[opt] identifier[opt]
    536 ///         'template' '<' template-parameter-list '>' 'class' identifier[opt]
    537 ///                  = id-expression
    538 Decl *
    539 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
    540   assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
    541 
    542   // Handle the template <...> part.
    543   SourceLocation TemplateLoc = ConsumeToken();
    544   SmallVector<Decl*,8> TemplateParams;
    545   SourceLocation LAngleLoc, RAngleLoc;
    546   {
    547     ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
    548     if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
    549                                RAngleLoc)) {
    550       return 0;
    551     }
    552   }
    553 
    554   // Generate a meaningful error if the user forgot to put class before the
    555   // identifier, comma, or greater. Provide a fixit if the identifier, comma,
    556   // or greater appear immediately or after 'typename' or 'struct'. In the
    557   // latter case, replace the keyword with 'class'.
    558   if (!Tok.is(tok::kw_class)) {
    559     bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
    560     const Token& Next = Replace ? NextToken() : Tok;
    561     if (Next.is(tok::identifier) || Next.is(tok::comma) ||
    562         Next.is(tok::greater) || Next.is(tok::greatergreater) ||
    563         Next.is(tok::ellipsis))
    564       Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
    565         << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
    566                     : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
    567     else
    568       Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
    569 
    570     if (Replace)
    571       ConsumeToken();
    572   } else
    573     ConsumeToken();
    574 
    575   // Parse the ellipsis, if given.
    576   SourceLocation EllipsisLoc;
    577   if (Tok.is(tok::ellipsis)) {
    578     EllipsisLoc = ConsumeToken();
    579 
    580     Diag(EllipsisLoc,
    581          getLangOpts().CPlusPlus0x
    582            ? diag::warn_cxx98_compat_variadic_templates
    583            : diag::ext_variadic_templates);
    584   }
    585 
    586   // Get the identifier, if given.
    587   SourceLocation NameLoc;
    588   IdentifierInfo* ParamName = 0;
    589   if (Tok.is(tok::identifier)) {
    590     ParamName = Tok.getIdentifierInfo();
    591     NameLoc = ConsumeToken();
    592   } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
    593              Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
    594     // Unnamed template parameter. Don't have to do anything here, just
    595     // don't consume this token.
    596   } else {
    597     Diag(Tok.getLocation(), diag::err_expected_ident);
    598     return 0;
    599   }
    600 
    601   TemplateParameterList *ParamList =
    602     Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
    603                                        TemplateLoc, LAngleLoc,
    604                                        TemplateParams.data(),
    605                                        TemplateParams.size(),
    606                                        RAngleLoc);
    607 
    608   // Grab a default argument (if available).
    609   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
    610   // we introduce the template parameter into the local scope.
    611   SourceLocation EqualLoc;
    612   ParsedTemplateArgument DefaultArg;
    613   if (Tok.is(tok::equal)) {
    614     EqualLoc = ConsumeToken();
    615     DefaultArg = ParseTemplateTemplateArgument();
    616     if (DefaultArg.isInvalid()) {
    617       Diag(Tok.getLocation(),
    618            diag::err_default_template_template_parameter_not_template);
    619       SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
    620     }
    621   }
    622 
    623   return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
    624                                                 ParamList, EllipsisLoc,
    625                                                 ParamName, NameLoc, Depth,
    626                                                 Position, EqualLoc, DefaultArg);
    627 }
    628 
    629 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
    630 /// template parameters (e.g., in "template<int Size> class array;").
    631 ///
    632 ///       template-parameter:
    633 ///         ...
    634 ///         parameter-declaration
    635 Decl *
    636 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
    637   // Parse the declaration-specifiers (i.e., the type).
    638   // FIXME: The type should probably be restricted in some way... Not all
    639   // declarators (parts of declarators?) are accepted for parameters.
    640   DeclSpec DS(AttrFactory);
    641   ParseDeclarationSpecifiers(DS);
    642 
    643   // Parse this as a typename.
    644   Declarator ParamDecl(DS, Declarator::TemplateParamContext);
    645   ParseDeclarator(ParamDecl);
    646   if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
    647     Diag(Tok.getLocation(), diag::err_expected_template_parameter);
    648     return 0;
    649   }
    650 
    651   // If there is a default value, parse it.
    652   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
    653   // we introduce the template parameter into the local scope.
    654   SourceLocation EqualLoc;
    655   ExprResult DefaultArg;
    656   if (Tok.is(tok::equal)) {
    657     EqualLoc = ConsumeToken();
    658 
    659     // C++ [temp.param]p15:
    660     //   When parsing a default template-argument for a non-type
    661     //   template-parameter, the first non-nested > is taken as the
    662     //   end of the template-parameter-list rather than a greater-than
    663     //   operator.
    664     GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
    665     EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
    666 
    667     DefaultArg = ParseAssignmentExpression();
    668     if (DefaultArg.isInvalid())
    669       SkipUntil(tok::comma, tok::greater, true, true);
    670   }
    671 
    672   // Create the parameter.
    673   return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
    674                                                Depth, Position, EqualLoc,
    675                                                DefaultArg.take());
    676 }
    677 
    678 /// \brief Parses a template-id that after the template name has
    679 /// already been parsed.
    680 ///
    681 /// This routine takes care of parsing the enclosed template argument
    682 /// list ('<' template-parameter-list [opt] '>') and placing the
    683 /// results into a form that can be transferred to semantic analysis.
    684 ///
    685 /// \param Template the template declaration produced by isTemplateName
    686 ///
    687 /// \param TemplateNameLoc the source location of the template name
    688 ///
    689 /// \param SS if non-NULL, the nested-name-specifier preceding the
    690 /// template name.
    691 ///
    692 /// \param ConsumeLastToken if true, then we will consume the last
    693 /// token that forms the template-id. Otherwise, we will leave the
    694 /// last token in the stream (e.g., so that it can be replaced with an
    695 /// annotation token).
    696 bool
    697 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
    698                                          SourceLocation TemplateNameLoc,
    699                                          const CXXScopeSpec &SS,
    700                                          bool ConsumeLastToken,
    701                                          SourceLocation &LAngleLoc,
    702                                          TemplateArgList &TemplateArgs,
    703                                          SourceLocation &RAngleLoc) {
    704   assert(Tok.is(tok::less) && "Must have already parsed the template-name");
    705 
    706   // Consume the '<'.
    707   LAngleLoc = ConsumeToken();
    708 
    709   // Parse the optional template-argument-list.
    710   bool Invalid = false;
    711   {
    712     GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
    713     if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
    714       Invalid = ParseTemplateArgumentList(TemplateArgs);
    715 
    716     if (Invalid) {
    717       // Try to find the closing '>'.
    718       SkipUntil(tok::greater, true, !ConsumeLastToken);
    719 
    720       return true;
    721     }
    722   }
    723 
    724   // What will be left once we've consumed the '>'.
    725   tok::TokenKind RemainingToken;
    726   const char *ReplacementStr = "> >";
    727 
    728   switch (Tok.getKind()) {
    729   default:
    730     Diag(Tok.getLocation(), diag::err_expected_greater);
    731     return true;
    732 
    733   case tok::greater:
    734     // Determine the location of the '>' token. Only consume this token
    735     // if the caller asked us to.
    736     RAngleLoc = Tok.getLocation();
    737     if (ConsumeLastToken)
    738       ConsumeToken();
    739     return false;
    740 
    741   case tok::greatergreater:
    742     RemainingToken = tok::greater;
    743     break;
    744 
    745   case tok::greatergreatergreater:
    746     RemainingToken = tok::greatergreater;
    747     break;
    748 
    749   case tok::greaterequal:
    750     RemainingToken = tok::equal;
    751     ReplacementStr = "> =";
    752     break;
    753 
    754   case tok::greatergreaterequal:
    755     RemainingToken = tok::greaterequal;
    756     break;
    757   }
    758 
    759   // This template-id is terminated by a token which starts with a '>'. Outside
    760   // C++11, this is now error recovery, and in C++11, this is error recovery if
    761   // the token isn't '>>'.
    762 
    763   RAngleLoc = Tok.getLocation();
    764 
    765   // The source range of the '>>' or '>=' at the start of the token.
    766   CharSourceRange ReplacementRange =
    767       CharSourceRange::getCharRange(RAngleLoc,
    768           Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
    769                                          getLangOpts()));
    770 
    771   // A hint to put a space between the '>>'s. In order to make the hint as
    772   // clear as possible, we include the characters either side of the space in
    773   // the replacement, rather than just inserting a space at SecondCharLoc.
    774   FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
    775                                                  ReplacementStr);
    776 
    777   // A hint to put another space after the token, if it would otherwise be
    778   // lexed differently.
    779   FixItHint Hint2;
    780   Token Next = NextToken();
    781   if ((RemainingToken == tok::greater ||
    782        RemainingToken == tok::greatergreater) &&
    783       (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
    784        Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
    785        Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
    786        Next.is(tok::equalequal)) &&
    787       areTokensAdjacent(Tok, Next))
    788     Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
    789 
    790   unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
    791   if (getLangOpts().CPlusPlus0x && Tok.is(tok::greatergreater))
    792     DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
    793   else if (Tok.is(tok::greaterequal))
    794     DiagId = diag::err_right_angle_bracket_equal_needs_space;
    795   Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
    796 
    797   // Strip the initial '>' from the token.
    798   if (RemainingToken == tok::equal && Next.is(tok::equal) &&
    799       areTokensAdjacent(Tok, Next)) {
    800     // Join two adjacent '=' tokens into one, for cases like:
    801     //   void (*p)() = f<int>;
    802     //   return f<int>==p;
    803     ConsumeToken();
    804     Tok.setKind(tok::equalequal);
    805     Tok.setLength(Tok.getLength() + 1);
    806   } else {
    807     Tok.setKind(RemainingToken);
    808     Tok.setLength(Tok.getLength() - 1);
    809   }
    810   Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
    811                                                  PP.getSourceManager(),
    812                                                  getLangOpts()));
    813 
    814   if (!ConsumeLastToken) {
    815     // Since we're not supposed to consume the '>' token, we need to push
    816     // this token and revert the current token back to the '>'.
    817     PP.EnterToken(Tok);
    818     Tok.setKind(tok::greater);
    819     Tok.setLength(1);
    820     Tok.setLocation(RAngleLoc);
    821   }
    822 
    823   return false;
    824 }
    825 
    826 /// \brief Replace the tokens that form a simple-template-id with an
    827 /// annotation token containing the complete template-id.
    828 ///
    829 /// The first token in the stream must be the name of a template that
    830 /// is followed by a '<'. This routine will parse the complete
    831 /// simple-template-id and replace the tokens with a single annotation
    832 /// token with one of two different kinds: if the template-id names a
    833 /// type (and \p AllowTypeAnnotation is true), the annotation token is
    834 /// a type annotation that includes the optional nested-name-specifier
    835 /// (\p SS). Otherwise, the annotation token is a template-id
    836 /// annotation that does not include the optional
    837 /// nested-name-specifier.
    838 ///
    839 /// \param Template  the declaration of the template named by the first
    840 /// token (an identifier), as returned from \c Action::isTemplateName().
    841 ///
    842 /// \param TemplateNameKind the kind of template that \p Template
    843 /// refers to, as returned from \c Action::isTemplateName().
    844 ///
    845 /// \param SS if non-NULL, the nested-name-specifier that precedes
    846 /// this template name.
    847 ///
    848 /// \param TemplateKWLoc if valid, specifies that this template-id
    849 /// annotation was preceded by the 'template' keyword and gives the
    850 /// location of that keyword. If invalid (the default), then this
    851 /// template-id was not preceded by a 'template' keyword.
    852 ///
    853 /// \param AllowTypeAnnotation if true (the default), then a
    854 /// simple-template-id that refers to a class template, template
    855 /// template parameter, or other template that produces a type will be
    856 /// replaced with a type annotation token. Otherwise, the
    857 /// simple-template-id is always replaced with a template-id
    858 /// annotation token.
    859 ///
    860 /// If an unrecoverable parse error occurs and no annotation token can be
    861 /// formed, this function returns true.
    862 ///
    863 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
    864                                      CXXScopeSpec &SS,
    865                                      SourceLocation TemplateKWLoc,
    866                                      UnqualifiedId &TemplateName,
    867                                      bool AllowTypeAnnotation) {
    868   assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
    869   assert(Template && Tok.is(tok::less) &&
    870          "Parser isn't at the beginning of a template-id");
    871 
    872   // Consume the template-name.
    873   SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
    874 
    875   // Parse the enclosed template argument list.
    876   SourceLocation LAngleLoc, RAngleLoc;
    877   TemplateArgList TemplateArgs;
    878   bool Invalid = ParseTemplateIdAfterTemplateName(Template,
    879                                                   TemplateNameLoc,
    880                                                   SS, false, LAngleLoc,
    881                                                   TemplateArgs,
    882                                                   RAngleLoc);
    883 
    884   if (Invalid) {
    885     // If we failed to parse the template ID but skipped ahead to a >, we're not
    886     // going to be able to form a token annotation.  Eat the '>' if present.
    887     if (Tok.is(tok::greater))
    888       ConsumeToken();
    889     return true;
    890   }
    891 
    892   ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
    893 
    894   // Build the annotation token.
    895   if (TNK == TNK_Type_template && AllowTypeAnnotation) {
    896     TypeResult Type
    897       = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
    898                                     Template, TemplateNameLoc,
    899                                     LAngleLoc, TemplateArgsPtr, RAngleLoc);
    900     if (Type.isInvalid()) {
    901       // If we failed to parse the template ID but skipped ahead to a >, we're not
    902       // going to be able to form a token annotation.  Eat the '>' if present.
    903       if (Tok.is(tok::greater))
    904         ConsumeToken();
    905       return true;
    906     }
    907 
    908     Tok.setKind(tok::annot_typename);
    909     setTypeAnnotation(Tok, Type.get());
    910     if (SS.isNotEmpty())
    911       Tok.setLocation(SS.getBeginLoc());
    912     else if (TemplateKWLoc.isValid())
    913       Tok.setLocation(TemplateKWLoc);
    914     else
    915       Tok.setLocation(TemplateNameLoc);
    916   } else {
    917     // Build a template-id annotation token that can be processed
    918     // later.
    919     Tok.setKind(tok::annot_template_id);
    920     TemplateIdAnnotation *TemplateId
    921       = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
    922     TemplateId->TemplateNameLoc = TemplateNameLoc;
    923     if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
    924       TemplateId->Name = TemplateName.Identifier;
    925       TemplateId->Operator = OO_None;
    926     } else {
    927       TemplateId->Name = 0;
    928       TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
    929     }
    930     TemplateId->SS = SS;
    931     TemplateId->TemplateKWLoc = TemplateKWLoc;
    932     TemplateId->Template = Template;
    933     TemplateId->Kind = TNK;
    934     TemplateId->LAngleLoc = LAngleLoc;
    935     TemplateId->RAngleLoc = RAngleLoc;
    936     ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
    937     for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
    938       Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
    939     Tok.setAnnotationValue(TemplateId);
    940     if (TemplateKWLoc.isValid())
    941       Tok.setLocation(TemplateKWLoc);
    942     else
    943       Tok.setLocation(TemplateNameLoc);
    944   }
    945 
    946   // Common fields for the annotation token
    947   Tok.setAnnotationEndLoc(RAngleLoc);
    948 
    949   // In case the tokens were cached, have Preprocessor replace them with the
    950   // annotation token.
    951   PP.AnnotateCachedTokens(Tok);
    952   return false;
    953 }
    954 
    955 /// \brief Replaces a template-id annotation token with a type
    956 /// annotation token.
    957 ///
    958 /// If there was a failure when forming the type from the template-id,
    959 /// a type annotation token will still be created, but will have a
    960 /// NULL type pointer to signify an error.
    961 void Parser::AnnotateTemplateIdTokenAsType() {
    962   assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
    963 
    964   TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
    965   assert((TemplateId->Kind == TNK_Type_template ||
    966           TemplateId->Kind == TNK_Dependent_template_name) &&
    967          "Only works for type and dependent templates");
    968 
    969   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
    970                                      TemplateId->NumArgs);
    971 
    972   TypeResult Type
    973     = Actions.ActOnTemplateIdType(TemplateId->SS,
    974                                   TemplateId->TemplateKWLoc,
    975                                   TemplateId->Template,
    976                                   TemplateId->TemplateNameLoc,
    977                                   TemplateId->LAngleLoc,
    978                                   TemplateArgsPtr,
    979                                   TemplateId->RAngleLoc);
    980   // Create the new "type" annotation token.
    981   Tok.setKind(tok::annot_typename);
    982   setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
    983   if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
    984     Tok.setLocation(TemplateId->SS.getBeginLoc());
    985   // End location stays the same
    986 
    987   // Replace the template-id annotation token, and possible the scope-specifier
    988   // that precedes it, with the typename annotation token.
    989   PP.AnnotateCachedTokens(Tok);
    990 }
    991 
    992 /// \brief Determine whether the given token can end a template argument.
    993 static bool isEndOfTemplateArgument(Token Tok) {
    994   return Tok.is(tok::comma) || Tok.is(tok::greater) ||
    995          Tok.is(tok::greatergreater);
    996 }
    997 
    998 /// \brief Parse a C++ template template argument.
    999 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
   1000   if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
   1001       !Tok.is(tok::annot_cxxscope))
   1002     return ParsedTemplateArgument();
   1003 
   1004   // C++0x [temp.arg.template]p1:
   1005   //   A template-argument for a template template-parameter shall be the name
   1006   //   of a class template or an alias template, expressed as id-expression.
   1007   //
   1008   // We parse an id-expression that refers to a class template or alias
   1009   // template. The grammar we parse is:
   1010   //
   1011   //   nested-name-specifier[opt] template[opt] identifier ...[opt]
   1012   //
   1013   // followed by a token that terminates a template argument, such as ',',
   1014   // '>', or (in some cases) '>>'.
   1015   CXXScopeSpec SS; // nested-name-specifier, if present
   1016   ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
   1017                                  /*EnteringContext=*/false);
   1018 
   1019   ParsedTemplateArgument Result;
   1020   SourceLocation EllipsisLoc;
   1021   if (SS.isSet() && Tok.is(tok::kw_template)) {
   1022     // Parse the optional 'template' keyword following the
   1023     // nested-name-specifier.
   1024     SourceLocation TemplateKWLoc = ConsumeToken();
   1025 
   1026     if (Tok.is(tok::identifier)) {
   1027       // We appear to have a dependent template name.
   1028       UnqualifiedId Name;
   1029       Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
   1030       ConsumeToken(); // the identifier
   1031 
   1032       // Parse the ellipsis.
   1033       if (Tok.is(tok::ellipsis))
   1034         EllipsisLoc = ConsumeToken();
   1035 
   1036       // If the next token signals the end of a template argument,
   1037       // then we have a dependent template name that could be a template
   1038       // template argument.
   1039       TemplateTy Template;
   1040       if (isEndOfTemplateArgument(Tok) &&
   1041           Actions.ActOnDependentTemplateName(getCurScope(),
   1042                                              SS, TemplateKWLoc, Name,
   1043                                              /*ObjectType=*/ ParsedType(),
   1044                                              /*EnteringContext=*/false,
   1045                                              Template))
   1046         Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
   1047     }
   1048   } else if (Tok.is(tok::identifier)) {
   1049     // We may have a (non-dependent) template name.
   1050     TemplateTy Template;
   1051     UnqualifiedId Name;
   1052     Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
   1053     ConsumeToken(); // the identifier
   1054 
   1055     // Parse the ellipsis.
   1056     if (Tok.is(tok::ellipsis))
   1057       EllipsisLoc = ConsumeToken();
   1058 
   1059     if (isEndOfTemplateArgument(Tok)) {
   1060       bool MemberOfUnknownSpecialization;
   1061       TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
   1062                                                /*hasTemplateKeyword=*/false,
   1063                                                     Name,
   1064                                                /*ObjectType=*/ ParsedType(),
   1065                                                     /*EnteringContext=*/false,
   1066                                                     Template,
   1067                                                 MemberOfUnknownSpecialization);
   1068       if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
   1069         // We have an id-expression that refers to a class template or
   1070         // (C++0x) alias template.
   1071         Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
   1072       }
   1073     }
   1074   }
   1075 
   1076   // If this is a pack expansion, build it as such.
   1077   if (EllipsisLoc.isValid() && !Result.isInvalid())
   1078     Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
   1079 
   1080   return Result;
   1081 }
   1082 
   1083 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
   1084 ///
   1085 ///       template-argument: [C++ 14.2]
   1086 ///         constant-expression
   1087 ///         type-id
   1088 ///         id-expression
   1089 ParsedTemplateArgument Parser::ParseTemplateArgument() {
   1090   // C++ [temp.arg]p2:
   1091   //   In a template-argument, an ambiguity between a type-id and an
   1092   //   expression is resolved to a type-id, regardless of the form of
   1093   //   the corresponding template-parameter.
   1094   //
   1095   // Therefore, we initially try to parse a type-id.
   1096   if (isCXXTypeId(TypeIdAsTemplateArgument)) {
   1097     SourceLocation Loc = Tok.getLocation();
   1098     TypeResult TypeArg = ParseTypeName(/*Range=*/0,
   1099                                        Declarator::TemplateTypeArgContext);
   1100     if (TypeArg.isInvalid())
   1101       return ParsedTemplateArgument();
   1102 
   1103     return ParsedTemplateArgument(ParsedTemplateArgument::Type,
   1104                                   TypeArg.get().getAsOpaquePtr(),
   1105                                   Loc);
   1106   }
   1107 
   1108   // Try to parse a template template argument.
   1109   {
   1110     TentativeParsingAction TPA(*this);
   1111 
   1112     ParsedTemplateArgument TemplateTemplateArgument
   1113       = ParseTemplateTemplateArgument();
   1114     if (!TemplateTemplateArgument.isInvalid()) {
   1115       TPA.Commit();
   1116       return TemplateTemplateArgument;
   1117     }
   1118 
   1119     // Revert this tentative parse to parse a non-type template argument.
   1120     TPA.Revert();
   1121   }
   1122 
   1123   // Parse a non-type template argument.
   1124   SourceLocation Loc = Tok.getLocation();
   1125   ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
   1126   if (ExprArg.isInvalid() || !ExprArg.get())
   1127     return ParsedTemplateArgument();
   1128 
   1129   return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
   1130                                 ExprArg.release(), Loc);
   1131 }
   1132 
   1133 /// \brief Determine whether the current tokens can only be parsed as a
   1134 /// template argument list (starting with the '<') and never as a '<'
   1135 /// expression.
   1136 bool Parser::IsTemplateArgumentList(unsigned Skip) {
   1137   struct AlwaysRevertAction : TentativeParsingAction {
   1138     AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
   1139     ~AlwaysRevertAction() { Revert(); }
   1140   } Tentative(*this);
   1141 
   1142   while (Skip) {
   1143     ConsumeToken();
   1144     --Skip;
   1145   }
   1146 
   1147   // '<'
   1148   if (!Tok.is(tok::less))
   1149     return false;
   1150   ConsumeToken();
   1151 
   1152   // An empty template argument list.
   1153   if (Tok.is(tok::greater))
   1154     return true;
   1155 
   1156   // See whether we have declaration specifiers, which indicate a type.
   1157   while (isCXXDeclarationSpecifier() == TPResult::True())
   1158     ConsumeToken();
   1159 
   1160   // If we have a '>' or a ',' then this is a template argument list.
   1161   return Tok.is(tok::greater) || Tok.is(tok::comma);
   1162 }
   1163 
   1164 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
   1165 /// (C++ [temp.names]). Returns true if there was an error.
   1166 ///
   1167 ///       template-argument-list: [C++ 14.2]
   1168 ///         template-argument
   1169 ///         template-argument-list ',' template-argument
   1170 bool
   1171 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
   1172   while (true) {
   1173     ParsedTemplateArgument Arg = ParseTemplateArgument();
   1174     if (Tok.is(tok::ellipsis)) {
   1175       SourceLocation EllipsisLoc  = ConsumeToken();
   1176       Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
   1177     }
   1178 
   1179     if (Arg.isInvalid()) {
   1180       SkipUntil(tok::comma, tok::greater, true, true);
   1181       return true;
   1182     }
   1183 
   1184     // Save this template argument.
   1185     TemplateArgs.push_back(Arg);
   1186 
   1187     // If the next token is a comma, consume it and keep reading
   1188     // arguments.
   1189     if (Tok.isNot(tok::comma)) break;
   1190 
   1191     // Consume the comma.
   1192     ConsumeToken();
   1193   }
   1194 
   1195   return false;
   1196 }
   1197 
   1198 /// \brief Parse a C++ explicit template instantiation
   1199 /// (C++ [temp.explicit]).
   1200 ///
   1201 ///       explicit-instantiation:
   1202 ///         'extern' [opt] 'template' declaration
   1203 ///
   1204 /// Note that the 'extern' is a GNU extension and C++0x feature.
   1205 Decl *Parser::ParseExplicitInstantiation(unsigned Context,
   1206                                          SourceLocation ExternLoc,
   1207                                          SourceLocation TemplateLoc,
   1208                                          SourceLocation &DeclEnd,
   1209                                          AccessSpecifier AS) {
   1210   // This isn't really required here.
   1211   ParsingDeclRAIIObject
   1212     ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
   1213 
   1214   return ParseSingleDeclarationAfterTemplate(Context,
   1215                                              ParsedTemplateInfo(ExternLoc,
   1216                                                                 TemplateLoc),
   1217                                              ParsingTemplateParams,
   1218                                              DeclEnd, AS);
   1219 }
   1220 
   1221 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
   1222   if (TemplateParams)
   1223     return getTemplateParamsRange(TemplateParams->data(),
   1224                                   TemplateParams->size());
   1225 
   1226   SourceRange R(TemplateLoc);
   1227   if (ExternLoc.isValid())
   1228     R.setBegin(ExternLoc);
   1229   return R;
   1230 }
   1231 
   1232 void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
   1233   ((Parser*)P)->LateTemplateParser(FD);
   1234 }
   1235 
   1236 
   1237 void Parser::LateTemplateParser(const FunctionDecl *FD) {
   1238   LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
   1239   if (LPT) {
   1240     ParseLateTemplatedFuncDef(*LPT);
   1241     return;
   1242   }
   1243 
   1244   llvm_unreachable("Late templated function without associated lexed tokens");
   1245 }
   1246 
   1247 /// \brief Late parse a C++ function template in Microsoft mode.
   1248 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
   1249   if(!LMT.D)
   1250      return;
   1251 
   1252   // Get the FunctionDecl.
   1253   FunctionDecl *FD = 0;
   1254   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
   1255     FD = FunTmpl->getTemplatedDecl();
   1256   else
   1257     FD = cast<FunctionDecl>(LMT.D);
   1258 
   1259   // To restore the context after late parsing.
   1260   Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
   1261 
   1262   SmallVector<ParseScope*, 4> TemplateParamScopeStack;
   1263   DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
   1264   if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
   1265     TemplateParamScopeStack.push_back(new ParseScope(this, Scope::TemplateParamScope));
   1266     Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
   1267     Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
   1268   } else {
   1269     // Get the list of DeclContext to reenter.
   1270     SmallVector<DeclContext*, 4> DeclContextToReenter;
   1271     DeclContext *DD = FD->getLexicalParent();
   1272     while (DD && !DD->isTranslationUnit()) {
   1273       DeclContextToReenter.push_back(DD);
   1274       DD = DD->getLexicalParent();
   1275     }
   1276 
   1277     // Reenter template scopes from outmost to innermost.
   1278     SmallVector<DeclContext*, 4>::reverse_iterator II =
   1279     DeclContextToReenter.rbegin();
   1280     for (; II != DeclContextToReenter.rend(); ++II) {
   1281       if (ClassTemplatePartialSpecializationDecl* MD =
   1282                 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
   1283         TemplateParamScopeStack.push_back(new ParseScope(this,
   1284                                                    Scope::TemplateParamScope));
   1285         Actions.ActOnReenterTemplateScope(getCurScope(), MD);
   1286       } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
   1287         TemplateParamScopeStack.push_back(new ParseScope(this,
   1288                                                     Scope::TemplateParamScope,
   1289                                        MD->getDescribedClassTemplate() != 0 ));
   1290         Actions.ActOnReenterTemplateScope(getCurScope(),
   1291                                           MD->getDescribedClassTemplate());
   1292       }
   1293       TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
   1294       Actions.PushDeclContext(Actions.getCurScope(), *II);
   1295     }
   1296     TemplateParamScopeStack.push_back(new ParseScope(this,
   1297                                       Scope::TemplateParamScope));
   1298     Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
   1299   }
   1300 
   1301   assert(!LMT.Toks.empty() && "Empty body!");
   1302 
   1303   // Append the current token at the end of the new token stream so that it
   1304   // doesn't get lost.
   1305   LMT.Toks.push_back(Tok);
   1306   PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
   1307 
   1308   // Consume the previously pushed token.
   1309   ConsumeAnyToken();
   1310   assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
   1311          && "Inline method not starting with '{', ':' or 'try'");
   1312 
   1313   // Parse the method body. Function body parsing code is similar enough
   1314   // to be re-used for method bodies as well.
   1315   ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
   1316 
   1317   // Recreate the containing function DeclContext.
   1318   Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FD));
   1319 
   1320   if (FunctionTemplateDecl *FunctionTemplate
   1321         = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
   1322     Actions.ActOnStartOfFunctionDef(getCurScope(),
   1323                                    FunctionTemplate->getTemplatedDecl());
   1324   if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
   1325     Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
   1326 
   1327 
   1328   if (Tok.is(tok::kw_try)) {
   1329     ParseFunctionTryBlock(LMT.D, FnScope);
   1330   } else {
   1331     if (Tok.is(tok::colon))
   1332       ParseConstructorInitializer(LMT.D);
   1333     else
   1334       Actions.ActOnDefaultCtorInitializers(LMT.D);
   1335 
   1336     if (Tok.is(tok::l_brace)) {
   1337       ParseFunctionStatementBody(LMT.D, FnScope);
   1338       Actions.MarkAsLateParsedTemplate(FD, false);
   1339     } else
   1340       Actions.ActOnFinishFunctionBody(LMT.D, 0);
   1341   }
   1342 
   1343   // Exit scopes.
   1344   FnScope.Exit();
   1345   SmallVector<ParseScope*, 4>::reverse_iterator I =
   1346    TemplateParamScopeStack.rbegin();
   1347   for (; I != TemplateParamScopeStack.rend(); ++I)
   1348     delete *I;
   1349 
   1350   DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
   1351   if (grp)
   1352     Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
   1353 }
   1354 
   1355 /// \brief Lex a delayed template function for late parsing.
   1356 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
   1357   tok::TokenKind kind = Tok.getKind();
   1358   if (!ConsumeAndStoreFunctionPrologue(Toks)) {
   1359     // Consume everything up to (and including) the matching right brace.
   1360     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
   1361   }
   1362 
   1363   // If we're in a function-try-block, we need to store all the catch blocks.
   1364   if (kind == tok::kw_try) {
   1365     while (Tok.is(tok::kw_catch)) {
   1366       ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
   1367       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
   1368     }
   1369   }
   1370 }
   1371