ParseTemplate.cpp revision 226890
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"
16212904Sdim#include "clang/Sema/DeclSpec.h"
17212904Sdim#include "clang/Sema/ParsedTemplate.h"
18212904Sdim#include "clang/Sema/Scope.h"
19200583Srdivacky#include "RAIIObjectsForParser.h"
20221345Sdim#include "clang/AST/DeclTemplate.h"
21221345Sdim#include "clang/AST/ASTConsumer.h"
22193326Sedusing namespace clang;
23193326Sed
24193326Sed/// \brief Parse a template declaration, explicit instantiation, or
25193326Sed/// explicit specialization.
26212904SdimDecl *
27193326SedParser::ParseDeclarationStartingWithTemplate(unsigned Context,
28193326Sed                                             SourceLocation &DeclEnd,
29226890Sdim                                             AccessSpecifier AS,
30226890Sdim                                             AttributeList *AccessAttrs) {
31226890Sdim  ObjCDeclContextSwitch ObjCDC(*this);
32226890Sdim
33226890Sdim  if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
34198092Srdivacky    return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(),
35226890Sdim                                           DeclEnd);
36226890Sdim  }
37226890Sdim  return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
38226890Sdim                                                  AccessAttrs);
39193326Sed}
40193326Sed
41198092Srdivacky/// \brief RAII class that manages the template parameter depth.
42198092Srdivackynamespace {
43199990Srdivacky  class TemplateParameterDepthCounter {
44198092Srdivacky    unsigned &Depth;
45198092Srdivacky    unsigned AddedLevels;
46198092Srdivacky
47198092Srdivacky  public:
48198092Srdivacky    explicit TemplateParameterDepthCounter(unsigned &Depth)
49198092Srdivacky      : Depth(Depth), AddedLevels(0) { }
50198092Srdivacky
51198092Srdivacky    ~TemplateParameterDepthCounter() {
52198092Srdivacky      Depth -= AddedLevels;
53198092Srdivacky    }
54198092Srdivacky
55198092Srdivacky    void operator++() {
56198092Srdivacky      ++Depth;
57198092Srdivacky      ++AddedLevels;
58198092Srdivacky    }
59198092Srdivacky
60198092Srdivacky    operator unsigned() const { return Depth; }
61198092Srdivacky  };
62198092Srdivacky}
63198092Srdivacky
64193326Sed/// \brief Parse a template declaration or an explicit specialization.
65193326Sed///
66193326Sed/// Template declarations include one or more template parameter lists
67193326Sed/// and either the function or class template declaration. Explicit
68193326Sed/// specializations contain one or more 'template < >' prefixes
69193326Sed/// followed by a (possibly templated) declaration. Since the
70193326Sed/// syntactic form of both features is nearly identical, we parse all
71193326Sed/// of the template headers together and let semantic analysis sort
72193326Sed/// the declarations from the explicit specializations.
73193326Sed///
74193326Sed///       template-declaration: [C++ temp]
75193326Sed///         'export'[opt] 'template' '<' template-parameter-list '>' declaration
76193326Sed///
77193326Sed///       explicit-specialization: [ C++ temp.expl.spec]
78193326Sed///         'template' '<' '>' declaration
79212904SdimDecl *
80193326SedParser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
81193326Sed                                                 SourceLocation &DeclEnd,
82226890Sdim                                                 AccessSpecifier AS,
83226890Sdim                                                 AttributeList *AccessAttrs) {
84198092Srdivacky  assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
85198092Srdivacky         "Token does not start a template declaration.");
86198092Srdivacky
87193326Sed  // Enter template-parameter scope.
88193326Sed  ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
89193326Sed
90212904Sdim  // Tell the action that names should be checked in the context of
91212904Sdim  // the declaration to come.
92212904Sdim  ParsingDeclRAIIObject ParsingTemplateParams(*this);
93212904Sdim
94193326Sed  // Parse multiple levels of template headers within this template
95193326Sed  // parameter scope, e.g.,
96193326Sed  //
97193326Sed  //   template<typename T>
98193326Sed  //     template<typename U>
99193326Sed  //       class A<T>::B { ... };
100193326Sed  //
101193326Sed  // We parse multiple levels non-recursively so that we can build a
102193326Sed  // single data structure containing all of the template parameter
103193326Sed  // lists to easily differentiate between the case above and:
104193326Sed  //
105193326Sed  //   template<typename T>
106193326Sed  //   class A {
107193326Sed  //     template<typename U> class B;
108193326Sed  //   };
109193326Sed  //
110193326Sed  // In the first case, the action for declaring A<T>::B receives
111193326Sed  // both template parameter lists. In the second case, the action for
112193326Sed  // defining A<T>::B receives just the inner template parameter list
113193326Sed  // (and retrieves the outer template parameter list from its
114193326Sed  // context).
115198092Srdivacky  bool isSpecialization = true;
116198893Srdivacky  bool LastParamListWasEmpty = false;
117193326Sed  TemplateParameterLists ParamLists;
118198092Srdivacky  TemplateParameterDepthCounter Depth(TemplateParameterDepth);
119193326Sed  do {
120193326Sed    // Consume the 'export', if any.
121193326Sed    SourceLocation ExportLoc;
122193326Sed    if (Tok.is(tok::kw_export)) {
123193326Sed      ExportLoc = ConsumeToken();
124193326Sed    }
125193326Sed
126193326Sed    // Consume the 'template', which should be here.
127193326Sed    SourceLocation TemplateLoc;
128193326Sed    if (Tok.is(tok::kw_template)) {
129193326Sed      TemplateLoc = ConsumeToken();
130193326Sed    } else {
131193326Sed      Diag(Tok.getLocation(), diag::err_expected_template);
132212904Sdim      return 0;
133193326Sed    }
134198092Srdivacky
135193326Sed    // Parse the '<' template-parameter-list '>'
136193326Sed    SourceLocation LAngleLoc, RAngleLoc;
137226890Sdim    SmallVector<Decl*, 4> TemplateParams;
138198092Srdivacky    if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
139198092Srdivacky                                RAngleLoc)) {
140198092Srdivacky      // Skip until the semi-colon or a }.
141198092Srdivacky      SkipUntil(tok::r_brace, true, true);
142198092Srdivacky      if (Tok.is(tok::semi))
143198092Srdivacky        ConsumeToken();
144212904Sdim      return 0;
145198092Srdivacky    }
146193326Sed
147193326Sed    ParamLists.push_back(
148198092Srdivacky      Actions.ActOnTemplateParameterList(Depth, ExportLoc,
149198092Srdivacky                                         TemplateLoc, LAngleLoc,
150193326Sed                                         TemplateParams.data(),
151193326Sed                                         TemplateParams.size(), RAngleLoc));
152198092Srdivacky
153198092Srdivacky    if (!TemplateParams.empty()) {
154198092Srdivacky      isSpecialization = false;
155198092Srdivacky      ++Depth;
156198893Srdivacky    } else {
157198893Srdivacky      LastParamListWasEmpty = true;
158198092Srdivacky    }
159193326Sed  } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
160193326Sed
161193326Sed  // Parse the actual template declaration.
162198092Srdivacky  return ParseSingleDeclarationAfterTemplate(Context,
163193326Sed                                             ParsedTemplateInfo(&ParamLists,
164198893Srdivacky                                                             isSpecialization,
165198893Srdivacky                                                         LastParamListWasEmpty),
166212904Sdim                                             ParsingTemplateParams,
167226890Sdim                                             DeclEnd, AS, AccessAttrs);
168193326Sed}
169193326Sed
170193326Sed/// \brief Parse a single declaration that declares a template,
171193326Sed/// template specialization, or explicit instantiation of a template.
172193326Sed///
173193326Sed/// \param TemplateParams if non-NULL, the template parameter lists
174193326Sed/// that preceded this declaration. In this case, the declaration is a
175193326Sed/// template declaration, out-of-line definition of a template, or an
176193326Sed/// explicit template specialization. When NULL, the declaration is an
177193326Sed/// explicit template instantiation.
178193326Sed///
179193326Sed/// \param TemplateLoc when TemplateParams is NULL, the location of
180193326Sed/// the 'template' keyword that indicates that we have an explicit
181193326Sed/// template instantiation.
182193326Sed///
183193326Sed/// \param DeclEnd will receive the source location of the last token
184193326Sed/// within this declaration.
185193326Sed///
186193326Sed/// \param AS the access specifier associated with this
187193326Sed/// declaration. Will be AS_none for namespace-scope declarations.
188193326Sed///
189193326Sed/// \returns the new declaration.
190212904SdimDecl *
191193326SedParser::ParseSingleDeclarationAfterTemplate(
192193326Sed                                       unsigned Context,
193193326Sed                                       const ParsedTemplateInfo &TemplateInfo,
194212904Sdim                                       ParsingDeclRAIIObject &DiagsFromTParams,
195193326Sed                                       SourceLocation &DeclEnd,
196226890Sdim                                       AccessSpecifier AS,
197226890Sdim                                       AttributeList *AccessAttrs) {
198193326Sed  assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
199193326Sed         "Template information required");
200193326Sed
201198092Srdivacky  if (Context == Declarator::MemberContext) {
202198092Srdivacky    // We are parsing a member template.
203226890Sdim    ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
204226890Sdim                                   &DiagsFromTParams);
205212904Sdim    return 0;
206198092Srdivacky  }
207198092Srdivacky
208221345Sdim  ParsedAttributesWithRange prefixAttrs(AttrFactory);
209218893Sdim  MaybeParseCXX0XAttributes(prefixAttrs);
210218893Sdim
211218893Sdim  if (Tok.is(tok::kw_using))
212218893Sdim    return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
213218893Sdim                                            prefixAttrs);
214218893Sdim
215212904Sdim  // Parse the declaration specifiers, stealing the accumulated
216212904Sdim  // diagnostics from the template parameters.
217221345Sdim  ParsingDeclSpec DS(*this, &DiagsFromTParams);
218199990Srdivacky
219218893Sdim  DS.takeAttributesFrom(prefixAttrs);
220199990Srdivacky
221202379Srdivacky  ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
222202379Srdivacky                             getDeclSpecContextFromDeclaratorContext(Context));
223193326Sed
224193326Sed  if (Tok.is(tok::semi)) {
225193326Sed    DeclEnd = ConsumeToken();
226212904Sdim    Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
227198893Srdivacky    DS.complete(Decl);
228198893Srdivacky    return Decl;
229193326Sed  }
230193326Sed
231193326Sed  // Parse the declarator.
232198893Srdivacky  ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
233193326Sed  ParseDeclarator(DeclaratorInfo);
234193326Sed  // Error parsing the declarator?
235193326Sed  if (!DeclaratorInfo.hasName()) {
236193326Sed    // If so, skip until the semi-colon or a }.
237193326Sed    SkipUntil(tok::r_brace, true, true);
238193326Sed    if (Tok.is(tok::semi))
239193326Sed      ConsumeToken();
240212904Sdim    return 0;
241193326Sed  }
242198092Srdivacky
243193326Sed  // If we have a declaration or declarator list, handle it.
244193326Sed  if (isDeclarationAfterDeclarator()) {
245193326Sed    // Parse this declaration.
246212904Sdim    Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
247212904Sdim                                                     TemplateInfo);
248193326Sed
249193326Sed    if (Tok.is(tok::comma)) {
250193326Sed      Diag(Tok, diag::err_multiple_template_declarators)
251193326Sed        << (int)TemplateInfo.Kind;
252193326Sed      SkipUntil(tok::semi, true, false);
253193326Sed      return ThisDecl;
254193326Sed    }
255193326Sed
256193326Sed    // Eat the semi colon after the declaration.
257198092Srdivacky    ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
258218893Sdim    DeclaratorInfo.complete(ThisDecl);
259193326Sed    return ThisDecl;
260193326Sed  }
261193326Sed
262193326Sed  if (DeclaratorInfo.isFunctionDeclarator() &&
263210299Sed      isStartOfFunctionDefinition(DeclaratorInfo)) {
264193326Sed    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
265193326Sed      Diag(Tok, diag::err_function_declared_typedef);
266193326Sed
267193326Sed      if (Tok.is(tok::l_brace)) {
268193326Sed        // This recovery skips the entire function body. It would be nice
269193326Sed        // to simply call ParseFunctionDefinition() below, however Sema
270193326Sed        // assumes the declarator represents a function, not a typedef.
271193326Sed        ConsumeBrace();
272193326Sed        SkipUntil(tok::r_brace, true);
273193326Sed      } else {
274193326Sed        SkipUntil(tok::semi);
275193326Sed      }
276212904Sdim      return 0;
277193326Sed    }
278195099Sed    return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo);
279193326Sed  }
280193326Sed
281193326Sed  if (DeclaratorInfo.isFunctionDeclarator())
282193326Sed    Diag(Tok, diag::err_expected_fn_body);
283193326Sed  else
284193326Sed    Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
285193326Sed  SkipUntil(tok::semi);
286212904Sdim  return 0;
287193326Sed}
288193326Sed
289193326Sed/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
290193326Sed/// angle brackets. Depth is the depth of this template-parameter-list, which
291193326Sed/// is the number of template headers directly enclosing this template header.
292193326Sed/// TemplateParams is the current list of template parameters we're building.
293193326Sed/// The template parameter we parse will be added to this list. LAngleLoc and
294198092Srdivacky/// RAngleLoc will receive the positions of the '<' and '>', respectively,
295193326Sed/// that enclose this template parameter list.
296198092Srdivacky///
297198092Srdivacky/// \returns true if an error occurred, false otherwise.
298193326Sedbool Parser::ParseTemplateParameters(unsigned Depth,
299226890Sdim                               SmallVectorImpl<Decl*> &TemplateParams,
300193326Sed                                     SourceLocation &LAngleLoc,
301193326Sed                                     SourceLocation &RAngleLoc) {
302193326Sed  // Get the template parameter list.
303198092Srdivacky  if (!Tok.is(tok::less)) {
304193326Sed    Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
305198092Srdivacky    return true;
306193326Sed  }
307193326Sed  LAngleLoc = ConsumeToken();
308198092Srdivacky
309193326Sed  // Try to parse the template parameter list.
310193326Sed  if (Tok.is(tok::greater))
311193326Sed    RAngleLoc = ConsumeToken();
312198092Srdivacky  else if (ParseTemplateParameterList(Depth, TemplateParams)) {
313198092Srdivacky    if (!Tok.is(tok::greater)) {
314193326Sed      Diag(Tok.getLocation(), diag::err_expected_greater);
315198092Srdivacky      return true;
316193326Sed    }
317193326Sed    RAngleLoc = ConsumeToken();
318193326Sed  }
319198092Srdivacky  return false;
320193326Sed}
321193326Sed
322193326Sed/// ParseTemplateParameterList - Parse a template parameter list. If
323193326Sed/// the parsing fails badly (i.e., closing bracket was left out), this
324193326Sed/// will try to put the token stream in a reasonable position (closing
325198092Srdivacky/// a statement, etc.) and return false.
326193326Sed///
327193326Sed///       template-parameter-list:    [C++ temp]
328193326Sed///         template-parameter
329193326Sed///         template-parameter-list ',' template-parameter
330198092Srdivackybool
331193326SedParser::ParseTemplateParameterList(unsigned Depth,
332226890Sdim                             SmallVectorImpl<Decl*> &TemplateParams) {
333198092Srdivacky  while (1) {
334212904Sdim    if (Decl *TmpParam
335193326Sed          = ParseTemplateParameter(Depth, TemplateParams.size())) {
336193326Sed      TemplateParams.push_back(TmpParam);
337193326Sed    } else {
338193326Sed      // If we failed to parse a template parameter, skip until we find
339193326Sed      // a comma or closing brace.
340193326Sed      SkipUntil(tok::comma, tok::greater, true, true);
341193326Sed    }
342198092Srdivacky
343193326Sed    // Did we find a comma or the end of the template parmeter list?
344198092Srdivacky    if (Tok.is(tok::comma)) {
345193326Sed      ConsumeToken();
346198092Srdivacky    } else if (Tok.is(tok::greater)) {
347193326Sed      // Don't consume this... that's done by template parser.
348193326Sed      break;
349193326Sed    } else {
350193326Sed      // Somebody probably forgot to close the template. Skip ahead and
351193326Sed      // try to get out of the expression. This error is currently
352193326Sed      // subsumed by whatever goes on in ParseTemplateParameter.
353193326Sed      // TODO: This could match >>, and it would be nice to avoid those
354193326Sed      // silly errors with template <vec<T>>.
355218893Sdim      Diag(Tok.getLocation(), diag::err_expected_comma_greater);
356193326Sed      SkipUntil(tok::greater, true, true);
357193326Sed      return false;
358193326Sed    }
359193326Sed  }
360193326Sed  return true;
361193326Sed}
362193326Sed
363199990Srdivacky/// \brief Determine whether the parser is at the start of a template
364199990Srdivacky/// type parameter.
365199990Srdivackybool Parser::isStartOfTemplateTypeParameter() {
366210299Sed  if (Tok.is(tok::kw_class)) {
367210299Sed    // "class" may be the start of an elaborated-type-specifier or a
368210299Sed    // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
369210299Sed    switch (NextToken().getKind()) {
370210299Sed    case tok::equal:
371210299Sed    case tok::comma:
372210299Sed    case tok::greater:
373210299Sed    case tok::greatergreater:
374210299Sed    case tok::ellipsis:
375210299Sed      return true;
376210299Sed
377210299Sed    case tok::identifier:
378210299Sed      // This may be either a type-parameter or an elaborated-type-specifier.
379210299Sed      // We have to look further.
380210299Sed      break;
381210299Sed
382210299Sed    default:
383210299Sed      return false;
384210299Sed    }
385210299Sed
386210299Sed    switch (GetLookAheadToken(2).getKind()) {
387210299Sed    case tok::equal:
388210299Sed    case tok::comma:
389210299Sed    case tok::greater:
390210299Sed    case tok::greatergreater:
391210299Sed      return true;
392210299Sed
393210299Sed    default:
394210299Sed      return false;
395210299Sed    }
396210299Sed  }
397199990Srdivacky
398199990Srdivacky  if (Tok.isNot(tok::kw_typename))
399199990Srdivacky    return false;
400199990Srdivacky
401199990Srdivacky  // C++ [temp.param]p2:
402199990Srdivacky  //   There is no semantic difference between class and typename in a
403199990Srdivacky  //   template-parameter. typename followed by an unqualified-id
404199990Srdivacky  //   names a template type parameter. typename followed by a
405199990Srdivacky  //   qualified-id denotes the type in a non-type
406199990Srdivacky  //   parameter-declaration.
407199990Srdivacky  Token Next = NextToken();
408199990Srdivacky
409199990Srdivacky  // If we have an identifier, skip over it.
410199990Srdivacky  if (Next.getKind() == tok::identifier)
411199990Srdivacky    Next = GetLookAheadToken(2);
412199990Srdivacky
413199990Srdivacky  switch (Next.getKind()) {
414199990Srdivacky  case tok::equal:
415199990Srdivacky  case tok::comma:
416199990Srdivacky  case tok::greater:
417199990Srdivacky  case tok::greatergreater:
418199990Srdivacky  case tok::ellipsis:
419199990Srdivacky    return true;
420199990Srdivacky
421199990Srdivacky  default:
422199990Srdivacky    return false;
423199990Srdivacky  }
424199990Srdivacky}
425199990Srdivacky
426193326Sed/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
427193326Sed///
428193326Sed///       template-parameter: [C++ temp.param]
429193326Sed///         type-parameter
430193326Sed///         parameter-declaration
431193326Sed///
432193326Sed///       type-parameter: (see below)
433218893Sdim///         'class' ...[opt] identifier[opt]
434193326Sed///         'class' identifier[opt] '=' type-id
435218893Sdim///         'typename' ...[opt] identifier[opt]
436193326Sed///         'typename' identifier[opt] '=' type-id
437218893Sdim///         'template' '<' template-parameter-list '>'
438218893Sdim///               'class' ...[opt] identifier[opt]
439218893Sdim///         'template' '<' template-parameter-list '>' 'class' identifier[opt]
440218893Sdim///               = id-expression
441212904SdimDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
442199990Srdivacky  if (isStartOfTemplateTypeParameter())
443193326Sed    return ParseTypeParameter(Depth, Position);
444198092Srdivacky
445198092Srdivacky  if (Tok.is(tok::kw_template))
446193326Sed    return ParseTemplateTemplateParameter(Depth, Position);
447193326Sed
448193326Sed  // If it's none of the above, then it must be a parameter declaration.
449193326Sed  // NOTE: This will pick up errors in the closure of the template parameter
450193326Sed  // list (e.g., template < ; Check here to implement >> style closures.
451193326Sed  return ParseNonTypeTemplateParameter(Depth, Position);
452193326Sed}
453193326Sed
454193326Sed/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
455193326Sed/// Other kinds of template parameters are parsed in
456193326Sed/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
457193326Sed///
458193326Sed///       type-parameter:     [C++ temp.param]
459194179Sed///         'class' ...[opt][C++0x] identifier[opt]
460193326Sed///         'class' identifier[opt] '=' type-id
461194179Sed///         'typename' ...[opt][C++0x] identifier[opt]
462193326Sed///         'typename' identifier[opt] '=' type-id
463212904SdimDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
464193326Sed  assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
465198092Srdivacky         "A type-parameter starts with 'class' or 'typename'");
466193326Sed
467193326Sed  // Consume the 'class' or 'typename' keyword.
468193326Sed  bool TypenameKeyword = Tok.is(tok::kw_typename);
469193326Sed  SourceLocation KeyLoc = ConsumeToken();
470193326Sed
471194179Sed  // Grab the ellipsis (if given).
472194179Sed  bool Ellipsis = false;
473194179Sed  SourceLocation EllipsisLoc;
474194179Sed  if (Tok.is(tok::ellipsis)) {
475194179Sed    Ellipsis = true;
476194179Sed    EllipsisLoc = ConsumeToken();
477198092Srdivacky
478226890Sdim    Diag(EllipsisLoc,
479226890Sdim         getLang().CPlusPlus0x
480226890Sdim           ? diag::warn_cxx98_compat_variadic_templates
481226890Sdim           : diag::ext_variadic_templates);
482194179Sed  }
483198092Srdivacky
484193326Sed  // Grab the template parameter name (if given)
485193326Sed  SourceLocation NameLoc;
486193326Sed  IdentifierInfo* ParamName = 0;
487198092Srdivacky  if (Tok.is(tok::identifier)) {
488193326Sed    ParamName = Tok.getIdentifierInfo();
489193326Sed    NameLoc = ConsumeToken();
490198092Srdivacky  } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
491198092Srdivacky            Tok.is(tok::greater)) {
492193326Sed    // Unnamed template parameter. Don't have to do anything here, just
493193326Sed    // don't consume this token.
494193326Sed  } else {
495193326Sed    Diag(Tok.getLocation(), diag::err_expected_ident);
496212904Sdim    return 0;
497193326Sed  }
498198092Srdivacky
499210299Sed  // Grab a default argument (if available).
500210299Sed  // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
501210299Sed  // we introduce the type parameter into the local scope.
502210299Sed  SourceLocation EqualLoc;
503212904Sdim  ParsedType DefaultArg;
504198092Srdivacky  if (Tok.is(tok::equal)) {
505210299Sed    EqualLoc = ConsumeToken();
506210299Sed    DefaultArg = ParseTypeName().get();
507193326Sed  }
508210299Sed
509210299Sed  return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
510210299Sed                                    EllipsisLoc, KeyLoc, ParamName, NameLoc,
511210299Sed                                    Depth, Position, EqualLoc, DefaultArg);
512193326Sed}
513193326Sed
514193326Sed/// ParseTemplateTemplateParameter - Handle the parsing of template
515198092Srdivacky/// template parameters.
516193326Sed///
517193326Sed///       type-parameter:    [C++ temp.param]
518218893Sdim///         'template' '<' template-parameter-list '>' 'class'
519218893Sdim///                  ...[opt] identifier[opt]
520218893Sdim///         'template' '<' template-parameter-list '>' 'class' identifier[opt]
521218893Sdim///                  = id-expression
522212904SdimDecl *
523193326SedParser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
524193326Sed  assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
525193326Sed
526193326Sed  // Handle the template <...> part.
527193326Sed  SourceLocation TemplateLoc = ConsumeToken();
528226890Sdim  SmallVector<Decl*,8> TemplateParams;
529193326Sed  SourceLocation LAngleLoc, RAngleLoc;
530193326Sed  {
531193326Sed    ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
532198092Srdivacky    if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
533198092Srdivacky                               RAngleLoc)) {
534212904Sdim      return 0;
535193326Sed    }
536193326Sed  }
537193326Sed
538193326Sed  // Generate a meaningful error if the user forgot to put class before the
539193326Sed  // identifier, comma, or greater.
540198092Srdivacky  if (!Tok.is(tok::kw_class)) {
541198092Srdivacky    Diag(Tok.getLocation(), diag::err_expected_class_before)
542193326Sed      << PP.getSpelling(Tok);
543212904Sdim    return 0;
544193326Sed  }
545218893Sdim  ConsumeToken();
546193326Sed
547218893Sdim  // Parse the ellipsis, if given.
548218893Sdim  SourceLocation EllipsisLoc;
549218893Sdim  if (Tok.is(tok::ellipsis)) {
550218893Sdim    EllipsisLoc = ConsumeToken();
551218893Sdim
552226890Sdim    Diag(EllipsisLoc,
553226890Sdim         getLang().CPlusPlus0x
554226890Sdim           ? diag::warn_cxx98_compat_variadic_templates
555226890Sdim           : diag::ext_variadic_templates);
556218893Sdim  }
557218893Sdim
558193326Sed  // Get the identifier, if given.
559193326Sed  SourceLocation NameLoc;
560193326Sed  IdentifierInfo* ParamName = 0;
561198092Srdivacky  if (Tok.is(tok::identifier)) {
562193326Sed    ParamName = Tok.getIdentifierInfo();
563193326Sed    NameLoc = ConsumeToken();
564198092Srdivacky  } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
565193326Sed    // Unnamed template parameter. Don't have to do anything here, just
566193326Sed    // don't consume this token.
567193326Sed  } else {
568193326Sed    Diag(Tok.getLocation(), diag::err_expected_ident);
569212904Sdim    return 0;
570193326Sed  }
571193326Sed
572226890Sdim  TemplateParameterList *ParamList =
573193326Sed    Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
574193326Sed                                       TemplateLoc, LAngleLoc,
575218893Sdim                                       TemplateParams.data(),
576193326Sed                                       TemplateParams.size(),
577193326Sed                                       RAngleLoc);
578193326Sed
579210299Sed  // Grab a default argument (if available).
580210299Sed  // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
581210299Sed  // we introduce the template parameter into the local scope.
582210299Sed  SourceLocation EqualLoc;
583210299Sed  ParsedTemplateArgument DefaultArg;
584193326Sed  if (Tok.is(tok::equal)) {
585210299Sed    EqualLoc = ConsumeToken();
586210299Sed    DefaultArg = ParseTemplateTemplateArgument();
587210299Sed    if (DefaultArg.isInvalid()) {
588199482Srdivacky      Diag(Tok.getLocation(),
589199482Srdivacky           diag::err_default_template_template_parameter_not_template);
590200583Srdivacky      static const tok::TokenKind EndToks[] = {
591199482Srdivacky        tok::comma, tok::greater, tok::greatergreater
592199482Srdivacky      };
593199482Srdivacky      SkipUntil(EndToks, 3, true, true);
594210299Sed    }
595193326Sed  }
596210299Sed
597210299Sed  return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
598218893Sdim                                                ParamList, EllipsisLoc,
599218893Sdim                                                ParamName, NameLoc, Depth,
600218893Sdim                                                Position, EqualLoc, DefaultArg);
601193326Sed}
602193326Sed
603193326Sed/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
604198092Srdivacky/// template parameters (e.g., in "template<int Size> class array;").
605193326Sed///
606193326Sed///       template-parameter:
607193326Sed///         ...
608193326Sed///         parameter-declaration
609212904SdimDecl *
610193326SedParser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
611193326Sed  // Parse the declaration-specifiers (i.e., the type).
612193326Sed  // FIXME: The type should probably be restricted in some way... Not all
613193326Sed  // declarators (parts of declarators?) are accepted for parameters.
614221345Sdim  DeclSpec DS(AttrFactory);
615193326Sed  ParseDeclarationSpecifiers(DS);
616193326Sed
617193326Sed  // Parse this as a typename.
618193326Sed  Declarator ParamDecl(DS, Declarator::TemplateParamContext);
619193326Sed  ParseDeclarator(ParamDecl);
620212904Sdim  if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
621193326Sed    // This probably shouldn't happen - and it's more of a Sema thing, but
622193326Sed    // basically we didn't parse the type name because we couldn't associate
623193326Sed    // it with an AST node. we should just skip to the comma or greater.
624193326Sed    // TODO: This is currently a placeholder for some kind of Sema Error.
625193326Sed    Diag(Tok.getLocation(), diag::err_parse_error);
626193326Sed    SkipUntil(tok::comma, tok::greater, true, true);
627212904Sdim    return 0;
628193326Sed  }
629193326Sed
630193326Sed  // If there is a default value, parse it.
631210299Sed  // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
632210299Sed  // we introduce the template parameter into the local scope.
633210299Sed  SourceLocation EqualLoc;
634212904Sdim  ExprResult DefaultArg;
635193326Sed  if (Tok.is(tok::equal)) {
636210299Sed    EqualLoc = ConsumeToken();
637193326Sed
638193326Sed    // C++ [temp.param]p15:
639193326Sed    //   When parsing a default template-argument for a non-type
640193326Sed    //   template-parameter, the first non-nested > is taken as the
641193326Sed    //   end of the template-parameter-list rather than a greater-than
642193326Sed    //   operator.
643198092Srdivacky    GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
644193326Sed
645210299Sed    DefaultArg = ParseAssignmentExpression();
646193326Sed    if (DefaultArg.isInvalid())
647193326Sed      SkipUntil(tok::comma, tok::greater, true, true);
648193326Sed  }
649198092Srdivacky
650210299Sed  // Create the parameter.
651210299Sed  return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
652210299Sed                                               Depth, Position, EqualLoc,
653212904Sdim                                               DefaultArg.take());
654193326Sed}
655193326Sed
656193326Sed/// \brief Parses a template-id that after the template name has
657193326Sed/// already been parsed.
658193326Sed///
659193326Sed/// This routine takes care of parsing the enclosed template argument
660193326Sed/// list ('<' template-parameter-list [opt] '>') and placing the
661193326Sed/// results into a form that can be transferred to semantic analysis.
662193326Sed///
663193326Sed/// \param Template the template declaration produced by isTemplateName
664193326Sed///
665193326Sed/// \param TemplateNameLoc the source location of the template name
666193326Sed///
667193326Sed/// \param SS if non-NULL, the nested-name-specifier preceding the
668193326Sed/// template name.
669193326Sed///
670193326Sed/// \param ConsumeLastToken if true, then we will consume the last
671193326Sed/// token that forms the template-id. Otherwise, we will leave the
672193326Sed/// last token in the stream (e.g., so that it can be replaced with an
673193326Sed/// annotation token).
674198092Srdivackybool
675193326SedParser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
676198092Srdivacky                                         SourceLocation TemplateNameLoc,
677221345Sdim                                         const CXXScopeSpec &SS,
678193326Sed                                         bool ConsumeLastToken,
679193326Sed                                         SourceLocation &LAngleLoc,
680193326Sed                                         TemplateArgList &TemplateArgs,
681193326Sed                                         SourceLocation &RAngleLoc) {
682193326Sed  assert(Tok.is(tok::less) && "Must have already parsed the template-name");
683193326Sed
684193326Sed  // Consume the '<'.
685193326Sed  LAngleLoc = ConsumeToken();
686193326Sed
687193326Sed  // Parse the optional template-argument-list.
688193326Sed  bool Invalid = false;
689193326Sed  {
690193326Sed    GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
691218893Sdim    if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
692199482Srdivacky      Invalid = ParseTemplateArgumentList(TemplateArgs);
693193326Sed
694193326Sed    if (Invalid) {
695193326Sed      // Try to find the closing '>'.
696193326Sed      SkipUntil(tok::greater, true, !ConsumeLastToken);
697193326Sed
698193326Sed      return true;
699193326Sed    }
700193326Sed  }
701193326Sed
702201361Srdivacky  if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) {
703201361Srdivacky    Diag(Tok.getLocation(), diag::err_expected_greater);
704193326Sed    return true;
705201361Srdivacky  }
706193326Sed
707193326Sed  // Determine the location of the '>' or '>>'. Only consume this
708193326Sed  // token if the caller asked us to.
709193326Sed  RAngleLoc = Tok.getLocation();
710193326Sed
711193326Sed  if (Tok.is(tok::greatergreater)) {
712193326Sed    if (!getLang().CPlusPlus0x) {
713193326Sed      const char *ReplaceStr = "> >";
714193326Sed      if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
715193326Sed        ReplaceStr = "> > ";
716193326Sed
717193326Sed      Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
718206084Srdivacky        << FixItHint::CreateReplacement(
719193326Sed                                 SourceRange(Tok.getLocation()), ReplaceStr);
720193326Sed    }
721193326Sed
722193326Sed    Tok.setKind(tok::greater);
723193326Sed    if (!ConsumeLastToken) {
724193326Sed      // Since we're not supposed to consume the '>>' token, we need
725193326Sed      // to insert a second '>' token after the first.
726193326Sed      PP.EnterToken(Tok);
727193326Sed    }
728193326Sed  } else if (ConsumeLastToken)
729193326Sed    ConsumeToken();
730193326Sed
731193326Sed  return false;
732193326Sed}
733198092Srdivacky
734193326Sed/// \brief Replace the tokens that form a simple-template-id with an
735193326Sed/// annotation token containing the complete template-id.
736193326Sed///
737193326Sed/// The first token in the stream must be the name of a template that
738193326Sed/// is followed by a '<'. This routine will parse the complete
739193326Sed/// simple-template-id and replace the tokens with a single annotation
740193326Sed/// token with one of two different kinds: if the template-id names a
741193326Sed/// type (and \p AllowTypeAnnotation is true), the annotation token is
742193326Sed/// a type annotation that includes the optional nested-name-specifier
743193326Sed/// (\p SS). Otherwise, the annotation token is a template-id
744193326Sed/// annotation that does not include the optional
745193326Sed/// nested-name-specifier.
746193326Sed///
747193326Sed/// \param Template  the declaration of the template named by the first
748193326Sed/// token (an identifier), as returned from \c Action::isTemplateName().
749193326Sed///
750193326Sed/// \param TemplateNameKind the kind of template that \p Template
751193326Sed/// refers to, as returned from \c Action::isTemplateName().
752193326Sed///
753193326Sed/// \param SS if non-NULL, the nested-name-specifier that precedes
754193326Sed/// this template name.
755193326Sed///
756193326Sed/// \param TemplateKWLoc if valid, specifies that this template-id
757193326Sed/// annotation was preceded by the 'template' keyword and gives the
758193326Sed/// location of that keyword. If invalid (the default), then this
759193326Sed/// template-id was not preceded by a 'template' keyword.
760193326Sed///
761193326Sed/// \param AllowTypeAnnotation if true (the default), then a
762193326Sed/// simple-template-id that refers to a class template, template
763193326Sed/// template parameter, or other template that produces a type will be
764193326Sed/// replaced with a type annotation token. Otherwise, the
765193326Sed/// simple-template-id is always replaced with a template-id
766193326Sed/// annotation token.
767195099Sed///
768195099Sed/// If an unrecoverable parse error occurs and no annotation token can be
769195099Sed/// formed, this function returns true.
770195099Sed///
771195099Sedbool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
772221345Sdim                                     CXXScopeSpec &SS,
773198893Srdivacky                                     UnqualifiedId &TemplateName,
774193326Sed                                     SourceLocation TemplateKWLoc,
775193326Sed                                     bool AllowTypeAnnotation) {
776193326Sed  assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
777198893Srdivacky  assert(Template && Tok.is(tok::less) &&
778193326Sed         "Parser isn't at the beginning of a template-id");
779193326Sed
780193326Sed  // Consume the template-name.
781198893Srdivacky  SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
782193326Sed
783193326Sed  // Parse the enclosed template argument list.
784193326Sed  SourceLocation LAngleLoc, RAngleLoc;
785193326Sed  TemplateArgList TemplateArgs;
786198893Srdivacky  bool Invalid = ParseTemplateIdAfterTemplateName(Template,
787198893Srdivacky                                                  TemplateNameLoc,
788198092Srdivacky                                                  SS, false, LAngleLoc,
789198092Srdivacky                                                  TemplateArgs,
790193326Sed                                                  RAngleLoc);
791198092Srdivacky
792195099Sed  if (Invalid) {
793195099Sed    // If we failed to parse the template ID but skipped ahead to a >, we're not
794195099Sed    // going to be able to form a token annotation.  Eat the '>' if present.
795195099Sed    if (Tok.is(tok::greater))
796195099Sed      ConsumeToken();
797195099Sed    return true;
798195099Sed  }
799193326Sed
800193326Sed  ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
801193326Sed                                     TemplateArgs.size());
802193326Sed
803193326Sed  // Build the annotation token.
804193326Sed  if (TNK == TNK_Type_template && AllowTypeAnnotation) {
805212904Sdim    TypeResult Type
806221345Sdim      = Actions.ActOnTemplateIdType(SS,
807221345Sdim                                    Template, TemplateNameLoc,
808193326Sed                                    LAngleLoc, TemplateArgsPtr,
809193326Sed                                    RAngleLoc);
810195099Sed    if (Type.isInvalid()) {
811195099Sed      // If we failed to parse the template ID but skipped ahead to a >, we're not
812195099Sed      // going to be able to form a token annotation.  Eat the '>' if present.
813195099Sed      if (Tok.is(tok::greater))
814195099Sed        ConsumeToken();
815195099Sed      return true;
816195099Sed    }
817193326Sed
818193326Sed    Tok.setKind(tok::annot_typename);
819212904Sdim    setTypeAnnotation(Tok, Type.get());
820221345Sdim    if (SS.isNotEmpty())
821221345Sdim      Tok.setLocation(SS.getBeginLoc());
822193326Sed    else if (TemplateKWLoc.isValid())
823193326Sed      Tok.setLocation(TemplateKWLoc);
824198092Srdivacky    else
825193326Sed      Tok.setLocation(TemplateNameLoc);
826193326Sed  } else {
827193326Sed    // Build a template-id annotation token that can be processed
828193326Sed    // later.
829193326Sed    Tok.setKind(tok::annot_template_id);
830198092Srdivacky    TemplateIdAnnotation *TemplateId
831193326Sed      = TemplateIdAnnotation::Allocate(TemplateArgs.size());
832193326Sed    TemplateId->TemplateNameLoc = TemplateNameLoc;
833198893Srdivacky    if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
834198893Srdivacky      TemplateId->Name = TemplateName.Identifier;
835198893Srdivacky      TemplateId->Operator = OO_None;
836198893Srdivacky    } else {
837198893Srdivacky      TemplateId->Name = 0;
838198893Srdivacky      TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
839198893Srdivacky    }
840221345Sdim    TemplateId->SS = SS;
841212904Sdim    TemplateId->Template = Template;
842193326Sed    TemplateId->Kind = TNK;
843193326Sed    TemplateId->LAngleLoc = LAngleLoc;
844193326Sed    TemplateId->RAngleLoc = RAngleLoc;
845199482Srdivacky    ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
846199482Srdivacky    for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
847219077Sdim      Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
848193326Sed    Tok.setAnnotationValue(TemplateId);
849193326Sed    if (TemplateKWLoc.isValid())
850193326Sed      Tok.setLocation(TemplateKWLoc);
851193326Sed    else
852193326Sed      Tok.setLocation(TemplateNameLoc);
853193326Sed
854193326Sed    TemplateArgsPtr.release();
855193326Sed  }
856193326Sed
857193326Sed  // Common fields for the annotation token
858193326Sed  Tok.setAnnotationEndLoc(RAngleLoc);
859193326Sed
860193326Sed  // In case the tokens were cached, have Preprocessor replace them with the
861193326Sed  // annotation token.
862193326Sed  PP.AnnotateCachedTokens(Tok);
863195099Sed  return false;
864193326Sed}
865193326Sed
866193326Sed/// \brief Replaces a template-id annotation token with a type
867193326Sed/// annotation token.
868193326Sed///
869193326Sed/// If there was a failure when forming the type from the template-id,
870193326Sed/// a type annotation token will still be created, but will have a
871193326Sed/// NULL type pointer to signify an error.
872221345Sdimvoid Parser::AnnotateTemplateIdTokenAsType() {
873193326Sed  assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
874193326Sed
875224145Sdim  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
876193326Sed  assert((TemplateId->Kind == TNK_Type_template ||
877193326Sed          TemplateId->Kind == TNK_Dependent_template_name) &&
878193326Sed         "Only works for type and dependent templates");
879198092Srdivacky
880198092Srdivacky  ASTTemplateArgsPtr TemplateArgsPtr(Actions,
881193326Sed                                     TemplateId->getTemplateArgs(),
882193326Sed                                     TemplateId->NumArgs);
883193326Sed
884212904Sdim  TypeResult Type
885221345Sdim    = Actions.ActOnTemplateIdType(TemplateId->SS,
886221345Sdim                                  TemplateId->Template,
887193326Sed                                  TemplateId->TemplateNameLoc,
888198092Srdivacky                                  TemplateId->LAngleLoc,
889193326Sed                                  TemplateArgsPtr,
890193326Sed                                  TemplateId->RAngleLoc);
891193326Sed  // Create the new "type" annotation token.
892193326Sed  Tok.setKind(tok::annot_typename);
893212904Sdim  setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
894221345Sdim  if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
895221345Sdim    Tok.setLocation(TemplateId->SS.getBeginLoc());
896203955Srdivacky  // End location stays the same
897193326Sed
898198954Srdivacky  // Replace the template-id annotation token, and possible the scope-specifier
899198954Srdivacky  // that precedes it, with the typename annotation token.
900198954Srdivacky  PP.AnnotateCachedTokens(Tok);
901193326Sed}
902193326Sed
903199482Srdivacky/// \brief Determine whether the given token can end a template argument.
904199482Srdivackystatic bool isEndOfTemplateArgument(Token Tok) {
905199482Srdivacky  return Tok.is(tok::comma) || Tok.is(tok::greater) ||
906199482Srdivacky         Tok.is(tok::greatergreater);
907199482Srdivacky}
908199482Srdivacky
909199482Srdivacky/// \brief Parse a C++ template template argument.
910199482SrdivackyParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
911199482Srdivacky  if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
912199482Srdivacky      !Tok.is(tok::annot_cxxscope))
913199482Srdivacky    return ParsedTemplateArgument();
914199482Srdivacky
915199482Srdivacky  // C++0x [temp.arg.template]p1:
916199482Srdivacky  //   A template-argument for a template template-parameter shall be the name
917223017Sdim  //   of a class template or an alias template, expressed as id-expression.
918199482Srdivacky  //
919223017Sdim  // We parse an id-expression that refers to a class template or alias
920223017Sdim  // template. The grammar we parse is:
921199482Srdivacky  //
922218893Sdim  //   nested-name-specifier[opt] template[opt] identifier ...[opt]
923199482Srdivacky  //
924199482Srdivacky  // followed by a token that terminates a template argument, such as ',',
925199482Srdivacky  // '>', or (in some cases) '>>'.
926199482Srdivacky  CXXScopeSpec SS; // nested-name-specifier, if present
927212904Sdim  ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
928199482Srdivacky                                 /*EnteringContext=*/false);
929199482Srdivacky
930218893Sdim  ParsedTemplateArgument Result;
931218893Sdim  SourceLocation EllipsisLoc;
932199482Srdivacky  if (SS.isSet() && Tok.is(tok::kw_template)) {
933199482Srdivacky    // Parse the optional 'template' keyword following the
934199482Srdivacky    // nested-name-specifier.
935199482Srdivacky    SourceLocation TemplateLoc = ConsumeToken();
936199482Srdivacky
937199482Srdivacky    if (Tok.is(tok::identifier)) {
938199482Srdivacky      // We appear to have a dependent template name.
939199482Srdivacky      UnqualifiedId Name;
940199482Srdivacky      Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
941199482Srdivacky      ConsumeToken(); // the identifier
942199482Srdivacky
943218893Sdim      // Parse the ellipsis.
944218893Sdim      if (Tok.is(tok::ellipsis))
945218893Sdim        EllipsisLoc = ConsumeToken();
946218893Sdim
947199482Srdivacky      // If the next token signals the end of a template argument,
948199482Srdivacky      // then we have a dependent template name that could be a template
949199482Srdivacky      // template argument.
950210299Sed      TemplateTy Template;
951210299Sed      if (isEndOfTemplateArgument(Tok) &&
952212904Sdim          Actions.ActOnDependentTemplateName(getCurScope(), TemplateLoc,
953212904Sdim                                             SS, Name,
954212904Sdim                                             /*ObjectType=*/ ParsedType(),
955210299Sed                                             /*EnteringContext=*/false,
956210299Sed                                             Template))
957218893Sdim        Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
958210299Sed    }
959199482Srdivacky  } else if (Tok.is(tok::identifier)) {
960199482Srdivacky    // We may have a (non-dependent) template name.
961199482Srdivacky    TemplateTy Template;
962199482Srdivacky    UnqualifiedId Name;
963199482Srdivacky    Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
964199482Srdivacky    ConsumeToken(); // the identifier
965199482Srdivacky
966218893Sdim    // Parse the ellipsis.
967218893Sdim    if (Tok.is(tok::ellipsis))
968218893Sdim      EllipsisLoc = ConsumeToken();
969218893Sdim
970199482Srdivacky    if (isEndOfTemplateArgument(Tok)) {
971208600Srdivacky      bool MemberOfUnknownSpecialization;
972212904Sdim      TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
973212904Sdim                                               /*hasTemplateKeyword=*/false,
974212904Sdim                                                    Name,
975212904Sdim                                               /*ObjectType=*/ ParsedType(),
976199482Srdivacky                                                    /*EnteringContext=*/false,
977208600Srdivacky                                                    Template,
978208600Srdivacky                                                MemberOfUnknownSpecialization);
979199482Srdivacky      if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
980199482Srdivacky        // We have an id-expression that refers to a class template or
981223017Sdim        // (C++0x) alias template.
982218893Sdim        Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
983199482Srdivacky      }
984199482Srdivacky    }
985199482Srdivacky  }
986199482Srdivacky
987218893Sdim  // If this is a pack expansion, build it as such.
988218893Sdim  if (EllipsisLoc.isValid() && !Result.isInvalid())
989218893Sdim    Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
990218893Sdim
991218893Sdim  return Result;
992199482Srdivacky}
993199482Srdivacky
994193326Sed/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
995193326Sed///
996193326Sed///       template-argument: [C++ 14.2]
997194711Sed///         constant-expression
998193326Sed///         type-id
999193326Sed///         id-expression
1000199482SrdivackyParsedTemplateArgument Parser::ParseTemplateArgument() {
1001193326Sed  // C++ [temp.arg]p2:
1002193326Sed  //   In a template-argument, an ambiguity between a type-id and an
1003193326Sed  //   expression is resolved to a type-id, regardless of the form of
1004193326Sed  //   the corresponding template-parameter.
1005193326Sed  //
1006199482Srdivacky  // Therefore, we initially try to parse a type-id.
1007193326Sed  if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1008199482Srdivacky    SourceLocation Loc = Tok.getLocation();
1009218893Sdim    TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1010218893Sdim                                       Declarator::TemplateTypeArgContext);
1011193326Sed    if (TypeArg.isInvalid())
1012199482Srdivacky      return ParsedTemplateArgument();
1013199482Srdivacky
1014212904Sdim    return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1015212904Sdim                                  TypeArg.get().getAsOpaquePtr(),
1016199482Srdivacky                                  Loc);
1017193326Sed  }
1018199482Srdivacky
1019199482Srdivacky  // Try to parse a template template argument.
1020199482Srdivacky  {
1021199482Srdivacky    TentativeParsingAction TPA(*this);
1022193326Sed
1023199482Srdivacky    ParsedTemplateArgument TemplateTemplateArgument
1024199482Srdivacky      = ParseTemplateTemplateArgument();
1025199482Srdivacky    if (!TemplateTemplateArgument.isInvalid()) {
1026199482Srdivacky      TPA.Commit();
1027199482Srdivacky      return TemplateTemplateArgument;
1028199482Srdivacky    }
1029199482Srdivacky
1030199482Srdivacky    // Revert this tentative parse to parse a non-type template argument.
1031199482Srdivacky    TPA.Revert();
1032199482Srdivacky  }
1033199482Srdivacky
1034199482Srdivacky  // Parse a non-type template argument.
1035199482Srdivacky  SourceLocation Loc = Tok.getLocation();
1036212904Sdim  ExprResult ExprArg = ParseConstantExpression();
1037193326Sed  if (ExprArg.isInvalid() || !ExprArg.get())
1038199482Srdivacky    return ParsedTemplateArgument();
1039193326Sed
1040199482Srdivacky  return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1041199482Srdivacky                                ExprArg.release(), Loc);
1042193326Sed}
1043193326Sed
1044208600Srdivacky/// \brief Determine whether the current tokens can only be parsed as a
1045208600Srdivacky/// template argument list (starting with the '<') and never as a '<'
1046208600Srdivacky/// expression.
1047208600Srdivackybool Parser::IsTemplateArgumentList(unsigned Skip) {
1048208600Srdivacky  struct AlwaysRevertAction : TentativeParsingAction {
1049208600Srdivacky    AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1050208600Srdivacky    ~AlwaysRevertAction() { Revert(); }
1051208600Srdivacky  } Tentative(*this);
1052208600Srdivacky
1053208600Srdivacky  while (Skip) {
1054208600Srdivacky    ConsumeToken();
1055208600Srdivacky    --Skip;
1056208600Srdivacky  }
1057208600Srdivacky
1058208600Srdivacky  // '<'
1059208600Srdivacky  if (!Tok.is(tok::less))
1060208600Srdivacky    return false;
1061208600Srdivacky  ConsumeToken();
1062208600Srdivacky
1063208600Srdivacky  // An empty template argument list.
1064208600Srdivacky  if (Tok.is(tok::greater))
1065208600Srdivacky    return true;
1066208600Srdivacky
1067208600Srdivacky  // See whether we have declaration specifiers, which indicate a type.
1068208600Srdivacky  while (isCXXDeclarationSpecifier() == TPResult::True())
1069208600Srdivacky    ConsumeToken();
1070208600Srdivacky
1071208600Srdivacky  // If we have a '>' or a ',' then this is a template argument list.
1072208600Srdivacky  return Tok.is(tok::greater) || Tok.is(tok::comma);
1073208600Srdivacky}
1074208600Srdivacky
1075193326Sed/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1076193326Sed/// (C++ [temp.names]). Returns true if there was an error.
1077193326Sed///
1078193326Sed///       template-argument-list: [C++ 14.2]
1079193326Sed///         template-argument
1080193326Sed///         template-argument-list ',' template-argument
1081198092Srdivackybool
1082199482SrdivackyParser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1083193326Sed  while (true) {
1084199482Srdivacky    ParsedTemplateArgument Arg = ParseTemplateArgument();
1085218893Sdim    if (Tok.is(tok::ellipsis)) {
1086218893Sdim      SourceLocation EllipsisLoc  = ConsumeToken();
1087218893Sdim      Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1088218893Sdim    }
1089218893Sdim
1090199482Srdivacky    if (Arg.isInvalid()) {
1091193326Sed      SkipUntil(tok::comma, tok::greater, true, true);
1092193326Sed      return true;
1093193326Sed    }
1094193326Sed
1095199482Srdivacky    // Save this template argument.
1096199482Srdivacky    TemplateArgs.push_back(Arg);
1097199482Srdivacky
1098193326Sed    // If the next token is a comma, consume it and keep reading
1099193326Sed    // arguments.
1100193326Sed    if (Tok.isNot(tok::comma)) break;
1101193326Sed
1102193326Sed    // Consume the comma.
1103193326Sed    ConsumeToken();
1104193326Sed  }
1105193326Sed
1106201361Srdivacky  return false;
1107193326Sed}
1108193326Sed
1109198092Srdivacky/// \brief Parse a C++ explicit template instantiation
1110193326Sed/// (C++ [temp.explicit]).
1111193326Sed///
1112193326Sed///       explicit-instantiation:
1113198092Srdivacky///         'extern' [opt] 'template' declaration
1114198092Srdivacky///
1115198092Srdivacky/// Note that the 'extern' is a GNU extension and C++0x feature.
1116212904SdimDecl *Parser::ParseExplicitInstantiation(SourceLocation ExternLoc,
1117212904Sdim                                         SourceLocation TemplateLoc,
1118212904Sdim                                         SourceLocation &DeclEnd) {
1119212904Sdim  // This isn't really required here.
1120212904Sdim  ParsingDeclRAIIObject ParsingTemplateParams(*this);
1121212904Sdim
1122198092Srdivacky  return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
1123198092Srdivacky                                             ParsedTemplateInfo(ExternLoc,
1124198092Srdivacky                                                                TemplateLoc),
1125212904Sdim                                             ParsingTemplateParams,
1126193326Sed                                             DeclEnd, AS_none);
1127193326Sed}
1128218893Sdim
1129218893SdimSourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1130218893Sdim  if (TemplateParams)
1131218893Sdim    return getTemplateParamsRange(TemplateParams->data(),
1132218893Sdim                                  TemplateParams->size());
1133218893Sdim
1134218893Sdim  SourceRange R(TemplateLoc);
1135218893Sdim  if (ExternLoc.isValid())
1136218893Sdim    R.setBegin(ExternLoc);
1137218893Sdim  return R;
1138218893Sdim}
1139221345Sdim
1140221345Sdimvoid Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
1141221345Sdim  ((Parser*)P)->LateTemplateParser(FD);
1142221345Sdim}
1143221345Sdim
1144221345Sdim
1145221345Sdimvoid Parser::LateTemplateParser(const FunctionDecl *FD) {
1146221345Sdim  LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1147221345Sdim  if (LPT) {
1148221345Sdim    ParseLateTemplatedFuncDef(*LPT);
1149221345Sdim    return;
1150221345Sdim  }
1151221345Sdim
1152221345Sdim  llvm_unreachable("Late templated function without associated lexed tokens");
1153221345Sdim}
1154221345Sdim
1155221345Sdim/// \brief Late parse a C++ function template in Microsoft mode.
1156221345Sdimvoid Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1157221345Sdim  if(!LMT.D)
1158221345Sdim     return;
1159221345Sdim
1160221345Sdim  // If this is a member template, introduce the template parameter scope.
1161221345Sdim  ParseScope TemplateScope(this, Scope::TemplateParamScope);
1162221345Sdim
1163221345Sdim  // Get the FunctionDecl.
1164221345Sdim  FunctionDecl *FD = 0;
1165221345Sdim  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
1166221345Sdim    FD = FunTmpl->getTemplatedDecl();
1167221345Sdim  else
1168221345Sdim    FD = cast<FunctionDecl>(LMT.D);
1169221345Sdim
1170221345Sdim  // Reinject the template parameters.
1171226890Sdim  SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1172221345Sdim  DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
1173221345Sdim  if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1174221345Sdim    Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1175221345Sdim    Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1176221345Sdim  } else {
1177221345Sdim    Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1178221345Sdim
1179226890Sdim    // Get the list of DeclContext to reenter.
1180226890Sdim    SmallVector<DeclContext*, 4> DeclContextToReenter;
1181221345Sdim    DeclContext *DD = FD->getLexicalParent();
1182221345Sdim    while (DD && DD->isRecord()) {
1183226890Sdim      DeclContextToReenter.push_back(DD);
1184221345Sdim      DD = DD->getLexicalParent();
1185221345Sdim    }
1186226890Sdim
1187226890Sdim    // Reenter template scopes from outmost to innermost.
1188226890Sdim    SmallVector<DeclContext*, 4>::reverse_iterator II =
1189226890Sdim    DeclContextToReenter.rbegin();
1190226890Sdim    for (; II != DeclContextToReenter.rend(); ++II) {
1191226890Sdim      if (ClassTemplatePartialSpecializationDecl* MD =
1192226890Sdim                dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
1193226890Sdim       TemplateParamScopeStack.push_back(new ParseScope(this,
1194226890Sdim                                                   Scope::TemplateParamScope));
1195226890Sdim        Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1196226890Sdim      } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
1197226890Sdim        TemplateParamScopeStack.push_back(new ParseScope(this,
1198226890Sdim                                                    Scope::TemplateParamScope,
1199226890Sdim                                       MD->getDescribedClassTemplate() != 0 ));
1200226890Sdim        Actions.ActOnReenterTemplateScope(getCurScope(),
1201226890Sdim                                          MD->getDescribedClassTemplate());
1202226890Sdim      }
1203226890Sdim    }
1204221345Sdim  }
1205221345Sdim  assert(!LMT.Toks.empty() && "Empty body!");
1206221345Sdim
1207221345Sdim  // Append the current token at the end of the new token stream so that it
1208221345Sdim  // doesn't get lost.
1209221345Sdim  LMT.Toks.push_back(Tok);
1210221345Sdim  PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1211221345Sdim
1212221345Sdim  // Consume the previously pushed token.
1213221345Sdim  ConsumeAnyToken();
1214221345Sdim  assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1215221345Sdim         && "Inline method not starting with '{', ':' or 'try'");
1216221345Sdim
1217221345Sdim  // Parse the method body. Function body parsing code is similar enough
1218221345Sdim  // to be re-used for method bodies as well.
1219221345Sdim  ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1220221345Sdim
1221221345Sdim  // Recreate the DeclContext.
1222221345Sdim  Sema::ContextRAII SavedContext(Actions, Actions.getContainingDC(FD));
1223221345Sdim
1224221345Sdim  if (FunctionTemplateDecl *FunctionTemplate
1225221345Sdim        = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
1226221345Sdim    Actions.ActOnStartOfFunctionDef(getCurScope(),
1227221345Sdim                                   FunctionTemplate->getTemplatedDecl());
1228221345Sdim  if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
1229221345Sdim    Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
1230221345Sdim
1231221345Sdim
1232221345Sdim  if (Tok.is(tok::kw_try)) {
1233221345Sdim    ParseFunctionTryBlock(LMT.D, FnScope);
1234226890Sdim  } else {
1235226890Sdim    if (Tok.is(tok::colon))
1236226890Sdim      ParseConstructorInitializer(LMT.D);
1237226890Sdim    else
1238226890Sdim      Actions.ActOnDefaultCtorInitializers(LMT.D);
1239221345Sdim
1240226890Sdim    if (Tok.is(tok::l_brace)) {
1241226890Sdim      ParseFunctionStatementBody(LMT.D, FnScope);
1242226890Sdim      Actions.MarkAsLateParsedTemplate(FD, false);
1243226890Sdim    } else
1244221345Sdim      Actions.ActOnFinishFunctionBody(LMT.D, 0);
1245226890Sdim  }
1246221345Sdim
1247226890Sdim  // Exit scopes.
1248226890Sdim  FnScope.Exit();
1249226890Sdim  SmallVector<ParseScope*, 4>::reverse_iterator I =
1250226890Sdim   TemplateParamScopeStack.rbegin();
1251226890Sdim  for (; I != TemplateParamScopeStack.rend(); ++I)
1252226890Sdim    delete *I;
1253221345Sdim
1254221345Sdim  DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1255221345Sdim  if (grp)
1256221345Sdim    Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
1257221345Sdim}
1258221345Sdim
1259221345Sdim/// \brief Lex a delayed template function for late parsing.
1260221345Sdimvoid Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1261221345Sdim  tok::TokenKind kind = Tok.getKind();
1262226890Sdim  if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1263226890Sdim    // Consume everything up to (and including) the matching right brace.
1264226890Sdim    ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1265221345Sdim  }
1266221345Sdim
1267221345Sdim  // If we're in a function-try-block, we need to store all the catch blocks.
1268221345Sdim  if (kind == tok::kw_try) {
1269221345Sdim    while (Tok.is(tok::kw_catch)) {
1270221345Sdim      ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1271221345Sdim      ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1272221345Sdim    }
1273221345Sdim  }
1274221345Sdim}
1275