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