ParseTemplate.cpp revision 198954
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/Parse/DeclSpec.h"
17193326Sed#include "clang/Parse/Scope.h"
18198092Srdivacky#include "llvm/Support/Compiler.h"
19193326Sedusing namespace clang;
20193326Sed
21193326Sed/// \brief Parse a template declaration, explicit instantiation, or
22193326Sed/// explicit specialization.
23193326SedParser::DeclPtrTy
24193326SedParser::ParseDeclarationStartingWithTemplate(unsigned Context,
25193326Sed                                             SourceLocation &DeclEnd,
26193326Sed                                             AccessSpecifier AS) {
27193326Sed  if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less))
28198092Srdivacky    return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(),
29198092Srdivacky                                      DeclEnd);
30193326Sed
31193326Sed  return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS);
32193326Sed}
33193326Sed
34198092Srdivacky/// \brief RAII class that manages the template parameter depth.
35198092Srdivackynamespace {
36198092Srdivacky  class VISIBILITY_HIDDEN TemplateParameterDepthCounter {
37198092Srdivacky    unsigned &Depth;
38198092Srdivacky    unsigned AddedLevels;
39198092Srdivacky
40198092Srdivacky  public:
41198092Srdivacky    explicit TemplateParameterDepthCounter(unsigned &Depth)
42198092Srdivacky      : Depth(Depth), AddedLevels(0) { }
43198092Srdivacky
44198092Srdivacky    ~TemplateParameterDepthCounter() {
45198092Srdivacky      Depth -= AddedLevels;
46198092Srdivacky    }
47198092Srdivacky
48198092Srdivacky    void operator++() {
49198092Srdivacky      ++Depth;
50198092Srdivacky      ++AddedLevels;
51198092Srdivacky    }
52198092Srdivacky
53198092Srdivacky    operator unsigned() const { return Depth; }
54198092Srdivacky  };
55198092Srdivacky}
56198092Srdivacky
57193326Sed/// \brief Parse a template declaration or an explicit specialization.
58193326Sed///
59193326Sed/// Template declarations include one or more template parameter lists
60193326Sed/// and either the function or class template declaration. Explicit
61193326Sed/// specializations contain one or more 'template < >' prefixes
62193326Sed/// followed by a (possibly templated) declaration. Since the
63193326Sed/// syntactic form of both features is nearly identical, we parse all
64193326Sed/// of the template headers together and let semantic analysis sort
65193326Sed/// the declarations from the explicit specializations.
66193326Sed///
67193326Sed///       template-declaration: [C++ temp]
68193326Sed///         'export'[opt] 'template' '<' template-parameter-list '>' declaration
69193326Sed///
70193326Sed///       explicit-specialization: [ C++ temp.expl.spec]
71193326Sed///         'template' '<' '>' declaration
72193326SedParser::DeclPtrTy
73193326SedParser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
74193326Sed                                                 SourceLocation &DeclEnd,
75193326Sed                                                 AccessSpecifier AS) {
76198092Srdivacky  assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
77198092Srdivacky         "Token does not start a template declaration.");
78198092Srdivacky
79193326Sed  // Enter template-parameter scope.
80193326Sed  ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
81193326Sed
82193326Sed  // Parse multiple levels of template headers within this template
83193326Sed  // parameter scope, e.g.,
84193326Sed  //
85193326Sed  //   template<typename T>
86193326Sed  //     template<typename U>
87193326Sed  //       class A<T>::B { ... };
88193326Sed  //
89193326Sed  // We parse multiple levels non-recursively so that we can build a
90193326Sed  // single data structure containing all of the template parameter
91193326Sed  // lists to easily differentiate between the case above and:
92193326Sed  //
93193326Sed  //   template<typename T>
94193326Sed  //   class A {
95193326Sed  //     template<typename U> class B;
96193326Sed  //   };
97193326Sed  //
98193326Sed  // In the first case, the action for declaring A<T>::B receives
99193326Sed  // both template parameter lists. In the second case, the action for
100193326Sed  // defining A<T>::B receives just the inner template parameter list
101193326Sed  // (and retrieves the outer template parameter list from its
102193326Sed  // context).
103198092Srdivacky  bool isSpecialization = true;
104198893Srdivacky  bool LastParamListWasEmpty = false;
105193326Sed  TemplateParameterLists ParamLists;
106198092Srdivacky  TemplateParameterDepthCounter Depth(TemplateParameterDepth);
107193326Sed  do {
108193326Sed    // Consume the 'export', if any.
109193326Sed    SourceLocation ExportLoc;
110193326Sed    if (Tok.is(tok::kw_export)) {
111193326Sed      ExportLoc = ConsumeToken();
112193326Sed    }
113193326Sed
114193326Sed    // Consume the 'template', which should be here.
115193326Sed    SourceLocation TemplateLoc;
116193326Sed    if (Tok.is(tok::kw_template)) {
117193326Sed      TemplateLoc = ConsumeToken();
118193326Sed    } else {
119193326Sed      Diag(Tok.getLocation(), diag::err_expected_template);
120193326Sed      return DeclPtrTy();
121193326Sed    }
122198092Srdivacky
123193326Sed    // Parse the '<' template-parameter-list '>'
124193326Sed    SourceLocation LAngleLoc, RAngleLoc;
125193326Sed    TemplateParameterList TemplateParams;
126198092Srdivacky    if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
127198092Srdivacky                                RAngleLoc)) {
128198092Srdivacky      // Skip until the semi-colon or a }.
129198092Srdivacky      SkipUntil(tok::r_brace, true, true);
130198092Srdivacky      if (Tok.is(tok::semi))
131198092Srdivacky        ConsumeToken();
132198092Srdivacky      return DeclPtrTy();
133198092Srdivacky    }
134193326Sed
135193326Sed    ParamLists.push_back(
136198092Srdivacky      Actions.ActOnTemplateParameterList(Depth, ExportLoc,
137198092Srdivacky                                         TemplateLoc, LAngleLoc,
138193326Sed                                         TemplateParams.data(),
139193326Sed                                         TemplateParams.size(), RAngleLoc));
140198092Srdivacky
141198092Srdivacky    if (!TemplateParams.empty()) {
142198092Srdivacky      isSpecialization = false;
143198092Srdivacky      ++Depth;
144198893Srdivacky    } else {
145198893Srdivacky      LastParamListWasEmpty = true;
146198092Srdivacky    }
147193326Sed  } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
148193326Sed
149193326Sed  // Parse the actual template declaration.
150198092Srdivacky  return ParseSingleDeclarationAfterTemplate(Context,
151193326Sed                                             ParsedTemplateInfo(&ParamLists,
152198893Srdivacky                                                             isSpecialization,
153198893Srdivacky                                                         LastParamListWasEmpty),
154193326Sed                                             DeclEnd, AS);
155193326Sed}
156193326Sed
157193326Sed/// \brief Parse a single declaration that declares a template,
158193326Sed/// template specialization, or explicit instantiation of a template.
159193326Sed///
160193326Sed/// \param TemplateParams if non-NULL, the template parameter lists
161193326Sed/// that preceded this declaration. In this case, the declaration is a
162193326Sed/// template declaration, out-of-line definition of a template, or an
163193326Sed/// explicit template specialization. When NULL, the declaration is an
164193326Sed/// explicit template instantiation.
165193326Sed///
166193326Sed/// \param TemplateLoc when TemplateParams is NULL, the location of
167193326Sed/// the 'template' keyword that indicates that we have an explicit
168193326Sed/// template instantiation.
169193326Sed///
170193326Sed/// \param DeclEnd will receive the source location of the last token
171193326Sed/// within this declaration.
172193326Sed///
173193326Sed/// \param AS the access specifier associated with this
174193326Sed/// declaration. Will be AS_none for namespace-scope declarations.
175193326Sed///
176193326Sed/// \returns the new declaration.
177198092SrdivackyParser::DeclPtrTy
178193326SedParser::ParseSingleDeclarationAfterTemplate(
179193326Sed                                       unsigned Context,
180193326Sed                                       const ParsedTemplateInfo &TemplateInfo,
181193326Sed                                       SourceLocation &DeclEnd,
182193326Sed                                       AccessSpecifier AS) {
183193326Sed  assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
184193326Sed         "Template information required");
185193326Sed
186198092Srdivacky  if (Context == Declarator::MemberContext) {
187198092Srdivacky    // We are parsing a member template.
188198092Srdivacky    ParseCXXClassMemberDeclaration(AS, TemplateInfo);
189198092Srdivacky    return DeclPtrTy::make((void*)0);
190198092Srdivacky  }
191198092Srdivacky
192193326Sed  // Parse the declaration specifiers.
193198893Srdivacky  ParsingDeclSpec DS(*this);
194193326Sed  ParseDeclarationSpecifiers(DS, TemplateInfo, AS);
195193326Sed
196193326Sed  if (Tok.is(tok::semi)) {
197193326Sed    DeclEnd = ConsumeToken();
198198893Srdivacky    DeclPtrTy Decl = Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
199198893Srdivacky    DS.complete(Decl);
200198893Srdivacky    return Decl;
201193326Sed  }
202193326Sed
203193326Sed  // Parse the declarator.
204198893Srdivacky  ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
205193326Sed  ParseDeclarator(DeclaratorInfo);
206193326Sed  // Error parsing the declarator?
207193326Sed  if (!DeclaratorInfo.hasName()) {
208193326Sed    // If so, skip until the semi-colon or a }.
209193326Sed    SkipUntil(tok::r_brace, true, true);
210193326Sed    if (Tok.is(tok::semi))
211193326Sed      ConsumeToken();
212193326Sed    return DeclPtrTy();
213193326Sed  }
214198092Srdivacky
215193326Sed  // If we have a declaration or declarator list, handle it.
216193326Sed  if (isDeclarationAfterDeclarator()) {
217193326Sed    // Parse this declaration.
218195099Sed    DeclPtrTy ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
219195099Sed                                                         TemplateInfo);
220193326Sed
221193326Sed    if (Tok.is(tok::comma)) {
222193326Sed      Diag(Tok, diag::err_multiple_template_declarators)
223193326Sed        << (int)TemplateInfo.Kind;
224193326Sed      SkipUntil(tok::semi, true, false);
225193326Sed      return ThisDecl;
226193326Sed    }
227193326Sed
228193326Sed    // Eat the semi colon after the declaration.
229198092Srdivacky    ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
230198893Srdivacky    DS.complete(ThisDecl);
231193326Sed    return ThisDecl;
232193326Sed  }
233193326Sed
234193326Sed  if (DeclaratorInfo.isFunctionDeclarator() &&
235193326Sed      isStartOfFunctionDefinition()) {
236193326Sed    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
237193326Sed      Diag(Tok, diag::err_function_declared_typedef);
238193326Sed
239193326Sed      if (Tok.is(tok::l_brace)) {
240193326Sed        // This recovery skips the entire function body. It would be nice
241193326Sed        // to simply call ParseFunctionDefinition() below, however Sema
242193326Sed        // assumes the declarator represents a function, not a typedef.
243193326Sed        ConsumeBrace();
244193326Sed        SkipUntil(tok::r_brace, true);
245193326Sed      } else {
246193326Sed        SkipUntil(tok::semi);
247193326Sed      }
248193326Sed      return DeclPtrTy();
249193326Sed    }
250195099Sed    return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo);
251193326Sed  }
252193326Sed
253193326Sed  if (DeclaratorInfo.isFunctionDeclarator())
254193326Sed    Diag(Tok, diag::err_expected_fn_body);
255193326Sed  else
256193326Sed    Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
257193326Sed  SkipUntil(tok::semi);
258193326Sed  return DeclPtrTy();
259193326Sed}
260193326Sed
261193326Sed/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
262193326Sed/// angle brackets. Depth is the depth of this template-parameter-list, which
263193326Sed/// is the number of template headers directly enclosing this template header.
264193326Sed/// TemplateParams is the current list of template parameters we're building.
265193326Sed/// The template parameter we parse will be added to this list. LAngleLoc and
266198092Srdivacky/// RAngleLoc will receive the positions of the '<' and '>', respectively,
267193326Sed/// that enclose this template parameter list.
268198092Srdivacky///
269198092Srdivacky/// \returns true if an error occurred, false otherwise.
270193326Sedbool Parser::ParseTemplateParameters(unsigned Depth,
271193326Sed                                     TemplateParameterList &TemplateParams,
272193326Sed                                     SourceLocation &LAngleLoc,
273193326Sed                                     SourceLocation &RAngleLoc) {
274193326Sed  // Get the template parameter list.
275198092Srdivacky  if (!Tok.is(tok::less)) {
276193326Sed    Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
277198092Srdivacky    return true;
278193326Sed  }
279193326Sed  LAngleLoc = ConsumeToken();
280198092Srdivacky
281193326Sed  // Try to parse the template parameter list.
282193326Sed  if (Tok.is(tok::greater))
283193326Sed    RAngleLoc = ConsumeToken();
284198092Srdivacky  else if (ParseTemplateParameterList(Depth, TemplateParams)) {
285198092Srdivacky    if (!Tok.is(tok::greater)) {
286193326Sed      Diag(Tok.getLocation(), diag::err_expected_greater);
287198092Srdivacky      return true;
288193326Sed    }
289193326Sed    RAngleLoc = ConsumeToken();
290193326Sed  }
291198092Srdivacky  return false;
292193326Sed}
293193326Sed
294193326Sed/// ParseTemplateParameterList - Parse a template parameter list. If
295193326Sed/// the parsing fails badly (i.e., closing bracket was left out), this
296193326Sed/// will try to put the token stream in a reasonable position (closing
297198092Srdivacky/// a statement, etc.) and return false.
298193326Sed///
299193326Sed///       template-parameter-list:    [C++ temp]
300193326Sed///         template-parameter
301193326Sed///         template-parameter-list ',' template-parameter
302198092Srdivackybool
303193326SedParser::ParseTemplateParameterList(unsigned Depth,
304193326Sed                                   TemplateParameterList &TemplateParams) {
305198092Srdivacky  while (1) {
306193326Sed    if (DeclPtrTy TmpParam
307193326Sed          = ParseTemplateParameter(Depth, TemplateParams.size())) {
308193326Sed      TemplateParams.push_back(TmpParam);
309193326Sed    } else {
310193326Sed      // If we failed to parse a template parameter, skip until we find
311193326Sed      // a comma or closing brace.
312193326Sed      SkipUntil(tok::comma, tok::greater, true, true);
313193326Sed    }
314198092Srdivacky
315193326Sed    // Did we find a comma or the end of the template parmeter list?
316198092Srdivacky    if (Tok.is(tok::comma)) {
317193326Sed      ConsumeToken();
318198092Srdivacky    } else if (Tok.is(tok::greater)) {
319193326Sed      // Don't consume this... that's done by template parser.
320193326Sed      break;
321193326Sed    } else {
322193326Sed      // Somebody probably forgot to close the template. Skip ahead and
323193326Sed      // try to get out of the expression. This error is currently
324193326Sed      // subsumed by whatever goes on in ParseTemplateParameter.
325193326Sed      // TODO: This could match >>, and it would be nice to avoid those
326193326Sed      // silly errors with template <vec<T>>.
327193326Sed      // Diag(Tok.getLocation(), diag::err_expected_comma_greater);
328193326Sed      SkipUntil(tok::greater, true, true);
329193326Sed      return false;
330193326Sed    }
331193326Sed  }
332193326Sed  return true;
333193326Sed}
334193326Sed
335193326Sed/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
336193326Sed///
337193326Sed///       template-parameter: [C++ temp.param]
338193326Sed///         type-parameter
339193326Sed///         parameter-declaration
340193326Sed///
341193326Sed///       type-parameter: (see below)
342194179Sed///         'class' ...[opt][C++0x] identifier[opt]
343193326Sed///         'class' identifier[opt] '=' type-id
344194179Sed///         'typename' ...[opt][C++0x] identifier[opt]
345193326Sed///         'typename' identifier[opt] '=' type-id
346194179Sed///         'template' ...[opt][C++0x] '<' template-parameter-list '>' 'class' identifier[opt]
347193326Sed///         'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
348198092SrdivackyParser::DeclPtrTy
349193326SedParser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
350198092Srdivacky  if (Tok.is(tok::kw_class) ||
351198092Srdivacky      (Tok.is(tok::kw_typename) &&
352198092Srdivacky       // FIXME: Next token has not been annotated!
353198092Srdivacky       NextToken().isNot(tok::annot_typename))) {
354193326Sed    return ParseTypeParameter(Depth, Position);
355193326Sed  }
356198092Srdivacky
357198092Srdivacky  if (Tok.is(tok::kw_template))
358193326Sed    return ParseTemplateTemplateParameter(Depth, Position);
359193326Sed
360193326Sed  // If it's none of the above, then it must be a parameter declaration.
361193326Sed  // NOTE: This will pick up errors in the closure of the template parameter
362193326Sed  // list (e.g., template < ; Check here to implement >> style closures.
363193326Sed  return ParseNonTypeTemplateParameter(Depth, Position);
364193326Sed}
365193326Sed
366193326Sed/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
367193326Sed/// Other kinds of template parameters are parsed in
368193326Sed/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
369193326Sed///
370193326Sed///       type-parameter:     [C++ temp.param]
371194179Sed///         'class' ...[opt][C++0x] identifier[opt]
372193326Sed///         'class' identifier[opt] '=' type-id
373194179Sed///         'typename' ...[opt][C++0x] identifier[opt]
374193326Sed///         'typename' identifier[opt] '=' type-id
375193326SedParser::DeclPtrTy Parser::ParseTypeParameter(unsigned Depth, unsigned Position){
376193326Sed  assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
377198092Srdivacky         "A type-parameter starts with 'class' or 'typename'");
378193326Sed
379193326Sed  // Consume the 'class' or 'typename' keyword.
380193326Sed  bool TypenameKeyword = Tok.is(tok::kw_typename);
381193326Sed  SourceLocation KeyLoc = ConsumeToken();
382193326Sed
383194179Sed  // Grab the ellipsis (if given).
384194179Sed  bool Ellipsis = false;
385194179Sed  SourceLocation EllipsisLoc;
386194179Sed  if (Tok.is(tok::ellipsis)) {
387194179Sed    Ellipsis = true;
388194179Sed    EllipsisLoc = ConsumeToken();
389198092Srdivacky
390198092Srdivacky    if (!getLang().CPlusPlus0x)
391194179Sed      Diag(EllipsisLoc, diag::err_variadic_templates);
392194179Sed  }
393198092Srdivacky
394193326Sed  // Grab the template parameter name (if given)
395193326Sed  SourceLocation NameLoc;
396193326Sed  IdentifierInfo* ParamName = 0;
397198092Srdivacky  if (Tok.is(tok::identifier)) {
398193326Sed    ParamName = Tok.getIdentifierInfo();
399193326Sed    NameLoc = ConsumeToken();
400198092Srdivacky  } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
401198092Srdivacky            Tok.is(tok::greater)) {
402193326Sed    // Unnamed template parameter. Don't have to do anything here, just
403193326Sed    // don't consume this token.
404193326Sed  } else {
405193326Sed    Diag(Tok.getLocation(), diag::err_expected_ident);
406193326Sed    return DeclPtrTy();
407193326Sed  }
408198092Srdivacky
409193326Sed  DeclPtrTy TypeParam = Actions.ActOnTypeParameter(CurScope, TypenameKeyword,
410194179Sed                                                   Ellipsis, EllipsisLoc,
411193326Sed                                                   KeyLoc, ParamName, NameLoc,
412193326Sed                                                   Depth, Position);
413193326Sed
414193326Sed  // Grab a default type id (if given).
415198092Srdivacky  if (Tok.is(tok::equal)) {
416193326Sed    SourceLocation EqualLoc = ConsumeToken();
417193326Sed    SourceLocation DefaultLoc = Tok.getLocation();
418193326Sed    TypeResult DefaultType = ParseTypeName();
419193326Sed    if (!DefaultType.isInvalid())
420193326Sed      Actions.ActOnTypeParameterDefault(TypeParam, EqualLoc, DefaultLoc,
421193326Sed                                        DefaultType.get());
422193326Sed  }
423198092Srdivacky
424193326Sed  return TypeParam;
425193326Sed}
426193326Sed
427193326Sed/// ParseTemplateTemplateParameter - Handle the parsing of template
428198092Srdivacky/// template parameters.
429193326Sed///
430193326Sed///       type-parameter:    [C++ temp.param]
431193326Sed///         'template' '<' template-parameter-list '>' 'class' identifier[opt]
432193326Sed///         'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
433193326SedParser::DeclPtrTy
434193326SedParser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
435193326Sed  assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
436193326Sed
437193326Sed  // Handle the template <...> part.
438193326Sed  SourceLocation TemplateLoc = ConsumeToken();
439198092Srdivacky  TemplateParameterList TemplateParams;
440193326Sed  SourceLocation LAngleLoc, RAngleLoc;
441193326Sed  {
442193326Sed    ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
443198092Srdivacky    if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
444198092Srdivacky                               RAngleLoc)) {
445193326Sed      return DeclPtrTy();
446193326Sed    }
447193326Sed  }
448193326Sed
449193326Sed  // Generate a meaningful error if the user forgot to put class before the
450193326Sed  // identifier, comma, or greater.
451198092Srdivacky  if (!Tok.is(tok::kw_class)) {
452198092Srdivacky    Diag(Tok.getLocation(), diag::err_expected_class_before)
453193326Sed      << PP.getSpelling(Tok);
454193326Sed    return DeclPtrTy();
455193326Sed  }
456193326Sed  SourceLocation ClassLoc = ConsumeToken();
457193326Sed
458193326Sed  // Get the identifier, if given.
459193326Sed  SourceLocation NameLoc;
460193326Sed  IdentifierInfo* ParamName = 0;
461198092Srdivacky  if (Tok.is(tok::identifier)) {
462193326Sed    ParamName = Tok.getIdentifierInfo();
463193326Sed    NameLoc = ConsumeToken();
464198092Srdivacky  } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
465193326Sed    // Unnamed template parameter. Don't have to do anything here, just
466193326Sed    // don't consume this token.
467193326Sed  } else {
468193326Sed    Diag(Tok.getLocation(), diag::err_expected_ident);
469193326Sed    return DeclPtrTy();
470193326Sed  }
471193326Sed
472198092Srdivacky  TemplateParamsTy *ParamList =
473193326Sed    Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
474193326Sed                                       TemplateLoc, LAngleLoc,
475198092Srdivacky                                       &TemplateParams[0],
476193326Sed                                       TemplateParams.size(),
477193326Sed                                       RAngleLoc);
478193326Sed
479193326Sed  Parser::DeclPtrTy Param
480193326Sed    = Actions.ActOnTemplateTemplateParameter(CurScope, TemplateLoc,
481193326Sed                                             ParamList, ParamName,
482193326Sed                                             NameLoc, Depth, Position);
483193326Sed
484193326Sed  // Get the a default value, if given.
485193326Sed  if (Tok.is(tok::equal)) {
486193326Sed    SourceLocation EqualLoc = ConsumeToken();
487193326Sed    OwningExprResult DefaultExpr = ParseCXXIdExpression();
488193326Sed    if (DefaultExpr.isInvalid())
489193326Sed      return Param;
490193326Sed    else if (Param)
491193326Sed      Actions.ActOnTemplateTemplateParameterDefault(Param, EqualLoc,
492193326Sed                                                    move(DefaultExpr));
493193326Sed  }
494193326Sed
495193326Sed  return Param;
496193326Sed}
497193326Sed
498193326Sed/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
499198092Srdivacky/// template parameters (e.g., in "template<int Size> class array;").
500193326Sed///
501193326Sed///       template-parameter:
502193326Sed///         ...
503193326Sed///         parameter-declaration
504193326Sed///
505193326Sed/// NOTE: It would be ideal to simply call out to ParseParameterDeclaration(),
506193326Sed/// but that didn't work out to well. Instead, this tries to recrate the basic
507193326Sed/// parsing of parameter declarations, but tries to constrain it for template
508193326Sed/// parameters.
509193326Sed/// FIXME: We need to make a ParseParameterDeclaration that works for
510193326Sed/// non-type template parameters and normal function parameters.
511198092SrdivackyParser::DeclPtrTy
512193326SedParser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
513193326Sed  SourceLocation StartLoc = Tok.getLocation();
514193326Sed
515193326Sed  // Parse the declaration-specifiers (i.e., the type).
516193326Sed  // FIXME: The type should probably be restricted in some way... Not all
517193326Sed  // declarators (parts of declarators?) are accepted for parameters.
518193326Sed  DeclSpec DS;
519193326Sed  ParseDeclarationSpecifiers(DS);
520193326Sed
521193326Sed  // Parse this as a typename.
522193326Sed  Declarator ParamDecl(DS, Declarator::TemplateParamContext);
523193326Sed  ParseDeclarator(ParamDecl);
524193326Sed  if (DS.getTypeSpecType() == DeclSpec::TST_unspecified && !DS.getTypeRep()) {
525193326Sed    // This probably shouldn't happen - and it's more of a Sema thing, but
526193326Sed    // basically we didn't parse the type name because we couldn't associate
527193326Sed    // it with an AST node. we should just skip to the comma or greater.
528193326Sed    // TODO: This is currently a placeholder for some kind of Sema Error.
529193326Sed    Diag(Tok.getLocation(), diag::err_parse_error);
530193326Sed    SkipUntil(tok::comma, tok::greater, true, true);
531193326Sed    return DeclPtrTy();
532193326Sed  }
533193326Sed
534198092Srdivacky  // Create the parameter.
535193326Sed  DeclPtrTy Param = Actions.ActOnNonTypeTemplateParameter(CurScope, ParamDecl,
536193326Sed                                                          Depth, Position);
537193326Sed
538193326Sed  // If there is a default value, parse it.
539193326Sed  if (Tok.is(tok::equal)) {
540193326Sed    SourceLocation EqualLoc = ConsumeToken();
541193326Sed
542193326Sed    // C++ [temp.param]p15:
543193326Sed    //   When parsing a default template-argument for a non-type
544193326Sed    //   template-parameter, the first non-nested > is taken as the
545193326Sed    //   end of the template-parameter-list rather than a greater-than
546193326Sed    //   operator.
547198092Srdivacky    GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
548193326Sed
549193326Sed    OwningExprResult DefaultArg = ParseAssignmentExpression();
550193326Sed    if (DefaultArg.isInvalid())
551193326Sed      SkipUntil(tok::comma, tok::greater, true, true);
552193326Sed    else if (Param)
553198092Srdivacky      Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc,
554193326Sed                                                   move(DefaultArg));
555193326Sed  }
556198092Srdivacky
557193326Sed  return Param;
558193326Sed}
559193326Sed
560193326Sed/// \brief Parses a template-id that after the template name has
561193326Sed/// already been parsed.
562193326Sed///
563193326Sed/// This routine takes care of parsing the enclosed template argument
564193326Sed/// list ('<' template-parameter-list [opt] '>') and placing the
565193326Sed/// results into a form that can be transferred to semantic analysis.
566193326Sed///
567193326Sed/// \param Template the template declaration produced by isTemplateName
568193326Sed///
569193326Sed/// \param TemplateNameLoc the source location of the template name
570193326Sed///
571193326Sed/// \param SS if non-NULL, the nested-name-specifier preceding the
572193326Sed/// template name.
573193326Sed///
574193326Sed/// \param ConsumeLastToken if true, then we will consume the last
575193326Sed/// token that forms the template-id. Otherwise, we will leave the
576193326Sed/// last token in the stream (e.g., so that it can be replaced with an
577193326Sed/// annotation token).
578198092Srdivackybool
579193326SedParser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
580198092Srdivacky                                         SourceLocation TemplateNameLoc,
581193326Sed                                         const CXXScopeSpec *SS,
582193326Sed                                         bool ConsumeLastToken,
583193326Sed                                         SourceLocation &LAngleLoc,
584193326Sed                                         TemplateArgList &TemplateArgs,
585193326Sed                                    TemplateArgIsTypeList &TemplateArgIsType,
586193326Sed                               TemplateArgLocationList &TemplateArgLocations,
587193326Sed                                         SourceLocation &RAngleLoc) {
588193326Sed  assert(Tok.is(tok::less) && "Must have already parsed the template-name");
589193326Sed
590193326Sed  // Consume the '<'.
591193326Sed  LAngleLoc = ConsumeToken();
592193326Sed
593193326Sed  // Parse the optional template-argument-list.
594193326Sed  bool Invalid = false;
595193326Sed  {
596193326Sed    GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
597193326Sed    if (Tok.isNot(tok::greater))
598193326Sed      Invalid = ParseTemplateArgumentList(TemplateArgs, TemplateArgIsType,
599193326Sed                                          TemplateArgLocations);
600193326Sed
601193326Sed    if (Invalid) {
602193326Sed      // Try to find the closing '>'.
603193326Sed      SkipUntil(tok::greater, true, !ConsumeLastToken);
604193326Sed
605193326Sed      return true;
606193326Sed    }
607193326Sed  }
608193326Sed
609193326Sed  if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
610193326Sed    return true;
611193326Sed
612193326Sed  // Determine the location of the '>' or '>>'. Only consume this
613193326Sed  // token if the caller asked us to.
614193326Sed  RAngleLoc = Tok.getLocation();
615193326Sed
616193326Sed  if (Tok.is(tok::greatergreater)) {
617193326Sed    if (!getLang().CPlusPlus0x) {
618193326Sed      const char *ReplaceStr = "> >";
619193326Sed      if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
620193326Sed        ReplaceStr = "> > ";
621193326Sed
622193326Sed      Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
623193326Sed        << CodeModificationHint::CreateReplacement(
624193326Sed                                 SourceRange(Tok.getLocation()), ReplaceStr);
625193326Sed    }
626193326Sed
627193326Sed    Tok.setKind(tok::greater);
628193326Sed    if (!ConsumeLastToken) {
629193326Sed      // Since we're not supposed to consume the '>>' token, we need
630193326Sed      // to insert a second '>' token after the first.
631193326Sed      PP.EnterToken(Tok);
632193326Sed    }
633193326Sed  } else if (ConsumeLastToken)
634193326Sed    ConsumeToken();
635193326Sed
636193326Sed  return false;
637193326Sed}
638198092Srdivacky
639193326Sed/// \brief Replace the tokens that form a simple-template-id with an
640193326Sed/// annotation token containing the complete template-id.
641193326Sed///
642193326Sed/// The first token in the stream must be the name of a template that
643193326Sed/// is followed by a '<'. This routine will parse the complete
644193326Sed/// simple-template-id and replace the tokens with a single annotation
645193326Sed/// token with one of two different kinds: if the template-id names a
646193326Sed/// type (and \p AllowTypeAnnotation is true), the annotation token is
647193326Sed/// a type annotation that includes the optional nested-name-specifier
648193326Sed/// (\p SS). Otherwise, the annotation token is a template-id
649193326Sed/// annotation that does not include the optional
650193326Sed/// nested-name-specifier.
651193326Sed///
652193326Sed/// \param Template  the declaration of the template named by the first
653193326Sed/// token (an identifier), as returned from \c Action::isTemplateName().
654193326Sed///
655193326Sed/// \param TemplateNameKind the kind of template that \p Template
656193326Sed/// refers to, as returned from \c Action::isTemplateName().
657193326Sed///
658193326Sed/// \param SS if non-NULL, the nested-name-specifier that precedes
659193326Sed/// this template name.
660193326Sed///
661193326Sed/// \param TemplateKWLoc if valid, specifies that this template-id
662193326Sed/// annotation was preceded by the 'template' keyword and gives the
663193326Sed/// location of that keyword. If invalid (the default), then this
664193326Sed/// template-id was not preceded by a 'template' keyword.
665193326Sed///
666193326Sed/// \param AllowTypeAnnotation if true (the default), then a
667193326Sed/// simple-template-id that refers to a class template, template
668193326Sed/// template parameter, or other template that produces a type will be
669193326Sed/// replaced with a type annotation token. Otherwise, the
670193326Sed/// simple-template-id is always replaced with a template-id
671193326Sed/// annotation token.
672195099Sed///
673195099Sed/// If an unrecoverable parse error occurs and no annotation token can be
674195099Sed/// formed, this function returns true.
675195099Sed///
676195099Sedbool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
677198092Srdivacky                                     const CXXScopeSpec *SS,
678198893Srdivacky                                     UnqualifiedId &TemplateName,
679193326Sed                                     SourceLocation TemplateKWLoc,
680193326Sed                                     bool AllowTypeAnnotation) {
681193326Sed  assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
682198893Srdivacky  assert(Template && Tok.is(tok::less) &&
683193326Sed         "Parser isn't at the beginning of a template-id");
684193326Sed
685193326Sed  // Consume the template-name.
686198893Srdivacky  SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
687193326Sed
688193326Sed  // Parse the enclosed template argument list.
689193326Sed  SourceLocation LAngleLoc, RAngleLoc;
690193326Sed  TemplateArgList TemplateArgs;
691193326Sed  TemplateArgIsTypeList TemplateArgIsType;
692193326Sed  TemplateArgLocationList TemplateArgLocations;
693198893Srdivacky  bool Invalid = ParseTemplateIdAfterTemplateName(Template,
694198893Srdivacky                                                  TemplateNameLoc,
695198092Srdivacky                                                  SS, false, LAngleLoc,
696198092Srdivacky                                                  TemplateArgs,
697193326Sed                                                  TemplateArgIsType,
698193326Sed                                                  TemplateArgLocations,
699193326Sed                                                  RAngleLoc);
700198092Srdivacky
701195099Sed  if (Invalid) {
702195099Sed    // If we failed to parse the template ID but skipped ahead to a >, we're not
703195099Sed    // going to be able to form a token annotation.  Eat the '>' if present.
704195099Sed    if (Tok.is(tok::greater))
705195099Sed      ConsumeToken();
706195099Sed    return true;
707195099Sed  }
708193326Sed
709193326Sed  ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
710193326Sed                                     TemplateArgIsType.data(),
711193326Sed                                     TemplateArgs.size());
712193326Sed
713193326Sed  // Build the annotation token.
714193326Sed  if (TNK == TNK_Type_template && AllowTypeAnnotation) {
715198092Srdivacky    Action::TypeResult Type
716193326Sed      = Actions.ActOnTemplateIdType(Template, TemplateNameLoc,
717193326Sed                                    LAngleLoc, TemplateArgsPtr,
718193326Sed                                    &TemplateArgLocations[0],
719193326Sed                                    RAngleLoc);
720195099Sed    if (Type.isInvalid()) {
721195099Sed      // If we failed to parse the template ID but skipped ahead to a >, we're not
722195099Sed      // going to be able to form a token annotation.  Eat the '>' if present.
723195099Sed      if (Tok.is(tok::greater))
724195099Sed        ConsumeToken();
725195099Sed      return true;
726195099Sed    }
727193326Sed
728193326Sed    Tok.setKind(tok::annot_typename);
729193326Sed    Tok.setAnnotationValue(Type.get());
730193326Sed    if (SS && SS->isNotEmpty())
731193326Sed      Tok.setLocation(SS->getBeginLoc());
732193326Sed    else if (TemplateKWLoc.isValid())
733193326Sed      Tok.setLocation(TemplateKWLoc);
734198092Srdivacky    else
735193326Sed      Tok.setLocation(TemplateNameLoc);
736193326Sed  } else {
737193326Sed    // Build a template-id annotation token that can be processed
738193326Sed    // later.
739193326Sed    Tok.setKind(tok::annot_template_id);
740198092Srdivacky    TemplateIdAnnotation *TemplateId
741193326Sed      = TemplateIdAnnotation::Allocate(TemplateArgs.size());
742193326Sed    TemplateId->TemplateNameLoc = TemplateNameLoc;
743198893Srdivacky    if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
744198893Srdivacky      TemplateId->Name = TemplateName.Identifier;
745198893Srdivacky      TemplateId->Operator = OO_None;
746198893Srdivacky    } else {
747198893Srdivacky      TemplateId->Name = 0;
748198893Srdivacky      TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
749198893Srdivacky    }
750193326Sed    TemplateId->Template = Template.getAs<void*>();
751193326Sed    TemplateId->Kind = TNK;
752193326Sed    TemplateId->LAngleLoc = LAngleLoc;
753193326Sed    TemplateId->RAngleLoc = RAngleLoc;
754193326Sed    void **Args = TemplateId->getTemplateArgs();
755193326Sed    bool *ArgIsType = TemplateId->getTemplateArgIsType();
756193326Sed    SourceLocation *ArgLocs = TemplateId->getTemplateArgLocations();
757193326Sed    for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) {
758193326Sed      Args[Arg] = TemplateArgs[Arg];
759193326Sed      ArgIsType[Arg] = TemplateArgIsType[Arg];
760193326Sed      ArgLocs[Arg] = TemplateArgLocations[Arg];
761193326Sed    }
762193326Sed    Tok.setAnnotationValue(TemplateId);
763193326Sed    if (TemplateKWLoc.isValid())
764193326Sed      Tok.setLocation(TemplateKWLoc);
765193326Sed    else
766193326Sed      Tok.setLocation(TemplateNameLoc);
767193326Sed
768193326Sed    TemplateArgsPtr.release();
769193326Sed  }
770193326Sed
771193326Sed  // Common fields for the annotation token
772193326Sed  Tok.setAnnotationEndLoc(RAngleLoc);
773193326Sed
774193326Sed  // In case the tokens were cached, have Preprocessor replace them with the
775193326Sed  // annotation token.
776193326Sed  PP.AnnotateCachedTokens(Tok);
777195099Sed  return false;
778193326Sed}
779193326Sed
780193326Sed/// \brief Replaces a template-id annotation token with a type
781193326Sed/// annotation token.
782193326Sed///
783193326Sed/// If there was a failure when forming the type from the template-id,
784193326Sed/// a type annotation token will still be created, but will have a
785193326Sed/// NULL type pointer to signify an error.
786193326Sedvoid Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
787193326Sed  assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
788193326Sed
789198092Srdivacky  TemplateIdAnnotation *TemplateId
790193326Sed    = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
791193326Sed  assert((TemplateId->Kind == TNK_Type_template ||
792193326Sed          TemplateId->Kind == TNK_Dependent_template_name) &&
793193326Sed         "Only works for type and dependent templates");
794198092Srdivacky
795198092Srdivacky  ASTTemplateArgsPtr TemplateArgsPtr(Actions,
796193326Sed                                     TemplateId->getTemplateArgs(),
797193326Sed                                     TemplateId->getTemplateArgIsType(),
798193326Sed                                     TemplateId->NumArgs);
799193326Sed
800198092Srdivacky  Action::TypeResult Type
801193326Sed    = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
802193326Sed                                  TemplateId->TemplateNameLoc,
803198092Srdivacky                                  TemplateId->LAngleLoc,
804193326Sed                                  TemplateArgsPtr,
805193326Sed                                  TemplateId->getTemplateArgLocations(),
806193326Sed                                  TemplateId->RAngleLoc);
807193326Sed  // Create the new "type" annotation token.
808193326Sed  Tok.setKind(tok::annot_typename);
809193326Sed  Tok.setAnnotationValue(Type.isInvalid()? 0 : Type.get());
810193326Sed  if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
811193326Sed    Tok.setLocation(SS->getBeginLoc());
812198954Srdivacky  Tok.setAnnotationEndLoc(TemplateId->TemplateNameLoc);
813193326Sed
814198954Srdivacky  // Replace the template-id annotation token, and possible the scope-specifier
815198954Srdivacky  // that precedes it, with the typename annotation token.
816198954Srdivacky  PP.AnnotateCachedTokens(Tok);
817193326Sed  TemplateId->Destroy();
818193326Sed}
819193326Sed
820193326Sed/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
821193326Sed///
822193326Sed///       template-argument: [C++ 14.2]
823194711Sed///         constant-expression
824193326Sed///         type-id
825193326Sed///         id-expression
826193326Sedvoid *Parser::ParseTemplateArgument(bool &ArgIsType) {
827193326Sed  // C++ [temp.arg]p2:
828193326Sed  //   In a template-argument, an ambiguity between a type-id and an
829193326Sed  //   expression is resolved to a type-id, regardless of the form of
830193326Sed  //   the corresponding template-parameter.
831193326Sed  //
832193326Sed  // Therefore, we initially try to parse a type-id.
833193326Sed  if (isCXXTypeId(TypeIdAsTemplateArgument)) {
834193326Sed    ArgIsType = true;
835193326Sed    TypeResult TypeArg = ParseTypeName();
836193326Sed    if (TypeArg.isInvalid())
837193326Sed      return 0;
838193326Sed    return TypeArg.get();
839193326Sed  }
840193326Sed
841194711Sed  OwningExprResult ExprArg = ParseConstantExpression();
842193326Sed  if (ExprArg.isInvalid() || !ExprArg.get())
843193326Sed    return 0;
844193326Sed
845193326Sed  ArgIsType = false;
846193326Sed  return ExprArg.release();
847193326Sed}
848193326Sed
849193326Sed/// ParseTemplateArgumentList - Parse a C++ template-argument-list
850193326Sed/// (C++ [temp.names]). Returns true if there was an error.
851193326Sed///
852193326Sed///       template-argument-list: [C++ 14.2]
853193326Sed///         template-argument
854193326Sed///         template-argument-list ',' template-argument
855198092Srdivackybool
856193326SedParser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
857193326Sed                                  TemplateArgIsTypeList &TemplateArgIsType,
858193326Sed                              TemplateArgLocationList &TemplateArgLocations) {
859193326Sed  while (true) {
860193326Sed    bool IsType = false;
861193326Sed    SourceLocation Loc = Tok.getLocation();
862193326Sed    void *Arg = ParseTemplateArgument(IsType);
863193326Sed    if (Arg) {
864193326Sed      TemplateArgs.push_back(Arg);
865193326Sed      TemplateArgIsType.push_back(IsType);
866193326Sed      TemplateArgLocations.push_back(Loc);
867193326Sed    } else {
868193326Sed      SkipUntil(tok::comma, tok::greater, true, true);
869193326Sed      return true;
870193326Sed    }
871193326Sed
872193326Sed    // If the next token is a comma, consume it and keep reading
873193326Sed    // arguments.
874193326Sed    if (Tok.isNot(tok::comma)) break;
875193326Sed
876193326Sed    // Consume the comma.
877193326Sed    ConsumeToken();
878193326Sed  }
879193326Sed
880193326Sed  return Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater);
881193326Sed}
882193326Sed
883198092Srdivacky/// \brief Parse a C++ explicit template instantiation
884193326Sed/// (C++ [temp.explicit]).
885193326Sed///
886193326Sed///       explicit-instantiation:
887198092Srdivacky///         'extern' [opt] 'template' declaration
888198092Srdivacky///
889198092Srdivacky/// Note that the 'extern' is a GNU extension and C++0x feature.
890198092SrdivackyParser::DeclPtrTy
891198092SrdivackyParser::ParseExplicitInstantiation(SourceLocation ExternLoc,
892198092Srdivacky                                   SourceLocation TemplateLoc,
893193326Sed                                   SourceLocation &DeclEnd) {
894198092Srdivacky  return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
895198092Srdivacky                                             ParsedTemplateInfo(ExternLoc,
896198092Srdivacky                                                                TemplateLoc),
897193326Sed                                             DeclEnd, AS_none);
898193326Sed}
899