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