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