ParseTemplate.cpp revision 245431
1193326Sed//===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements parsing of C++ templates.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#include "clang/Parse/Parser.h"
15193326Sed#include "clang/Parse/ParseDiagnostic.h"
16193326Sed#include "clang/Sema/DeclSpec.h"
17212904Sdim#include "clang/Sema/ParsedTemplate.h"
18193326Sed#include "clang/Sema/Scope.h"
19193326Sed#include "RAIIObjectsForParser.h"
20193326Sed#include "clang/AST/DeclTemplate.h"
21193326Sed#include "clang/AST/ASTConsumer.h"
22193326Sedusing namespace clang;
23193326Sed
24193326Sed/// \brief Parse a template declaration, explicit instantiation, or
25193326Sed/// explicit specialization.
26193326SedDecl *
27193326SedParser::ParseDeclarationStartingWithTemplate(unsigned Context,
28193326Sed                                             SourceLocation &DeclEnd,
29193326Sed                                             AccessSpecifier AS,
30193326Sed                                             AttributeList *AccessAttrs) {
31193326Sed  ObjCDeclContextSwitch ObjCDC(*this);
32193326Sed
33193326Sed  if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
34193326Sed    return ParseExplicitInstantiation(Context,
35193326Sed                                      SourceLocation(), ConsumeToken(),
36193326Sed                                      DeclEnd, AS);
37193326Sed  }
38193326Sed  return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
39193326Sed                                                  AccessAttrs);
40193326Sed}
41193326Sed
42193326Sed/// \brief RAII class that manages the template parameter depth.
43193326Sednamespace {
44193326Sed  class TemplateParameterDepthCounter {
45193326Sed    unsigned &Depth;
46193326Sed    unsigned AddedLevels;
47193326Sed
48193326Sed  public:
49193326Sed    explicit TemplateParameterDepthCounter(unsigned &Depth)
50193326Sed      : Depth(Depth), AddedLevels(0) { }
51193326Sed
52193326Sed    ~TemplateParameterDepthCounter() {
53193326Sed      Depth -= AddedLevels;
54193326Sed    }
55193326Sed
56193326Sed    void operator++() {
57193326Sed      ++Depth;
58193326Sed      ++AddedLevels;
59199990Srdivacky    }
60193326Sed
61221345Sdim    operator unsigned() const { return Depth; }
62193326Sed  };
63199990Srdivacky}
64193326Sed
65235633Sdim/// \brief Parse a template declaration or an explicit specialization.
66193326Sed///
67193326Sed/// Template declarations include one or more template parameter lists
68193326Sed/// and either the function or class template declaration. Explicit
69193326Sed/// specializations contain one or more 'template < >' prefixes
70193326Sed/// followed by a (possibly templated) declaration. Since the
71193326Sed/// syntactic form of both features is nearly identical, we parse all
72193326Sed/// of the template headers together and let semantic analysis sort
73193326Sed/// the declarations from the explicit specializations.
74193326Sed///
75193326Sed///       template-declaration: [C++ temp]
76193326Sed///         'export'[opt] 'template' '<' template-parameter-list '>' declaration
77193326Sed///
78235633Sdim///       explicit-specialization: [ C++ temp.expl.spec]
79235633Sdim///         'template' '<' '>' declaration
80235633SdimDecl *
81235633SdimParser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
82235633Sdim                                                 SourceLocation &DeclEnd,
83193326Sed                                                 AccessSpecifier AS,
84193326Sed                                                 AttributeList *AccessAttrs) {
85193326Sed  assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
86193326Sed         "Token does not start a template declaration.");
87193326Sed
88193326Sed  // Enter template-parameter scope.
89193326Sed  ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
90193326Sed
91193326Sed  // Tell the action that names should be checked in the context of
92193326Sed  // the declaration to come.
93193326Sed  ParsingDeclRAIIObject
94193326Sed    ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
95193326Sed
96193326Sed  // Parse multiple levels of template headers within this template
97193326Sed  // parameter scope, e.g.,
98193326Sed  //
99193326Sed  //   template<typename T>
100193326Sed  //     template<typename U>
101193326Sed  //       class A<T>::B { ... };
102193326Sed  //
103193326Sed  // We parse multiple levels non-recursively so that we can build a
104193326Sed  // single data structure containing all of the template parameter
105193326Sed  // lists to easily differentiate between the case above and:
106193326Sed  //
107245431Sdim  //   template<typename T>
108245431Sdim  //   class A {
109245431Sdim  //     template<typename U> class B;
110193326Sed  //   };
111193326Sed  //
112193326Sed  // In the first case, the action for declaring A<T>::B receives
113193326Sed  // both template parameter lists. In the second case, the action for
114245431Sdim  // defining A<T>::B receives just the inner template parameter list
115245431Sdim  // (and retrieves the outer template parameter list from its
116245431Sdim  // context).
117245431Sdim  bool isSpecialization = true;
118245431Sdim  bool LastParamListWasEmpty = false;
119245431Sdim  TemplateParameterLists ParamLists;
120245431Sdim  TemplateParameterDepthCounter Depth(TemplateParameterDepth);
121245431Sdim  do {
122193326Sed    // Consume the 'export', if any.
123193326Sed    SourceLocation ExportLoc;
124193326Sed    if (Tok.is(tok::kw_export)) {
125245431Sdim      ExportLoc = ConsumeToken();
126245431Sdim    }
127245431Sdim
128193326Sed    // Consume the 'template', which should be here.
129193326Sed    SourceLocation TemplateLoc;
130235633Sdim    if (Tok.is(tok::kw_template)) {
131193326Sed      TemplateLoc = ConsumeToken();
132193326Sed    } else {
133193326Sed      Diag(Tok.getLocation(), diag::err_expected_template);
134193326Sed      return 0;
135193326Sed    }
136193326Sed
137193326Sed    // Parse the '<' template-parameter-list '>'
138193326Sed    SourceLocation LAngleLoc, RAngleLoc;
139193326Sed    SmallVector<Decl*, 4> TemplateParams;
140193326Sed    if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
141193326Sed                                RAngleLoc)) {
142193326Sed      // Skip until the semi-colon or a }.
143193326Sed      SkipUntil(tok::r_brace, true, true);
144193326Sed      if (Tok.is(tok::semi))
145193326Sed        ConsumeToken();
146193326Sed      return 0;
147193326Sed    }
148235633Sdim
149235633Sdim    ParamLists.push_back(
150235633Sdim      Actions.ActOnTemplateParameterList(Depth, ExportLoc,
151235633Sdim                                         TemplateLoc, LAngleLoc,
152235633Sdim                                         TemplateParams.data(),
153235633Sdim                                         TemplateParams.size(), RAngleLoc));
154193326Sed
155193326Sed    if (!TemplateParams.empty()) {
156218893Sdim      isSpecialization = false;
157245431Sdim      ++Depth;
158245431Sdim    } else {
159193326Sed      LastParamListWasEmpty = true;
160245431Sdim    }
161235633Sdim  } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
162218893Sdim
163218893Sdim  // Parse the actual template declaration.
164193326Sed  return ParseSingleDeclarationAfterTemplate(Context,
165245431Sdim                                             ParsedTemplateInfo(&ParamLists,
166245431Sdim                                                             isSpecialization,
167245431Sdim                                                         LastParamListWasEmpty),
168245431Sdim                                             ParsingTemplateParams,
169245431Sdim                                             DeclEnd, AS, AccessAttrs);
170245431Sdim}
171245431Sdim
172245431Sdim/// \brief Parse a single declaration that declares a template,
173245431Sdim/// template specialization, or explicit instantiation of a template.
174245431Sdim///
175245431Sdim/// \param TemplateParams if non-NULL, the template parameter lists
176245431Sdim/// that preceded this declaration. In this case, the declaration is a
177193326Sed/// template declaration, out-of-line definition of a template, or an
178193326Sed/// explicit template specialization. When NULL, the declaration is an
179193326Sed/// explicit template instantiation.
180193326Sed///
181235633Sdim/// \param TemplateLoc when TemplateParams is NULL, the location of
182193326Sed/// the 'template' keyword that indicates that we have an explicit
183193326Sed/// template instantiation.
184193326Sed///
185193326Sed/// \param DeclEnd will receive the source location of the last token
186193326Sed/// within this declaration.
187193326Sed///
188193326Sed/// \param AS the access specifier associated with this
189193326Sed/// declaration. Will be AS_none for namespace-scope declarations.
190193326Sed///
191193326Sed/// \returns the new declaration.
192193326SedDecl *
193193326SedParser::ParseSingleDeclarationAfterTemplate(
194193326Sed                                       unsigned Context,
195193326Sed                                       const ParsedTemplateInfo &TemplateInfo,
196193326Sed                                       ParsingDeclRAIIObject &DiagsFromTParams,
197193326Sed                                       SourceLocation &DeclEnd,
198193326Sed                                       AccessSpecifier AS,
199193326Sed                                       AttributeList *AccessAttrs) {
200193326Sed  assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
201193326Sed         "Template information required");
202193326Sed
203193326Sed  if (Context == Declarator::MemberContext) {
204193326Sed    // We are parsing a member template.
205193326Sed    ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
206193326Sed                                   &DiagsFromTParams);
207193326Sed    return 0;
208193326Sed  }
209193326Sed
210193326Sed  ParsedAttributesWithRange prefixAttrs(AttrFactory);
211193326Sed  MaybeParseCXX0XAttributes(prefixAttrs);
212193326Sed
213193326Sed  if (Tok.is(tok::kw_using))
214193326Sed    return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
215193326Sed                                            prefixAttrs);
216193326Sed
217193326Sed  // Parse the declaration specifiers, stealing any diagnostics from
218193326Sed  // the template parameters.
219193326Sed  ParsingDeclSpec DS(*this, &DiagsFromTParams);
220193326Sed
221212904Sdim  // Move the attributes from the prefix into the DS.
222212904Sdim  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
223212904Sdim    ProhibitAttributes(prefixAttrs);
224212904Sdim  else
225212904Sdim    DS.takeAttributesFrom(prefixAttrs);
226193326Sed
227212904Sdim  ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
228212904Sdim                             getDeclSpecContextFromDeclaratorContext(Context));
229212904Sdim
230212904Sdim  if (Tok.is(tok::semi)) {
231212904Sdim    DeclEnd = ConsumeToken();
232212904Sdim    Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
233212904Sdim    DS.complete(Decl);
234212904Sdim    return Decl;
235212904Sdim  }
236212904Sdim
237193326Sed  // Parse the declarator.
238193326Sed  ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
239193326Sed  ParseDeclarator(DeclaratorInfo);
240193326Sed  // Error parsing the declarator?
241193326Sed  if (!DeclaratorInfo.hasName()) {
242193326Sed    // If so, skip until the semi-colon or a }.
243193326Sed    SkipUntil(tok::r_brace, true, true);
244193326Sed    if (Tok.is(tok::semi))
245193326Sed      ConsumeToken();
246193326Sed    return 0;
247193326Sed  }
248193326Sed
249193326Sed  LateParsedAttrList LateParsedAttrs(true);
250193326Sed  if (DeclaratorInfo.isFunctionDeclarator())
251193326Sed    MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
252193326Sed
253193326Sed  // If we have a declaration or declarator list, handle it.
254193326Sed  if (isDeclarationAfterDeclarator()) {
255235633Sdim    // Parse this declaration.
256235633Sdim    Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
257193326Sed                                                     TemplateInfo);
258193326Sed
259193326Sed    if (Tok.is(tok::comma)) {
260193326Sed      Diag(Tok, diag::err_multiple_template_declarators)
261193326Sed        << (int)TemplateInfo.Kind;
262193326Sed      SkipUntil(tok::semi, true, false);
263193326Sed      return ThisDecl;
264193326Sed    }
265193326Sed
266193326Sed    // Eat the semi colon after the declaration.
267193326Sed    ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
268193326Sed    if (LateParsedAttrs.size() > 0)
269193326Sed      ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
270193326Sed    DeclaratorInfo.complete(ThisDecl);
271193326Sed    return ThisDecl;
272193326Sed  }
273193326Sed
274193326Sed  if (DeclaratorInfo.isFunctionDeclarator() &&
275193326Sed      isStartOfFunctionDefinition(DeclaratorInfo)) {
276193326Sed    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
277218893Sdim      // Recover by ignoring the 'typedef'. This was probably supposed to be
278193326Sed      // the 'typename' keyword, which we should have already suggested adding
279218893Sdim      // if it's appropriate.
280235633Sdim      Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
281218893Sdim        << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
282218893Sdim      DS.ClearStorageClassSpecs();
283193326Sed    }
284193326Sed    return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
285193326Sed                                   &LateParsedAttrs);
286193326Sed  }
287193326Sed
288193326Sed  if (DeclaratorInfo.isFunctionDeclarator())
289193326Sed    Diag(Tok, diag::err_expected_fn_body);
290193326Sed  else
291193326Sed    Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
292193326Sed  SkipUntil(tok::semi);
293193326Sed  return 0;
294193326Sed}
295193326Sed
296193326Sed/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
297193326Sed/// angle brackets. Depth is the depth of this template-parameter-list, which
298235633Sdim/// is the number of template headers directly enclosing this template header.
299235633Sdim/// TemplateParams is the current list of template parameters we're building.
300193326Sed/// The template parameter we parse will be added to this list. LAngleLoc and
301193326Sed/// RAngleLoc will receive the positions of the '<' and '>', respectively,
302193326Sed/// that enclose this template parameter list.
303193326Sed///
304193326Sed/// \returns true if an error occurred, false otherwise.
305193326Sedbool Parser::ParseTemplateParameters(unsigned Depth,
306193326Sed                               SmallVectorImpl<Decl*> &TemplateParams,
307193326Sed                                     SourceLocation &LAngleLoc,
308193326Sed                                     SourceLocation &RAngleLoc) {
309193326Sed  // Get the template parameter list.
310198092Srdivacky  if (!Tok.is(tok::less)) {
311193326Sed    Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
312193326Sed    return true;
313193326Sed  }
314193326Sed  LAngleLoc = ConsumeToken();
315193326Sed
316193326Sed  // Try to parse the template parameter list.
317193326Sed  bool Failed = false;
318193326Sed  if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
319193326Sed    Failed = ParseTemplateParameterList(Depth, TemplateParams);
320193326Sed
321193326Sed  if (Tok.is(tok::greatergreater)) {
322193326Sed    // No diagnostic required here: a template-parameter-list can only be
323193326Sed    // followed by a declaration or, for a template template parameter, the
324193326Sed    // 'class' keyword. Therefore, the second '>' will be diagnosed later.
325193326Sed    // This matters for elegant diagnosis of:
326193326Sed    //   template<template<typename>> struct S;
327193326Sed    Tok.setKind(tok::greater);
328198092Srdivacky    RAngleLoc = Tok.getLocation();
329193326Sed    Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
330193326Sed  } else if (Tok.is(tok::greater))
331193326Sed    RAngleLoc = ConsumeToken();
332193326Sed  else if (Failed) {
333193326Sed    Diag(Tok.getLocation(), diag::err_expected_greater);
334193326Sed    return true;
335193326Sed  }
336193326Sed  return false;
337193326Sed}
338193326Sed
339193326Sed/// ParseTemplateParameterList - Parse a template parameter list. If
340193326Sed/// the parsing fails badly (i.e., closing bracket was left out), this
341193326Sed/// will try to put the token stream in a reasonable position (closing
342193326Sed/// a statement, etc.) and return false.
343193326Sed///
344193326Sed///       template-parameter-list:    [C++ temp]
345193326Sed///         template-parameter
346193326Sed///         template-parameter-list ',' template-parameter
347193326Sedbool
348193326SedParser::ParseTemplateParameterList(unsigned Depth,
349193326Sed                             SmallVectorImpl<Decl*> &TemplateParams) {
350193326Sed  while (1) {
351193326Sed    if (Decl *TmpParam
352193326Sed          = ParseTemplateParameter(Depth, TemplateParams.size())) {
353193326Sed      TemplateParams.push_back(TmpParam);
354218893Sdim    } else {
355193326Sed      // If we failed to parse a template parameter, skip until we find
356218893Sdim      // a comma or closing brace.
357235633Sdim      SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
358218893Sdim    }
359218893Sdim
360218893Sdim    // Did we find a comma or the end of the template parmeter list?
361193326Sed    if (Tok.is(tok::comma)) {
362193326Sed      ConsumeToken();
363193326Sed    } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
364193326Sed      // Don't consume this... that's done by template parser.
365193326Sed      break;
366193326Sed    } else {
367193326Sed      // Somebody probably forgot to close the template. Skip ahead and
368193326Sed      // try to get out of the expression. This error is currently
369193326Sed      // subsumed by whatever goes on in ParseTemplateParameter.
370193326Sed      Diag(Tok.getLocation(), diag::err_expected_comma_greater);
371193326Sed      SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
372193326Sed      return false;
373193326Sed    }
374193326Sed  }
375193326Sed  return true;
376193326Sed}
377193326Sed
378193326Sed/// \brief Determine whether the parser is at the start of a template
379193326Sed/// type parameter.
380193326Sedbool Parser::isStartOfTemplateTypeParameter() {
381193326Sed  if (Tok.is(tok::kw_class)) {
382235633Sdim    // "class" may be the start of an elaborated-type-specifier or a
383193326Sed    // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
384193326Sed    switch (NextToken().getKind()) {
385193326Sed    case tok::equal:
386193326Sed    case tok::comma:
387193326Sed    case tok::greater:
388193326Sed    case tok::greatergreater:
389193326Sed    case tok::ellipsis:
390193326Sed      return true;
391193326Sed
392193326Sed    case tok::identifier:
393193326Sed      // This may be either a type-parameter or an elaborated-type-specifier.
394193326Sed      // We have to look further.
395193326Sed      break;
396235633Sdim
397235633Sdim    default:
398235633Sdim      return false;
399235633Sdim    }
400199990Srdivacky
401235633Sdim    switch (GetLookAheadToken(2).getKind()) {
402235633Sdim    case tok::equal:
403199990Srdivacky    case tok::comma:
404235633Sdim    case tok::greater:
405235633Sdim    case tok::greatergreater:
406235633Sdim      return true;
407199990Srdivacky
408235633Sdim    default:
409235633Sdim      return false;
410235633Sdim    }
411199990Srdivacky  }
412226890Sdim
413199990Srdivacky  if (Tok.isNot(tok::kw_typename))
414235633Sdim    return false;
415199990Srdivacky
416199990Srdivacky  // C++ [temp.param]p2:
417235633Sdim  //   There is no semantic difference between class and typename in a
418235633Sdim  //   template-parameter. typename followed by an unqualified-id
419199990Srdivacky  //   names a template type parameter. typename followed by a
420235633Sdim  //   qualified-id denotes the type in a non-type
421199990Srdivacky  //   parameter-declaration.
422199990Srdivacky  Token Next = NextToken();
423235633Sdim
424199990Srdivacky  // If we have an identifier, skip over it.
425235633Sdim  if (Next.getKind() == tok::identifier)
426199990Srdivacky    Next = GetLookAheadToken(2);
427235633Sdim
428199990Srdivacky  switch (Next.getKind()) {
429235633Sdim  case tok::equal:
430235633Sdim  case tok::comma:
431235633Sdim  case tok::greater:
432226890Sdim  case tok::greatergreater:
433235633Sdim  case tok::ellipsis:
434226890Sdim    return true;
435199990Srdivacky
436235633Sdim  default:
437199990Srdivacky    return false;
438235633Sdim  }
439235633Sdim}
440235633Sdim
441199990Srdivacky/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
442235633Sdim///
443235633Sdim///       template-parameter: [C++ temp.param]
444199990Srdivacky///         type-parameter
445199990Srdivacky///         parameter-declaration
446199990Srdivacky///
447235633Sdim///       type-parameter: (see below)
448235633Sdim///         'class' ...[opt] identifier[opt]
449235633Sdim///         'class' identifier[opt] '=' type-id
450199990Srdivacky///         'typename' ...[opt] identifier[opt]
451235633Sdim///         'typename' identifier[opt] '=' type-id
452235633Sdim///         'template' '<' template-parameter-list '>'
453235633Sdim///               'class' ...[opt] identifier[opt]
454235633Sdim///         'template' '<' template-parameter-list '>' 'class' identifier[opt]
455235633Sdim///               = id-expression
456235633SdimDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
457235633Sdim  if (isStartOfTemplateTypeParameter())
458235633Sdim    return ParseTypeParameter(Depth, Position);
459235633Sdim
460235633Sdim  if (Tok.is(tok::kw_template))
461235633Sdim    return ParseTemplateTemplateParameter(Depth, Position);
462235633Sdim
463235633Sdim  // If it's none of the above, then it must be a parameter declaration.
464235633Sdim  // NOTE: This will pick up errors in the closure of the template parameter
465235633Sdim  // list (e.g., template < ; Check here to implement >> style closures.
466235633Sdim  return ParseNonTypeTemplateParameter(Depth, Position);
467235633Sdim}
468235633Sdim
469235633Sdim/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
470235633Sdim/// Other kinds of template parameters are parsed in
471235633Sdim/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
472235633Sdim///
473235633Sdim///       type-parameter:     [C++ temp.param]
474235633Sdim///         'class' ...[opt][C++0x] identifier[opt]
475235633Sdim///         'class' identifier[opt] '=' type-id
476235633Sdim///         'typename' ...[opt][C++0x] identifier[opt]
477235633Sdim///         'typename' identifier[opt] '=' type-id
478235633SdimDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
479235633Sdim  assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
480235633Sdim         "A type-parameter starts with 'class' or 'typename'");
481235633Sdim
482235633Sdim  // Consume the 'class' or 'typename' keyword.
483235633Sdim  bool TypenameKeyword = Tok.is(tok::kw_typename);
484235633Sdim  SourceLocation KeyLoc = ConsumeToken();
485235633Sdim
486235633Sdim  // Grab the ellipsis (if given).
487235633Sdim  bool Ellipsis = false;
488235633Sdim  SourceLocation EllipsisLoc;
489235633Sdim  if (Tok.is(tok::ellipsis)) {
490199990Srdivacky    Ellipsis = true;
491199990Srdivacky    EllipsisLoc = ConsumeToken();
492235633Sdim
493235633Sdim    Diag(EllipsisLoc,
494235633Sdim         getLangOpts().CPlusPlus0x
495235633Sdim           ? diag::warn_cxx98_compat_variadic_templates
496235633Sdim           : diag::ext_variadic_templates);
497235633Sdim  }
498235633Sdim
499235633Sdim  // Grab the template parameter name (if given)
500235633Sdim  SourceLocation NameLoc;
501199990Srdivacky  IdentifierInfo* ParamName = 0;
502235633Sdim  if (Tok.is(tok::identifier)) {
503235633Sdim    ParamName = Tok.getIdentifierInfo();
504235633Sdim    NameLoc = ConsumeToken();
505235633Sdim  } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
506235633Sdim             Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
507235633Sdim    // Unnamed template parameter. Don't have to do anything here, just
508235633Sdim    // don't consume this token.
509235633Sdim  } else {
510235633Sdim    Diag(Tok.getLocation(), diag::err_expected_ident);
511235633Sdim    return 0;
512235633Sdim  }
513235633Sdim
514235633Sdim  // Grab a default argument (if available).
515235633Sdim  // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
516235633Sdim  // we introduce the type parameter into the local scope.
517235633Sdim  SourceLocation EqualLoc;
518235633Sdim  ParsedType DefaultArg;
519235633Sdim  if (Tok.is(tok::equal)) {
520235633Sdim    EqualLoc = ConsumeToken();
521235633Sdim    DefaultArg = ParseTypeName(/*Range=*/0,
522235633Sdim                               Declarator::TemplateTypeArgContext).get();
523235633Sdim  }
524235633Sdim
525235633Sdim  return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
526235633Sdim                                    EllipsisLoc, KeyLoc, ParamName, NameLoc,
527235633Sdim                                    Depth, Position, EqualLoc, DefaultArg);
528235633Sdim}
529235633Sdim
530235633Sdim/// ParseTemplateTemplateParameter - Handle the parsing of template
531235633Sdim/// template parameters.
532235633Sdim///
533235633Sdim///       type-parameter:    [C++ temp.param]
534235633Sdim///         'template' '<' template-parameter-list '>' 'class'
535235633Sdim///                  ...[opt] identifier[opt]
536235633Sdim///         'template' '<' template-parameter-list '>' 'class' identifier[opt]
537235633Sdim///                  = id-expression
538235633SdimDecl *
539235633SdimParser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
540235633Sdim  assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
541235633Sdim
542235633Sdim  // Handle the template <...> part.
543235633Sdim  SourceLocation TemplateLoc = ConsumeToken();
544235633Sdim  SmallVector<Decl*,8> TemplateParams;
545235633Sdim  SourceLocation LAngleLoc, RAngleLoc;
546235633Sdim  {
547235633Sdim    ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
548235633Sdim    if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
549235633Sdim                               RAngleLoc)) {
550235633Sdim      return 0;
551235633Sdim    }
552235633Sdim  }
553235633Sdim
554235633Sdim  // Generate a meaningful error if the user forgot to put class before the
555235633Sdim  // identifier, comma, or greater. Provide a fixit if the identifier, comma,
556199990Srdivacky  // or greater appear immediately or after 'typename' or 'struct'. In the
557199990Srdivacky  // latter case, replace the keyword with 'class'.
558193326Sed  if (!Tok.is(tok::kw_class)) {
559193326Sed    bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
560193326Sed    const Token& Next = Replace ? NextToken() : Tok;
561193326Sed    if (Next.is(tok::identifier) || Next.is(tok::comma) ||
562193326Sed        Next.is(tok::greater) || Next.is(tok::greatergreater) ||
563193326Sed        Next.is(tok::ellipsis))
564193326Sed      Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
565193326Sed        << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
566193326Sed                    : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
567193326Sed    else
568193326Sed      Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
569193326Sed
570193326Sed    if (Replace)
571193326Sed      ConsumeToken();
572193326Sed  } else
573218893Sdim    ConsumeToken();
574193326Sed
575193326Sed  // Parse the ellipsis, if given.
576193326Sed  SourceLocation EllipsisLoc;
577193326Sed  if (Tok.is(tok::ellipsis)) {
578193326Sed    EllipsisLoc = ConsumeToken();
579193326Sed
580193326Sed    Diag(EllipsisLoc,
581193326Sed         getLangOpts().CPlusPlus0x
582193326Sed           ? diag::warn_cxx98_compat_variadic_templates
583193326Sed           : diag::ext_variadic_templates);
584193326Sed  }
585193326Sed
586193326Sed  // Get the identifier, if given.
587193326Sed  SourceLocation NameLoc;
588193326Sed  IdentifierInfo* ParamName = 0;
589193326Sed  if (Tok.is(tok::identifier)) {
590193326Sed    ParamName = Tok.getIdentifierInfo();
591193326Sed    NameLoc = ConsumeToken();
592193326Sed  } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
593193326Sed             Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
594193326Sed    // Unnamed template parameter. Don't have to do anything here, just
595193326Sed    // don't consume this token.
596218893Sdim  } else {
597193326Sed    Diag(Tok.getLocation(), diag::err_expected_ident);
598193326Sed    return 0;
599193326Sed  }
600193326Sed
601193326Sed  TemplateParameterList *ParamList =
602193326Sed    Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
603193326Sed                                       TemplateLoc, LAngleLoc,
604193326Sed                                       TemplateParams.data(),
605193326Sed                                       TemplateParams.size(),
606193326Sed                                       RAngleLoc);
607193326Sed
608193326Sed  // Grab a default argument (if available).
609193326Sed  // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
610193326Sed  // we introduce the template parameter into the local scope.
611193326Sed  SourceLocation EqualLoc;
612193326Sed  ParsedTemplateArgument DefaultArg;
613193326Sed  if (Tok.is(tok::equal)) {
614193326Sed    EqualLoc = ConsumeToken();
615193326Sed    DefaultArg = ParseTemplateTemplateArgument();
616193326Sed    if (DefaultArg.isInvalid()) {
617204643Srdivacky      Diag(Tok.getLocation(),
618204643Srdivacky           diag::err_default_template_template_parameter_not_template);
619193326Sed      SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
620193326Sed    }
621218893Sdim  }
622193326Sed
623193326Sed  return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
624193326Sed                                                ParamList, EllipsisLoc,
625193326Sed                                                ParamName, NameLoc, Depth,
626193326Sed                                                Position, EqualLoc, DefaultArg);
627193326Sed}
628193326Sed
629193326Sed/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
630193326Sed/// template parameters (e.g., in "template<int Size> class array;").
631193326Sed///
632193326Sed///       template-parameter:
633193326Sed///         ...
634193326Sed///         parameter-declaration
635193326SedDecl *
636218893SdimParser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
637218893Sdim  // Parse the declaration-specifiers (i.e., the type).
638218893Sdim  // FIXME: The type should probably be restricted in some way... Not all
639198092Srdivacky  // declarators (parts of declarators?) are accepted for parameters.
640198092Srdivacky  DeclSpec DS(AttrFactory);
641198092Srdivacky  ParseDeclarationSpecifiers(DS);
642193326Sed
643198092Srdivacky  // Parse this as a typename.
644198092Srdivacky  Declarator ParamDecl(DS, Declarator::TemplateParamContext);
645245431Sdim  ParseDeclarator(ParamDecl);
646245431Sdim  if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
647193326Sed    Diag(Tok.getLocation(), diag::err_expected_template_parameter);
648193326Sed    return 0;
649193326Sed  }
650193326Sed
651193326Sed  // If there is a default value, parse it.
652235633Sdim  // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
653235633Sdim  // we introduce the template parameter into the local scope.
654193326Sed  SourceLocation EqualLoc;
655193326Sed  ExprResult DefaultArg;
656193326Sed  if (Tok.is(tok::equal)) {
657193326Sed    EqualLoc = ConsumeToken();
658193326Sed
659193326Sed    // C++ [temp.param]p15:
660193326Sed    //   When parsing a default template-argument for a non-type
661193326Sed    //   template-parameter, the first non-nested > is taken as the
662193326Sed    //   end of the template-parameter-list rather than a greater-than
663193326Sed    //   operator.
664218893Sdim    GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
665218893Sdim    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
666218893Sdim
667218893Sdim    DefaultArg = ParseAssignmentExpression();
668218893Sdim    if (DefaultArg.isInvalid())
669226890Sdim      SkipUntil(tok::comma, tok::greater, true, true);
670226890Sdim  }
671193326Sed
672193326Sed  // Create the parameter.
673193326Sed  return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
674193326Sed                                               Depth, Position, EqualLoc,
675193326Sed                                               DefaultArg.take());
676193326Sed}
677193326Sed
678193326Sed/// \brief Parses a template-id that after the template name has
679193326Sed/// already been parsed.
680193326Sed///
681193326Sed/// This routine takes care of parsing the enclosed template argument
682193326Sed/// list ('<' template-parameter-list [opt] '>') and placing the
683193326Sed/// results into a form that can be transferred to semantic analysis.
684193326Sed///
685193326Sed/// \param Template the template declaration produced by isTemplateName
686218893Sdim///
687218893Sdim/// \param TemplateNameLoc the source location of the template name
688218893Sdim///
689218893Sdim/// \param SS if non-NULL, the nested-name-specifier preceding the
690193326Sed/// template name.
691193326Sed///
692193326Sed/// \param ConsumeLastToken if true, then we will consume the last
693193326Sed/// token that forms the template-id. Otherwise, we will leave the
694193326Sed/// last token in the stream (e.g., so that it can be replaced with an
695245431Sdim/// annotation token).
696193326Sedbool
697193326SedParser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
698193326Sed                                         SourceLocation TemplateNameLoc,
699193326Sed                                         const CXXScopeSpec &SS,
700193326Sed                                         bool ConsumeLastToken,
701193326Sed                                         SourceLocation &LAngleLoc,
702193326Sed                                         TemplateArgList &TemplateArgs,
703193326Sed                                         SourceLocation &RAngleLoc) {
704193326Sed  assert(Tok.is(tok::less) && "Must have already parsed the template-name");
705193326Sed
706193326Sed  // Consume the '<'.
707193326Sed  LAngleLoc = ConsumeToken();
708193326Sed
709193326Sed  // Parse the optional template-argument-list.
710193326Sed  bool Invalid = false;
711193326Sed  {
712193326Sed    GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
713193326Sed    if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
714193326Sed      Invalid = ParseTemplateArgumentList(TemplateArgs);
715193326Sed
716193326Sed    if (Invalid) {
717218893Sdim      // Try to find the closing '>'.
718218893Sdim      SkipUntil(tok::greater, true, !ConsumeLastToken);
719218893Sdim
720218893Sdim      return true;
721218893Sdim    }
722218893Sdim  }
723226890Sdim
724226890Sdim  // What will be left once we've consumed the '>'.
725226890Sdim  tok::TokenKind RemainingToken;
726218893Sdim  const char *ReplacementStr = "> >";
727218893Sdim
728226890Sdim  switch (Tok.getKind()) {
729226890Sdim  default:
730226890Sdim    Diag(Tok.getLocation(), diag::err_expected_greater);
731218893Sdim    return true;
732218893Sdim
733218893Sdim  case tok::greater:
734218893Sdim    // Determine the location of the '>' token. Only consume this token
735218893Sdim    // if the caller asked us to.
736218893Sdim    RAngleLoc = Tok.getLocation();
737218893Sdim    if (ConsumeLastToken)
738218893Sdim      ConsumeToken();
739218893Sdim    return false;
740218893Sdim
741218893Sdim  case tok::greatergreater:
742218893Sdim    RemainingToken = tok::greater;
743218893Sdim    break;
744218893Sdim
745218893Sdim  case tok::greatergreatergreater:
746218893Sdim    RemainingToken = tok::greatergreater;
747218893Sdim    break;
748218893Sdim
749218893Sdim  case tok::greaterequal:
750218893Sdim    RemainingToken = tok::equal;
751218893Sdim    ReplacementStr = "> =";
752218893Sdim    break;
753218893Sdim
754218893Sdim  case tok::greatergreaterequal:
755218893Sdim    RemainingToken = tok::greaterequal;
756218893Sdim    break;
757218893Sdim  }
758218893Sdim
759245431Sdim  // This template-id is terminated by a token which starts with a '>'. Outside
760218893Sdim  // C++11, this is now error recovery, and in C++11, this is error recovery if
761218893Sdim  // the token isn't '>>'.
762218893Sdim
763218893Sdim  RAngleLoc = Tok.getLocation();
764218893Sdim
765218893Sdim  // The source range of the '>>' or '>=' at the start of the token.
766218893Sdim  CharSourceRange ReplacementRange =
767218893Sdim      CharSourceRange::getCharRange(RAngleLoc,
768218893Sdim          Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
769245431Sdim                                         getLangOpts()));
770218893Sdim
771218893Sdim  // A hint to put a space between the '>>'s. In order to make the hint as
772218893Sdim  // clear as possible, we include the characters either side of the space in
773218893Sdim  // the replacement, rather than just inserting a space at SecondCharLoc.
774218893Sdim  FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
775218893Sdim                                                 ReplacementStr);
776218893Sdim
777218893Sdim  // A hint to put another space after the token, if it would otherwise be
778218893Sdim  // lexed differently.
779218893Sdim  FixItHint Hint2;
780218893Sdim  Token Next = NextToken();
781218893Sdim  if ((RemainingToken == tok::greater ||
782218893Sdim       RemainingToken == tok::greatergreater) &&
783218893Sdim      (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
784218893Sdim       Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
785245431Sdim       Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
786235633Sdim       Next.is(tok::equalequal)) &&
787221345Sdim      areTokensAdjacent(Tok, Next))
788221345Sdim    Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
789218893Sdim
790218893Sdim  unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
791221345Sdim  if (getLangOpts().CPlusPlus0x && Tok.is(tok::greatergreater))
792235633Sdim    DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
793235633Sdim  else if (Tok.is(tok::greaterequal))
794223017Sdim    DiagId = diag::err_right_angle_bracket_equal_needs_space;
795218893Sdim  Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
796218893Sdim
797218893Sdim  // Strip the initial '>' from the token.
798218893Sdim  if (RemainingToken == tok::equal && Next.is(tok::equal) &&
799218893Sdim      areTokensAdjacent(Tok, Next)) {
800218893Sdim    // Join two adjacent '=' tokens into one, for cases like:
801218893Sdim    //   void (*p)() = f<int>;
802218893Sdim    //   return f<int>==p;
803218893Sdim    ConsumeToken();
804226890Sdim    Tok.setKind(tok::equalequal);
805218893Sdim    Tok.setLength(Tok.getLength() + 1);
806218893Sdim  } else {
807218893Sdim    Tok.setKind(RemainingToken);
808221345Sdim    Tok.setLength(Tok.getLength() - 1);
809235633Sdim  }
810218893Sdim  Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
811218893Sdim                                                 PP.getSourceManager(),
812218893Sdim                                                 getLangOpts()));
813218893Sdim
814218893Sdim  if (!ConsumeLastToken) {
815218893Sdim    // Since we're not supposed to consume the '>' token, we need to push
816218893Sdim    // this token and revert the current token back to the '>'.
817218893Sdim    PP.EnterToken(Tok);
818218893Sdim    Tok.setKind(tok::greater);
819218893Sdim    Tok.setLength(1);
820218893Sdim    Tok.setLocation(RAngleLoc);
821218893Sdim  }
822218893Sdim
823218893Sdim  return false;
824218893Sdim}
825223017Sdim
826218893Sdim/// \brief Replace the tokens that form a simple-template-id with an
827218893Sdim/// annotation token containing the complete template-id.
828218893Sdim///
829218893Sdim/// The first token in the stream must be the name of a template that
830218893Sdim/// is followed by a '<'. This routine will parse the complete
831218893Sdim/// simple-template-id and replace the tokens with a single annotation
832218893Sdim/// token with one of two different kinds: if the template-id names a
833218893Sdim/// type (and \p AllowTypeAnnotation is true), the annotation token is
834218893Sdim/// a type annotation that includes the optional nested-name-specifier
835218893Sdim/// (\p SS). Otherwise, the annotation token is a template-id
836226890Sdim/// annotation that does not include the optional
837218893Sdim/// nested-name-specifier.
838218893Sdim///
839226890Sdim/// \param Template  the declaration of the template named by the first
840218893Sdim/// token (an identifier), as returned from \c Action::isTemplateName().
841218893Sdim///
842218893Sdim/// \param TemplateNameKind the kind of template that \p Template
843218893Sdim/// refers to, as returned from \c Action::isTemplateName().
844218893Sdim///
845218893Sdim/// \param SS if non-NULL, the nested-name-specifier that precedes
846218893Sdim/// this template name.
847218893Sdim///
848218893Sdim/// \param TemplateKWLoc if valid, specifies that this template-id
849245431Sdim/// annotation was preceded by the 'template' keyword and gives the
850245431Sdim/// location of that keyword. If invalid (the default), then this
851245431Sdim/// template-id was not preceded by a 'template' keyword.
852245431Sdim///
853245431Sdim/// \param AllowTypeAnnotation if true (the default), then a
854245431Sdim/// simple-template-id that refers to a class template, template
855193326Sed/// template parameter, or other template that produces a type will be
856193326Sed/// replaced with a type annotation token. Otherwise, the
857193326Sed/// simple-template-id is always replaced with a template-id
858193326Sed/// annotation token.
859193326Sed///
860245431Sdim/// If an unrecoverable parse error occurs and no annotation token can be
861245431Sdim/// formed, this function returns true.
862245431Sdim///
863245431Sdimbool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
864245431Sdim                                     CXXScopeSpec &SS,
865245431Sdim                                     SourceLocation TemplateKWLoc,
866245431Sdim                                     UnqualifiedId &TemplateName,
867193326Sed                                     bool AllowTypeAnnotation) {
868193326Sed  assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
869193326Sed  assert(Template && Tok.is(tok::less) &&
870193326Sed         "Parser isn't at the beginning of a template-id");
871193326Sed
872193326Sed  // Consume the template-name.
873198954Srdivacky  SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
874193326Sed
875193326Sed  // Parse the enclosed template argument list.
876193326Sed  SourceLocation LAngleLoc, RAngleLoc;
877193326Sed  TemplateArgList TemplateArgs;
878193326Sed  bool Invalid = ParseTemplateIdAfterTemplateName(Template,
879193326Sed                                                  TemplateNameLoc,
880193326Sed                                                  SS, false, LAngleLoc,
881193326Sed                                                  TemplateArgs,
882193326Sed                                                  RAngleLoc);
883193326Sed
884193326Sed  if (Invalid) {
885193326Sed    // If we failed to parse the template ID but skipped ahead to a >, we're not
886193326Sed    // going to be able to form a token annotation.  Eat the '>' if present.
887193326Sed    if (Tok.is(tok::greater))
888193326Sed      ConsumeToken();
889193326Sed    return true;
890193326Sed  }
891193326Sed
892193326Sed  ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
893193326Sed
894193326Sed  // Build the annotation token.
895193326Sed  if (TNK == TNK_Type_template && AllowTypeAnnotation) {
896193326Sed    TypeResult Type
897193326Sed      = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
898193326Sed                                    Template, TemplateNameLoc,
899193326Sed                                    LAngleLoc, TemplateArgsPtr, RAngleLoc);
900193326Sed    if (Type.isInvalid()) {
901193326Sed      // If we failed to parse the template ID but skipped ahead to a >, we're not
902193326Sed      // going to be able to form a token annotation.  Eat the '>' if present.
903193326Sed      if (Tok.is(tok::greater))
904193326Sed        ConsumeToken();
905193326Sed      return true;
906193326Sed    }
907193326Sed
908193326Sed    Tok.setKind(tok::annot_typename);
909193326Sed    setTypeAnnotation(Tok, Type.get());
910193326Sed    if (SS.isNotEmpty())
911193326Sed      Tok.setLocation(SS.getBeginLoc());
912193326Sed    else if (TemplateKWLoc.isValid())
913193326Sed      Tok.setLocation(TemplateKWLoc);
914193326Sed    else
915193326Sed      Tok.setLocation(TemplateNameLoc);
916193326Sed  } else {
917193326Sed    // Build a template-id annotation token that can be processed
918195099Sed    // later.
919193326Sed    Tok.setKind(tok::annot_template_id);
920193326Sed    TemplateIdAnnotation *TemplateId
921193326Sed      = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
922193326Sed    TemplateId->TemplateNameLoc = TemplateNameLoc;
923193326Sed    if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
924193326Sed      TemplateId->Name = TemplateName.Identifier;
925193326Sed      TemplateId->Operator = OO_None;
926193326Sed    } else {
927193326Sed      TemplateId->Name = 0;
928193326Sed      TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
929193326Sed    }
930193326Sed    TemplateId->SS = SS;
931193326Sed    TemplateId->TemplateKWLoc = TemplateKWLoc;
932193326Sed    TemplateId->Template = Template;
933193326Sed    TemplateId->Kind = TNK;
934193326Sed    TemplateId->LAngleLoc = LAngleLoc;
935193326Sed    TemplateId->RAngleLoc = RAngleLoc;
936193326Sed    ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
937193326Sed    for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
938193326Sed      Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
939193326Sed    Tok.setAnnotationValue(TemplateId);
940193326Sed    if (TemplateKWLoc.isValid())
941193326Sed      Tok.setLocation(TemplateKWLoc);
942193326Sed    else
943193326Sed      Tok.setLocation(TemplateNameLoc);
944193326Sed  }
945193326Sed
946193326Sed  // Common fields for the annotation token
947193326Sed  Tok.setAnnotationEndLoc(RAngleLoc);
948193326Sed
949193326Sed  // In case the tokens were cached, have Preprocessor replace them with the
950193326Sed  // annotation token.
951193326Sed  PP.AnnotateCachedTokens(Tok);
952193326Sed  return false;
953193326Sed}
954193326Sed
955193326Sed/// \brief Replaces a template-id annotation token with a type
956193326Sed/// annotation token.
957235633Sdim///
958245431Sdim/// If there was a failure when forming the type from the template-id,
959245431Sdim/// a type annotation token will still be created, but will have a
960193326Sed/// NULL type pointer to signify an error.
961245431Sdimvoid Parser::AnnotateTemplateIdTokenAsType() {
962203955Srdivacky  assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
963203955Srdivacky
964203955Srdivacky  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
965203955Srdivacky  assert((TemplateId->Kind == TNK_Type_template ||
966245431Sdim          TemplateId->Kind == TNK_Dependent_template_name) &&
967245431Sdim         "Only works for type and dependent templates");
968245431Sdim
969245431Sdim  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
970245431Sdim                                     TemplateId->NumArgs);
971245431Sdim
972245431Sdim  TypeResult Type
973245431Sdim    = Actions.ActOnTemplateIdType(TemplateId->SS,
974245431Sdim                                  TemplateId->TemplateKWLoc,
975245431Sdim                                  TemplateId->Template,
976245431Sdim                                  TemplateId->TemplateNameLoc,
977245431Sdim                                  TemplateId->LAngleLoc,
978245431Sdim                                  TemplateArgsPtr,
979245431Sdim                                  TemplateId->RAngleLoc);
980245431Sdim  // Create the new "type" annotation token.
981245431Sdim  Tok.setKind(tok::annot_typename);
982245431Sdim  setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
983245431Sdim  if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
984245431Sdim    Tok.setLocation(TemplateId->SS.getBeginLoc());
985245431Sdim  // End location stays the same
986245431Sdim
987245431Sdim  // Replace the template-id annotation token, and possible the scope-specifier
988245431Sdim  // that precedes it, with the typename annotation token.
989245431Sdim  PP.AnnotateCachedTokens(Tok);
990245431Sdim}
991245431Sdim
992245431Sdim/// \brief Determine whether the given token can end a template argument.
993245431Sdimstatic bool isEndOfTemplateArgument(Token Tok) {
994245431Sdim  return Tok.is(tok::comma) || Tok.is(tok::greater) ||
995245431Sdim         Tok.is(tok::greatergreater);
996245431Sdim}
997245431Sdim
998245431Sdim/// \brief Parse a C++ template template argument.
999245431SdimParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1000245431Sdim  if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1001245431Sdim      !Tok.is(tok::annot_cxxscope))
1002245431Sdim    return ParsedTemplateArgument();
1003245431Sdim
1004245431Sdim  // C++0x [temp.arg.template]p1:
1005245431Sdim  //   A template-argument for a template template-parameter shall be the name
1006245431Sdim  //   of a class template or an alias template, expressed as id-expression.
1007245431Sdim  //
1008245431Sdim  // We parse an id-expression that refers to a class template or alias
1009245431Sdim  // template. The grammar we parse is:
1010245431Sdim  //
1011245431Sdim  //   nested-name-specifier[opt] template[opt] identifier ...[opt]
1012245431Sdim  //
1013245431Sdim  // followed by a token that terminates a template argument, such as ',',
1014193326Sed  // '>', or (in some cases) '>>'.
1015193326Sed  CXXScopeSpec SS; // nested-name-specifier, if present
1016193326Sed  ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1017193326Sed                                 /*EnteringContext=*/false);
1018204643Srdivacky
1019245431Sdim  ParsedTemplateArgument Result;
1020193326Sed  SourceLocation EllipsisLoc;
1021201361Srdivacky  if (SS.isSet() && Tok.is(tok::kw_template)) {
1022201361Srdivacky    // Parse the optional 'template' keyword following the
1023201361Srdivacky    // nested-name-specifier.
1024201361Srdivacky    SourceLocation TemplateKWLoc = ConsumeToken();
1025201361Srdivacky
1026235633Sdim    if (Tok.is(tok::identifier)) {
1027235633Sdim      // We appear to have a dependent template name.
1028235633Sdim      UnqualifiedId Name;
1029193326Sed      Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1030193326Sed      ConsumeToken(); // the identifier
1031193326Sed
1032204643Srdivacky      // Parse the ellipsis.
1033245431Sdim      if (Tok.is(tok::ellipsis))
1034235633Sdim        EllipsisLoc = ConsumeToken();
1035193326Sed
1036193326Sed      // If the next token signals the end of a template argument,
1037193326Sed      // then we have a dependent template name that could be a template
1038193326Sed      // template argument.
1039193326Sed      TemplateTy Template;
1040193326Sed      if (isEndOfTemplateArgument(Tok) &&
1041198954Srdivacky          Actions.ActOnDependentTemplateName(getCurScope(),
1042193326Sed                                             SS, TemplateKWLoc, Name,
1043193326Sed                                             /*ObjectType=*/ ParsedType(),
1044198954Srdivacky                                             /*EnteringContext=*/false,
1045193326Sed                                             Template))
1046193326Sed        Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1047193326Sed    }
1048193326Sed  } else if (Tok.is(tok::identifier)) {
1049193326Sed    // We may have a (non-dependent) template name.
1050193326Sed    TemplateTy Template;
1051193326Sed    UnqualifiedId Name;
1052193326Sed    Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1053193326Sed    ConsumeToken(); // the identifier
1054193326Sed
1055193326Sed    // Parse the ellipsis.
1056193326Sed    if (Tok.is(tok::ellipsis))
1057226890Sdim      EllipsisLoc = ConsumeToken();
1058226890Sdim
1059226890Sdim    if (isEndOfTemplateArgument(Tok)) {
1060193326Sed      bool MemberOfUnknownSpecialization;
1061193326Sed      TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1062193326Sed                                               /*hasTemplateKeyword=*/false,
1063193326Sed                                                    Name,
1064193326Sed                                               /*ObjectType=*/ ParsedType(),
1065193326Sed                                                    /*EnteringContext=*/false,
1066193326Sed                                                    Template,
1067193326Sed                                                MemberOfUnknownSpecialization);
1068193326Sed      if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1069193326Sed        // We have an id-expression that refers to a class template or
1070193326Sed        // (C++0x) alias template.
1071193326Sed        Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1072193326Sed      }
1073193326Sed    }
1074193326Sed  }
1075193326Sed
1076193326Sed  // If this is a pack expansion, build it as such.
1077193326Sed  if (EllipsisLoc.isValid() && !Result.isInvalid())
1078193326Sed    Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1079193326Sed
1080193326Sed  return Result;
1081193326Sed}
1082193326Sed
1083193326Sed/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1084198092Srdivacky///
1085193326Sed///       template-argument: [C++ 14.2]
1086193326Sed///         constant-expression
1087193326Sed///         type-id
1088193326Sed///         id-expression
1089193326SedParsedTemplateArgument Parser::ParseTemplateArgument() {
1090208600Srdivacky  // C++ [temp.arg]p2:
1091194179Sed  //   In a template-argument, an ambiguity between a type-id and an
1092194179Sed  //   expression is resolved to a type-id, regardless of the form of
1093226890Sdim  //   the corresponding template-parameter.
1094194179Sed  //
1095226890Sdim  // Therefore, we initially try to parse a type-id.
1096194179Sed  if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1097212904Sdim    SourceLocation Loc = Tok.getLocation();
1098212904Sdim    TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1099212904Sdim                                       Declarator::TemplateTypeArgContext);
1100212904Sdim    if (TypeArg.isInvalid())
1101203955Srdivacky      return ParsedTemplateArgument();
1102203955Srdivacky
1103203955Srdivacky    return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1104203955Srdivacky                                  TypeArg.get().getAsOpaquePtr(),
1105193326Sed                                  Loc);
1106207619Srdivacky  }
1107224145Sdim
1108207619Srdivacky  // Try to parse a template template argument.
1109207619Srdivacky  {
1110207619Srdivacky    TentativeParsingAction TPA(*this);
1111221345Sdim
1112207619Srdivacky    ParsedTemplateArgument TemplateTemplateArgument
1113207619Srdivacky      = ParseTemplateTemplateArgument();
1114207619Srdivacky    if (!TemplateTemplateArgument.isInvalid()) {
1115207619Srdivacky      TPA.Commit();
1116201361Srdivacky      return TemplateTemplateArgument;
1117201361Srdivacky    }
1118204643Srdivacky
1119204643Srdivacky    // Revert this tentative parse to parse a non-type template argument.
1120235633Sdim    TPA.Revert();
1121235633Sdim  }
1122235633Sdim
1123235633Sdim  // Parse a non-type template argument.
1124235633Sdim  SourceLocation Loc = Tok.getLocation();
1125235633Sdim  ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1126235633Sdim  if (ExprArg.isInvalid() || !ExprArg.get())
1127235633Sdim    return ParsedTemplateArgument();
1128235633Sdim
1129235633Sdim  return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1130235633Sdim                                ExprArg.release(), Loc);
1131235633Sdim}
1132235633Sdim
1133235633Sdim/// \brief Determine whether the current tokens can only be parsed as a
1134235633Sdim/// template argument list (starting with the '<') and never as a '<'
1135245431Sdim/// expression.
1136245431Sdimbool Parser::IsTemplateArgumentList(unsigned Skip) {
1137235633Sdim  struct AlwaysRevertAction : TentativeParsingAction {
1138235633Sdim    AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1139235633Sdim    ~AlwaysRevertAction() { Revert(); }
1140235633Sdim  } Tentative(*this);
1141235633Sdim
1142245431Sdim  while (Skip) {
1143245431Sdim    ConsumeToken();
1144245431Sdim    --Skip;
1145245431Sdim  }
1146245431Sdim
1147245431Sdim  // '<'
1148245431Sdim  if (!Tok.is(tok::less))
1149245431Sdim    return false;
1150245431Sdim  ConsumeToken();
1151245431Sdim
1152245431Sdim  // An empty template argument list.
1153245431Sdim  if (Tok.is(tok::greater))
1154245431Sdim    return true;
1155245431Sdim
1156245431Sdim  // See whether we have declaration specifiers, which indicate a type.
1157245431Sdim  while (isCXXDeclarationSpecifier() == TPResult::True())
1158245431Sdim    ConsumeToken();
1159245431Sdim
1160245431Sdim  // If we have a '>' or a ',' then this is a template argument list.
1161245431Sdim  return Tok.is(tok::greater) || Tok.is(tok::comma);
1162245431Sdim}
1163245431Sdim
1164245431Sdim/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1165245431Sdim/// (C++ [temp.names]). Returns true if there was an error.
1166245431Sdim///
1167245431Sdim///       template-argument-list: [C++ 14.2]
1168245431Sdim///         template-argument
1169245431Sdim///         template-argument-list ',' template-argument
1170245431Sdimbool
1171235633SdimParser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1172235633Sdim  while (true) {
1173201361Srdivacky    ParsedTemplateArgument Arg = ParseTemplateArgument();
1174235633Sdim    if (Tok.is(tok::ellipsis)) {
1175201361Srdivacky      SourceLocation EllipsisLoc  = ConsumeToken();
1176201361Srdivacky      Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1177193326Sed    }
1178193326Sed
1179193326Sed    if (Arg.isInvalid()) {
1180193326Sed      SkipUntil(tok::comma, tok::greater, true, true);
1181193326Sed      return true;
1182193326Sed    }
1183193326Sed
1184193326Sed    // Save this template argument.
1185193326Sed    TemplateArgs.push_back(Arg);
1186193326Sed
1187193326Sed    // If the next token is a comma, consume it and keep reading
1188193326Sed    // arguments.
1189193326Sed    if (Tok.isNot(tok::comma)) break;
1190193326Sed
1191193326Sed    // Consume the comma.
1192193326Sed    ConsumeToken();
1193193326Sed  }
1194193326Sed
1195218893Sdim  return false;
1196218893Sdim}
1197218893Sdim
1198235633Sdim/// \brief Parse a C++ explicit template instantiation
1199218893Sdim/// (C++ [temp.explicit]).
1200218893Sdim///
1201218893Sdim///       explicit-instantiation:
1202218893Sdim///         'extern' [opt] 'template' declaration
1203218893Sdim///
1204218893Sdim/// Note that the 'extern' is a GNU extension and C++0x feature.
1205235633SdimDecl *Parser::ParseExplicitInstantiation(unsigned Context,
1206218893Sdim                                         SourceLocation ExternLoc,
1207218893Sdim                                         SourceLocation TemplateLoc,
1208218893Sdim                                         SourceLocation &DeclEnd,
1209218893Sdim                                         AccessSpecifier AS) {
1210218893Sdim  // This isn't really required here.
1211218893Sdim  ParsingDeclRAIIObject
1212218893Sdim    ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1213218893Sdim
1214235633Sdim  return ParseSingleDeclarationAfterTemplate(Context,
1215235633Sdim                                             ParsedTemplateInfo(ExternLoc,
1216235633Sdim                                                                TemplateLoc),
1217218893Sdim                                             ParsingTemplateParams,
1218218893Sdim                                             DeclEnd, AS);
1219218893Sdim}
1220218893Sdim
1221193326SedSourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1222193326Sed  if (TemplateParams)
1223198092Srdivacky    return getTemplateParamsRange(TemplateParams->data(),
1224198092Srdivacky                                  TemplateParams->size());
1225193326Sed
1226193326Sed  SourceRange R(TemplateLoc);
1227193326Sed  if (ExternLoc.isValid())
1228193326Sed    R.setBegin(ExternLoc);
1229221345Sdim  return R;
1230235633Sdim}
1231193326Sed
1232193326Sedvoid Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
1233226890Sdim  ((Parser*)P)->LateTemplateParser(FD);
1234193326Sed}
1235193326Sed
1236193326Sed
1237235633Sdimvoid Parser::LateTemplateParser(const FunctionDecl *FD) {
1238193326Sed  LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1239193326Sed  if (LPT) {
1240193326Sed    ParseLateTemplatedFuncDef(*LPT);
1241235633Sdim    return;
1242235633Sdim  }
1243235633Sdim
1244235633Sdim  llvm_unreachable("Late templated function without associated lexed tokens");
1245235633Sdim}
1246235633Sdim
1247235633Sdim/// \brief Late parse a C++ function template in Microsoft mode.
1248235633Sdimvoid Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1249235633Sdim  if(!LMT.D)
1250218893Sdim     return;
1251218893Sdim
1252218893Sdim  // Get the FunctionDecl.
1253193326Sed  FunctionDecl *FD = 0;
1254193326Sed  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
1255195099Sed    FD = FunTmpl->getTemplatedDecl();
1256193326Sed  else
1257193326Sed    FD = cast<FunctionDecl>(LMT.D);
1258193326Sed
1259193326Sed  // To restore the context after late parsing.
1260193326Sed  Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1261193326Sed
1262193326Sed  SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1263193326Sed  DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
1264235633Sdim  if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1265193326Sed    TemplateParamScopeStack.push_back(new ParseScope(this, Scope::TemplateParamScope));
1266193326Sed    Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1267193326Sed    Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1268193326Sed  } else {
1269193326Sed    // Get the list of DeclContext to reenter.
1270193326Sed    SmallVector<DeclContext*, 4> DeclContextToReenter;
1271193326Sed    DeclContext *DD = FD->getLexicalParent();
1272193326Sed    while (DD && !DD->isTranslationUnit()) {
1273193326Sed      DeclContextToReenter.push_back(DD);
1274235633Sdim      DD = DD->getLexicalParent();
1275235633Sdim    }
1276235633Sdim
1277193326Sed    // Reenter template scopes from outmost to innermost.
1278193326Sed    SmallVector<DeclContext*, 4>::reverse_iterator II =
1279193326Sed    DeclContextToReenter.rbegin();
1280223017Sdim    for (; II != DeclContextToReenter.rend(); ++II) {
1281223017Sdim      if (ClassTemplatePartialSpecializationDecl* MD =
1282223017Sdim                dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
1283223017Sdim        TemplateParamScopeStack.push_back(new ParseScope(this,
1284235633Sdim                                                   Scope::TemplateParamScope));
1285226890Sdim        Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1286226890Sdim      } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
1287226890Sdim        TemplateParamScopeStack.push_back(new ParseScope(this,
1288193326Sed                                                    Scope::TemplateParamScope,
1289193326Sed                                       MD->getDescribedClassTemplate() != 0 ));
1290193326Sed        Actions.ActOnReenterTemplateScope(getCurScope(),
1291193326Sed                                          MD->getDescribedClassTemplate());
1292193326Sed      }
1293193326Sed      TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1294193326Sed      Actions.PushDeclContext(Actions.getCurScope(), *II);
1295193326Sed    }
1296193326Sed    TemplateParamScopeStack.push_back(new ParseScope(this,
1297193326Sed                                      Scope::TemplateParamScope));
1298193326Sed    Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1299193326Sed  }
1300193326Sed
1301193326Sed  assert(!LMT.Toks.empty() && "Empty body!");
1302193326Sed
1303193326Sed  // Append the current token at the end of the new token stream so that it
1304193326Sed  // doesn't get lost.
1305193326Sed  LMT.Toks.push_back(Tok);
1306193326Sed  PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1307193326Sed
1308193326Sed  // Consume the previously pushed token.
1309193326Sed  ConsumeAnyToken();
1310218893Sdim  assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1311218893Sdim         && "Inline method not starting with '{', ':' or 'try'");
1312218893Sdim
1313218893Sdim  // Parse the method body. Function body parsing code is similar enough
1314218893Sdim  // to be re-used for method bodies as well.
1315218893Sdim  ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1316218893Sdim
1317218893Sdim  // Recreate the containing function DeclContext.
1318218893Sdim  Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FD));
1319218893Sdim
1320218893Sdim  if (FunctionTemplateDecl *FunctionTemplate
1321218893Sdim        = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
1322218893Sdim    Actions.ActOnStartOfFunctionDef(getCurScope(),
1323218893Sdim                                   FunctionTemplate->getTemplatedDecl());
1324218893Sdim  if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
1325218893Sdim    Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
1326218893Sdim
1327218893Sdim
1328218893Sdim  if (Tok.is(tok::kw_try)) {
1329218893Sdim    ParseFunctionTryBlock(LMT.D, FnScope);
1330218893Sdim  } else {
1331218893Sdim    if (Tok.is(tok::colon))
1332218893Sdim      ParseConstructorInitializer(LMT.D);
1333218893Sdim    else
1334245431Sdim      Actions.ActOnDefaultCtorInitializers(LMT.D);
1335245431Sdim
1336245431Sdim    if (Tok.is(tok::l_brace)) {
1337245431Sdim      ParseFunctionStatementBody(LMT.D, FnScope);
1338193326Sed      Actions.MarkAsLateParsedTemplate(FD, false);
1339193326Sed    } else
1340193326Sed      Actions.ActOnFinishFunctionBody(LMT.D, 0);
1341193326Sed  }
1342193326Sed
1343218893Sdim  // Exit scopes.
1344245431Sdim  FnScope.Exit();
1345245431Sdim  SmallVector<ParseScope*, 4>::reverse_iterator I =
1346193326Sed   TemplateParamScopeStack.rbegin();
1347218893Sdim  for (; I != TemplateParamScopeStack.rend(); ++I)
1348235633Sdim    delete *I;
1349218893Sdim
1350218893Sdim  DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1351198092Srdivacky  if (grp)
1352193326Sed    Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
1353193326Sed}
1354193326Sed
1355193326Sed/// \brief Lex a delayed template function for late parsing.
1356193326Sedvoid Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1357193326Sed  tok::TokenKind kind = Tok.getKind();
1358193326Sed  if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1359193326Sed    // Consume everything up to (and including) the matching right brace.
1360193326Sed    ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1361193326Sed  }
1362193326Sed
1363193326Sed  // If we're in a function-try-block, we need to store all the catch blocks.
1364193326Sed  if (kind == tok::kw_try) {
1365245431Sdim    while (Tok.is(tok::kw_catch)) {
1366193326Sed      ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1367193326Sed      ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1368193326Sed    }
1369193326Sed  }
1370193326Sed}
1371193326Sed