DeclTemplate.h revision 7b0b83f39b4db3fa3c48cc7bb2ca11a365da13f7
1//===-- DeclTemplate.h - Classes for representing C++ templates -*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the C++ template declaration subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
15#define LLVM_CLANG_AST_DECLTEMPLATE_H
16
17#include "clang/AST/DeclCXX.h"
18#include "llvm/ADT/APSInt.h"
19#include "llvm/ADT/FoldingSet.h"
20#include "llvm/ADT/PointerUnion.h"
21#include <limits>
22
23namespace clang {
24
25class TemplateParameterList;
26class TemplateDecl;
27class FunctionTemplateDecl;
28class ClassTemplateDecl;
29class ClassTemplatePartialSpecializationDecl;
30class TemplateTypeParmDecl;
31class NonTypeTemplateParmDecl;
32class TemplateTemplateParmDecl;
33
34/// \brief Stores a template parameter of any kind.
35typedef llvm::PointerUnion3<TemplateTypeParmDecl*, NonTypeTemplateParmDecl*,
36                            TemplateTemplateParmDecl*> TemplateParameter;
37
38/// TemplateParameterList - Stores a list of template parameters for a
39/// TemplateDecl and its derived classes.
40class TemplateParameterList {
41  /// The location of the 'template' keyword.
42  SourceLocation TemplateLoc;
43
44  /// The locations of the '<' and '>' angle brackets.
45  SourceLocation LAngleLoc, RAngleLoc;
46
47  /// The number of template parameters in this template
48  /// parameter list.
49  unsigned NumParams;
50
51  TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
52                        Decl **Params, unsigned NumParams,
53                        SourceLocation RAngleLoc);
54
55public:
56  static TemplateParameterList *Create(ASTContext &C,
57                                       SourceLocation TemplateLoc,
58                                       SourceLocation LAngleLoc,
59                                       Decl **Params,
60                                       unsigned NumParams,
61                                       SourceLocation RAngleLoc);
62
63  /// iterator - Iterates through the template parameters in this list.
64  typedef Decl** iterator;
65
66  /// const_iterator - Iterates through the template parameters in this list.
67  typedef Decl* const* const_iterator;
68
69  iterator begin() { return reinterpret_cast<Decl **>(this + 1); }
70  const_iterator begin() const {
71    return reinterpret_cast<Decl * const *>(this + 1);
72  }
73  iterator end() { return begin() + NumParams; }
74  const_iterator end() const { return begin() + NumParams; }
75
76  unsigned size() const { return NumParams; }
77
78  Decl* getParam(unsigned Idx) {
79    assert(Idx < size() && "Template parameter index out-of-range");
80    return begin()[Idx];
81  }
82
83  const Decl* getParam(unsigned Idx) const {
84    assert(Idx < size() && "Template parameter index out-of-range");
85    return begin()[Idx];
86  }
87
88  /// \btief Returns the minimum number of arguments needed to form a
89  /// template specialization. This may be fewer than the number of
90  /// template parameters, if some of the parameters have default
91  /// arguments or if there is a parameter pack.
92  unsigned getMinRequiredArguments() const;
93
94  SourceLocation getTemplateLoc() const { return TemplateLoc; }
95  SourceLocation getLAngleLoc() const { return LAngleLoc; }
96  SourceLocation getRAngleLoc() const { return RAngleLoc; }
97
98  SourceRange getSourceRange() const {
99    return SourceRange(TemplateLoc, RAngleLoc);
100  }
101};
102
103/// \brief Represents a template argument within a class template
104/// specialization.
105class TemplateArgument {
106  union {
107    uintptr_t TypeOrValue;
108    struct {
109      char Value[sizeof(llvm::APSInt)];
110      void *Type;
111    } Integer;
112    struct {
113      TemplateArgument *Args;
114      unsigned NumArgs;
115      bool CopyArgs;
116    } Args;
117  };
118
119  /// \brief Location of the beginning of this template argument.
120  SourceLocation StartLoc;
121
122public:
123  /// \brief The type of template argument we're storing.
124  enum ArgKind {
125    Null = 0,
126    /// The template argument is a type. Its value is stored in the
127    /// TypeOrValue field.
128    Type = 1,
129    /// The template argument is a declaration
130    Declaration = 2,
131    /// The template argument is an integral value stored in an llvm::APSInt.
132    Integral = 3,
133    /// The template argument is a value- or type-dependent expression
134    /// stored in an Expr*.
135    Expression = 4,
136
137    /// The template argument is actually a parameter pack. Arguments are stored
138    /// in the Args struct.
139    Pack = 5
140  } Kind;
141
142  /// \brief Construct an empty, invalid template argument.
143  TemplateArgument() : TypeOrValue(0), StartLoc(), Kind(Null) { }
144
145  /// \brief Construct a template type argument.
146  TemplateArgument(SourceLocation Loc, QualType T) : Kind(Type) {
147    TypeOrValue = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
148    StartLoc = Loc;
149  }
150
151  /// \brief Construct a template argument that refers to a
152  /// declaration, which is either an external declaration or a
153  /// template declaration.
154  TemplateArgument(SourceLocation Loc, Decl *D) : Kind(Declaration) {
155    // FIXME: Need to be sure we have the "canonical" declaration!
156    TypeOrValue = reinterpret_cast<uintptr_t>(D);
157    StartLoc = Loc;
158  }
159
160  /// \brief Construct an integral constant template argument.
161  TemplateArgument(SourceLocation Loc, const llvm::APSInt &Value,
162                   QualType Type)
163  : Kind(Integral) {
164    new (Integer.Value) llvm::APSInt(Value);
165    Integer.Type = Type.getAsOpaquePtr();
166    StartLoc = Loc;
167  }
168
169  /// \brief Construct a template argument that is an expression.
170  ///
171  /// This form of template argument only occurs in template argument
172  /// lists used for dependent types and for expression; it will not
173  /// occur in a non-dependent, canonical template argument list.
174  TemplateArgument(Expr *E);
175
176  /// \brief Copy constructor for a template argument.
177  TemplateArgument(const TemplateArgument &Other) : Kind(Other.Kind) {
178    if (Kind == Integral) {
179      new (Integer.Value) llvm::APSInt(*Other.getAsIntegral());
180      Integer.Type = Other.Integer.Type;
181    } else if (Kind == Pack) {
182      Args.NumArgs = Other.Args.NumArgs;
183      Args.Args = new TemplateArgument[Args.NumArgs];
184      for (unsigned I = 0; I != Args.NumArgs; ++I)
185        Args.Args[I] = Other.Args.Args[I];
186    }
187    else
188      TypeOrValue = Other.TypeOrValue;
189    StartLoc = Other.StartLoc;
190  }
191
192  TemplateArgument& operator=(const TemplateArgument& Other) {
193    // FIXME: Does not provide the strong guarantee for exception
194    // safety.
195    using llvm::APSInt;
196
197    // FIXME: Handle Packs
198    assert(Kind != Pack && "FIXME: Handle packs");
199    assert(Other.Kind != Pack && "FIXME: Handle packs");
200
201    if (Kind == Other.Kind && Kind == Integral) {
202      // Copy integral values.
203      *this->getAsIntegral() = *Other.getAsIntegral();
204      Integer.Type = Other.Integer.Type;
205    } else {
206      // Destroy the current integral value, if that's what we're holding.
207      if (Kind == Integral)
208        getAsIntegral()->~APSInt();
209
210      Kind = Other.Kind;
211
212      if (Other.Kind == Integral) {
213        new (Integer.Value) llvm::APSInt(*Other.getAsIntegral());
214        Integer.Type = Other.Integer.Type;
215      } else
216        TypeOrValue = Other.TypeOrValue;
217    }
218    StartLoc = Other.StartLoc;
219
220    return *this;
221  }
222
223  ~TemplateArgument() {
224    using llvm::APSInt;
225
226    if (Kind == Integral)
227      getAsIntegral()->~APSInt();
228    else if (Kind == Pack && Args.CopyArgs)
229      delete[] Args.Args;
230  }
231
232  /// \brief Return the kind of stored template argument.
233  ArgKind getKind() const { return Kind; }
234
235  /// \brief Determine whether this template argument has no value.
236  bool isNull() const { return Kind == Null; }
237
238  /// \brief Retrieve the template argument as a type.
239  QualType getAsType() const {
240    if (Kind != Type)
241      return QualType();
242
243    return QualType::getFromOpaquePtr(
244                                      reinterpret_cast<void*>(TypeOrValue));
245  }
246
247  /// \brief Retrieve the template argument as a declaration.
248  Decl *getAsDecl() const {
249    if (Kind != Declaration)
250      return 0;
251    return reinterpret_cast<Decl *>(TypeOrValue);
252  }
253
254  /// \brief Retrieve the template argument as an integral value.
255  llvm::APSInt *getAsIntegral() {
256    if (Kind != Integral)
257      return 0;
258    return reinterpret_cast<llvm::APSInt*>(&Integer.Value[0]);
259  }
260
261  const llvm::APSInt *getAsIntegral() const {
262    return const_cast<TemplateArgument*>(this)->getAsIntegral();
263  }
264
265  /// \brief Retrieve the type of the integral value.
266  QualType getIntegralType() const {
267    if (Kind != Integral)
268      return QualType();
269
270    return QualType::getFromOpaquePtr(Integer.Type);
271  }
272
273  void setIntegralType(QualType T) {
274    assert(Kind == Integral &&
275           "Cannot set the integral type of a non-integral template argument");
276    Integer.Type = T.getAsOpaquePtr();
277  };
278
279  /// \brief Retrieve the template argument as an expression.
280  Expr *getAsExpr() const {
281    if (Kind != Expression)
282      return 0;
283
284    return reinterpret_cast<Expr *>(TypeOrValue);
285  }
286
287  /// \brief Iterator that traverses the elements of a template argument pack.
288  typedef const TemplateArgument * pack_iterator;
289
290  /// \brief Iterator referencing the first argument of a template argument
291  /// pack.
292  pack_iterator pack_begin() const {
293    assert(Kind == Pack);
294    return Args.Args;
295  }
296
297  /// \brief Iterator referencing one past the last argument of a template
298  /// argument pack.
299  pack_iterator pack_end() const {
300    assert(Kind == Pack);
301    return Args.Args + Args.NumArgs;
302  }
303
304  /// \brief The number of template arguments in the given template argument
305  /// pack.
306  unsigned pack_size() const {
307    assert(Kind == Pack);
308    return Args.NumArgs;
309  }
310
311  /// \brief Retrieve the location where the template argument starts.
312  SourceLocation getLocation() const { return StartLoc; }
313
314  /// \brief Construct a template argument pack.
315  void setArgumentPack(TemplateArgument *Args, unsigned NumArgs, bool CopyArgs);
316
317  /// \brief Used to insert TemplateArguments into FoldingSets.
318  void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context) const {
319    ID.AddInteger(Kind);
320    switch (Kind) {
321      case Null:
322        break;
323
324      case Type:
325        getAsType().Profile(ID);
326        break;
327
328      case Declaration:
329        ID.AddPointer(getAsDecl()? getAsDecl()->getCanonicalDecl() : 0);
330        break;
331
332      case Integral:
333        getAsIntegral()->Profile(ID);
334        getIntegralType().Profile(ID);
335        break;
336
337      case Expression:
338        getAsExpr()->Profile(ID, Context, true);
339        break;
340
341      case Pack:
342        ID.AddInteger(Args.NumArgs);
343        for (unsigned I = 0; I != Args.NumArgs; ++I)
344          Args.Args[I].Profile(ID, Context);
345    }
346  }
347};
348
349/// \brief A helper class for making template argument lists.
350class TemplateArgumentListBuilder {
351  TemplateArgument *StructuredArgs;
352  unsigned MaxStructuredArgs;
353  unsigned NumStructuredArgs;
354
355  TemplateArgument *FlatArgs;
356  unsigned MaxFlatArgs;
357  unsigned NumFlatArgs;
358
359  bool AddingToPack;
360  unsigned PackBeginIndex;
361
362public:
363  TemplateArgumentListBuilder(const TemplateParameterList *Parameters,
364                              unsigned NumTemplateArgs)
365  : StructuredArgs(0), MaxStructuredArgs(Parameters->size()),
366  NumStructuredArgs(0), FlatArgs(0),
367  MaxFlatArgs(std::max(MaxStructuredArgs, NumTemplateArgs)), NumFlatArgs(0),
368  AddingToPack(false), PackBeginIndex(0) { }
369
370  void Append(const TemplateArgument& Arg);
371  void BeginPack();
372  void EndPack();
373
374  void ReleaseArgs();
375
376  unsigned flatSize() const {
377    return NumFlatArgs;
378  }
379  const TemplateArgument *getFlatArguments() const {
380    return FlatArgs;
381  }
382
383  unsigned structuredSize() const {
384    // If we don't have any structured args, just reuse the flat size.
385    if (!StructuredArgs)
386      return flatSize();
387
388    return NumStructuredArgs;
389  }
390  const TemplateArgument *getStructuredArguments() const {
391    // If we don't have any structured args, just reuse the flat args.
392    if (!StructuredArgs)
393      return getFlatArguments();
394
395    return StructuredArgs;
396  }
397};
398
399/// \brief A template argument list.
400///
401/// FIXME: In the future, this class will be extended to support
402/// variadic templates and member templates, which will make some of
403/// the function names below make more sense.
404class TemplateArgumentList {
405  /// \brief The template argument list.
406  ///
407  /// The integer value will be non-zero to indicate that this
408  /// template argument list does not own the pointer.
409  llvm::PointerIntPair<const TemplateArgument *, 1> FlatArguments;
410
411  /// \brief The number of template arguments in this template
412  /// argument list.
413  unsigned NumFlatArguments;
414
415  llvm::PointerIntPair<const TemplateArgument *, 1> StructuredArguments;
416  unsigned NumStructuredArguments;
417
418public:
419  TemplateArgumentList(ASTContext &Context,
420                       TemplateArgumentListBuilder &Builder,
421                       bool TakeArgs);
422
423  ~TemplateArgumentList();
424
425  /// \brief Retrieve the template argument at a given index.
426  const TemplateArgument &get(unsigned Idx) const {
427    assert(Idx < NumFlatArguments && "Invalid template argument index");
428    return getFlatArgumentList()[Idx];
429  }
430
431  /// \brief Retrieve the template argument at a given index.
432  const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
433
434  /// \brief Retrieve the number of template arguments in this
435  /// template argument list.
436  unsigned size() const { return NumFlatArguments; }
437
438  /// \brief Retrieve the number of template arguments in the
439  /// flattened template argument list.
440  unsigned flat_size() const { return NumFlatArguments; }
441
442  /// \brief Retrieve the flattened template argument list.
443  const TemplateArgument *getFlatArgumentList() const {
444    return FlatArguments.getPointer();
445  }
446};
447
448//===----------------------------------------------------------------------===//
449// Kinds of Templates
450//===----------------------------------------------------------------------===//
451
452/// TemplateDecl - The base class of all kinds of template declarations (e.g.,
453/// class, function, etc.). The TemplateDecl class stores the list of template
454/// parameters and a reference to the templated scoped declaration: the
455/// underlying AST node.
456class TemplateDecl : public NamedDecl {
457protected:
458  // This is probably never used.
459  TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
460               DeclarationName Name)
461    : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(0)
462  { }
463
464  // Construct a template decl with the given name and parameters.
465  // Used when there is not templated element (tt-params, alias?).
466  TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
467               DeclarationName Name, TemplateParameterList *Params)
468    : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(Params)
469  { }
470
471  // Construct a template decl with name, parameters, and templated element.
472  TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
473               DeclarationName Name, TemplateParameterList *Params,
474               NamedDecl *Decl)
475    : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
476      TemplateParams(Params) { }
477public:
478  ~TemplateDecl();
479
480  /// Get the list of template parameters
481  TemplateParameterList *getTemplateParameters() const {
482    return TemplateParams;
483  }
484
485  /// Get the underlying, templated declaration.
486  NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
487
488  // Implement isa/cast/dyncast/etc.
489  static bool classof(const Decl *D) {
490      return D->getKind() >= TemplateFirst && D->getKind() <= TemplateLast;
491  }
492  static bool classof(const TemplateDecl *D) { return true; }
493  static bool classof(const FunctionTemplateDecl *D) { return true; }
494  static bool classof(const ClassTemplateDecl *D) { return true; }
495  static bool classof(const TemplateTemplateParmDecl *D) { return true; }
496
497protected:
498  NamedDecl *TemplatedDecl;
499  TemplateParameterList* TemplateParams;
500};
501
502/// \brief Provides information about a function template specialization,
503/// which is a FunctionDecl that has been explicitly specialization or
504/// instantiated from a function template.
505class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
506public:
507  /// \brief The function template specialization that this structure
508  /// describes.
509  FunctionDecl *Function;
510
511  /// \brief The function template from which this function template
512  /// specialization was generated.
513  ///
514  /// The bit will be 0 for an implicit instantiation, 1 for an explicit
515  /// specialization.
516  llvm::PointerIntPair<FunctionTemplateDecl *, 1> Template;
517
518  /// \brief The template arguments used to produce the function template
519  /// specialization from the function template.
520  const TemplateArgumentList *TemplateArguments;
521
522  /// \brief Retrieve the template from which this function was specialized.
523  FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
524
525  /// \brief Determine whether this is an explicit specialization.
526  bool isExplicitSpecialization() const { return Template.getInt(); }
527
528  /// \brief Set whether this is an explicit specialization or an implicit
529  /// instantiation.
530  void setExplicitSpecialization(bool ES) {
531    Template.setInt(ES);
532  }
533
534  void Profile(llvm::FoldingSetNodeID &ID) {
535    Profile(ID, TemplateArguments->getFlatArgumentList(),
536            TemplateArguments->flat_size(),
537            Function->getASTContext());
538  }
539
540  static void
541  Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs,
542          unsigned NumTemplateArgs, ASTContext &Context) {
543    ID.AddInteger(NumTemplateArgs);
544    for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg)
545      TemplateArgs[Arg].Profile(ID, Context);
546  }
547};
548
549/// Declaration of a template function.
550class FunctionTemplateDecl : public TemplateDecl {
551protected:
552  /// \brief Data that is common to all of the declarations of a given
553  /// function template.
554  struct Common {
555    /// \brief The function template specializations for this function
556    /// template, including explicit specializations and instantiations.
557    llvm::FoldingSet<FunctionTemplateSpecializationInfo> Specializations;
558  };
559
560  /// \brief A pointer to the previous declaration (if this is a redeclaration)
561  /// or to the data that is common to all declarations of this function
562  /// template.
563  llvm::PointerUnion<Common*, FunctionTemplateDecl*> CommonOrPrev;
564
565  /// \brief Retrieves the "common" pointer shared by all
566  /// (re-)declarations of the same function template. Calling this routine
567  /// may implicitly allocate memory for the common pointer.
568  Common *getCommonPtr();
569
570  FunctionTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
571                       TemplateParameterList *Params, NamedDecl *Decl)
572    : TemplateDecl(FunctionTemplate, DC, L, Name, Params, Decl),
573      CommonOrPrev((Common*)0) { }
574
575public:
576  void Destroy(ASTContext &C);
577
578  /// Get the underlying function declaration of the template.
579  FunctionDecl *getTemplatedDecl() const {
580    return static_cast<FunctionDecl*>(TemplatedDecl);
581  }
582
583  /// \brief Retrieve the set of function template specializations of this
584  /// function template.
585  llvm::FoldingSet<FunctionTemplateSpecializationInfo> &getSpecializations() {
586    return getCommonPtr()->Specializations;
587  }
588
589  /// \brief Retrieve the previous declaration of this function template, or
590  /// NULL if no such declaration exists.
591  const FunctionTemplateDecl *getPreviousDeclaration() const {
592    return CommonOrPrev.dyn_cast<FunctionTemplateDecl*>();
593  }
594
595  /// \brief Retrieve the previous declaration of this function template, or
596  /// NULL if no such declaration exists.
597  FunctionTemplateDecl *getPreviousDeclaration() {
598    return CommonOrPrev.dyn_cast<FunctionTemplateDecl*>();
599  }
600
601  /// \brief Set the previous declaration of this function template.
602  void setPreviousDeclaration(FunctionTemplateDecl *Prev) {
603    if (Prev)
604      CommonOrPrev = Prev;
605  }
606
607  virtual FunctionTemplateDecl *getCanonicalDecl();
608
609  /// Create a template function node.
610  static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
611                                      SourceLocation L,
612                                      DeclarationName Name,
613                                      TemplateParameterList *Params,
614                                      NamedDecl *Decl);
615
616  // Implement isa/cast/dyncast support
617  static bool classof(const Decl *D)
618  { return D->getKind() == FunctionTemplate; }
619  static bool classof(const FunctionTemplateDecl *D)
620  { return true; }
621};
622
623//===----------------------------------------------------------------------===//
624// Kinds of Template Parameters
625//===----------------------------------------------------------------------===//
626
627/// The TemplateParmPosition class defines the position of a template parameter
628/// within a template parameter list. Because template parameter can be listed
629/// sequentially for out-of-line template members, each template parameter is
630/// given a Depth - the nesting of template parameter scopes - and a Position -
631/// the occurrence within the parameter list.
632/// This class is inheritedly privately by different kinds of template
633/// parameters and is not part of the Decl hierarchy. Just a facility.
634class TemplateParmPosition
635{
636protected:
637  // FIXME: This should probably never be called, but it's here as
638  TemplateParmPosition()
639    : Depth(0), Position(0)
640  { /* assert(0 && "Cannot create positionless template parameter"); */ }
641
642  TemplateParmPosition(unsigned D, unsigned P)
643    : Depth(D), Position(P)
644  { }
645
646  // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
647  // position? Maybe?
648  unsigned Depth;
649  unsigned Position;
650
651public:
652  /// Get the nesting depth of the template parameter.
653  unsigned getDepth() const { return Depth; }
654
655  /// Get the position of the template parameter within its parameter list.
656  unsigned getPosition() const { return Position; }
657
658  /// Get the index of the template parameter within its parameter list.
659  unsigned getIndex() const { return Position; }
660};
661
662/// TemplateTypeParmDecl - Declaration of a template type parameter,
663/// e.g., "T" in
664/// @code
665/// template<typename T> class vector;
666/// @endcode
667class TemplateTypeParmDecl : public TypeDecl {
668  /// \brief Whether this template type parameter was declaration with
669  /// the 'typename' keyword. If false, it was declared with the
670  /// 'class' keyword.
671  bool Typename : 1;
672
673  /// \brief Whether this template type parameter inherited its
674  /// default argument.
675  bool InheritedDefault : 1;
676
677  /// \brief Whether this is a parameter pack.
678  bool ParameterPack : 1;
679
680  /// \brief The location of the default argument, if any.
681  SourceLocation DefaultArgumentLoc;
682
683  /// \brief The default template argument, if any.
684  QualType DefaultArgument;
685
686  TemplateTypeParmDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
687                       bool Typename, QualType Type, bool ParameterPack)
688    : TypeDecl(TemplateTypeParm, DC, L, Id), Typename(Typename),
689      InheritedDefault(false), ParameterPack(ParameterPack), DefaultArgument() {
690    TypeForDecl = Type.getTypePtr();
691  }
692
693public:
694  static TemplateTypeParmDecl *Create(ASTContext &C, DeclContext *DC,
695                                      SourceLocation L, unsigned D, unsigned P,
696                                      IdentifierInfo *Id, bool Typename,
697                                      bool ParameterPack);
698
699  /// \brief Whether this template type parameter was declared with
700  /// the 'typename' keyword. If not, it was declared with the 'class'
701  /// keyword.
702  bool wasDeclaredWithTypename() const { return Typename; }
703
704  /// \brief Determine whether this template parameter has a default
705  /// argument.
706  bool hasDefaultArgument() const { return !DefaultArgument.isNull(); }
707
708  /// \brief Retrieve the default argument, if any.
709  QualType getDefaultArgument() const { return DefaultArgument; }
710
711  /// \brief Retrieve the location of the default argument, if any.
712  SourceLocation getDefaultArgumentLoc() const { return DefaultArgumentLoc; }
713
714  /// \brief Determines whether the default argument was inherited
715  /// from a previous declaration of this template.
716  bool defaultArgumentWasInherited() const { return InheritedDefault; }
717
718  /// \brief Set the default argument for this template parameter, and
719  /// whether that default argument was inherited from another
720  /// declaration.
721  void setDefaultArgument(QualType DefArg, SourceLocation DefArgLoc,
722                          bool Inherited) {
723    DefaultArgument = DefArg;
724    DefaultArgumentLoc = DefArgLoc;
725    InheritedDefault = Inherited;
726  }
727
728  /// \brief Returns whether this is a parameter pack.
729  bool isParameterPack() const { return ParameterPack; }
730
731  // Implement isa/cast/dyncast/etc.
732  static bool classof(const Decl *D) {
733    return D->getKind() == TemplateTypeParm;
734  }
735  static bool classof(const TemplateTypeParmDecl *D) { return true; }
736};
737
738/// NonTypeTemplateParmDecl - Declares a non-type template parameter,
739/// e.g., "Size" in
740/// @code
741/// template<int Size> class array { };
742/// @endcode
743class NonTypeTemplateParmDecl
744  : public VarDecl, protected TemplateParmPosition {
745  /// \brief The default template argument, if any.
746  Expr *DefaultArgument;
747
748  NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation L, unsigned D,
749                          unsigned P, IdentifierInfo *Id, QualType T,
750                          SourceLocation TSSL = SourceLocation())
751    : VarDecl(NonTypeTemplateParm, DC, L, Id, T, VarDecl::None, TSSL),
752      TemplateParmPosition(D, P), DefaultArgument(0)
753  { }
754
755public:
756  static NonTypeTemplateParmDecl *
757  Create(ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D,
758         unsigned P, IdentifierInfo *Id, QualType T,
759         SourceLocation TypeSpecStartLoc = SourceLocation());
760
761  using TemplateParmPosition::getDepth;
762  using TemplateParmPosition::getPosition;
763  using TemplateParmPosition::getIndex;
764
765  /// \brief Determine whether this template parameter has a default
766  /// argument.
767  bool hasDefaultArgument() const { return DefaultArgument; }
768
769  /// \brief Retrieve the default argument, if any.
770  Expr *getDefaultArgument() const { return DefaultArgument; }
771
772  /// \brief Retrieve the location of the default argument, if any.
773  SourceLocation getDefaultArgumentLoc() const;
774
775  /// \brief Set the default argument for this template parameter.
776  void setDefaultArgument(Expr *DefArg) {
777    DefaultArgument = DefArg;
778  }
779
780  // Implement isa/cast/dyncast/etc.
781  static bool classof(const Decl *D) {
782    return D->getKind() == NonTypeTemplateParm;
783  }
784  static bool classof(const NonTypeTemplateParmDecl *D) { return true; }
785};
786
787/// TemplateTemplateParmDecl - Declares a template template parameter,
788/// e.g., "T" in
789/// @code
790/// template <template <typename> class T> class container { };
791/// @endcode
792/// A template template parameter is a TemplateDecl because it defines the
793/// name of a template and the template parameters allowable for substitution.
794class TemplateTemplateParmDecl
795  : public TemplateDecl, protected TemplateParmPosition {
796
797  /// \brief The default template argument, if any.
798  Expr *DefaultArgument;
799
800  TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
801                           unsigned D, unsigned P,
802                           IdentifierInfo *Id, TemplateParameterList *Params)
803    : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
804      TemplateParmPosition(D, P), DefaultArgument(0)
805    { }
806
807public:
808  static TemplateTemplateParmDecl *Create(ASTContext &C, DeclContext *DC,
809                                          SourceLocation L, unsigned D,
810                                          unsigned P, IdentifierInfo *Id,
811                                          TemplateParameterList *Params);
812
813  using TemplateParmPosition::getDepth;
814  using TemplateParmPosition::getPosition;
815  using TemplateParmPosition::getIndex;
816
817  /// \brief Determine whether this template parameter has a default
818  /// argument.
819  bool hasDefaultArgument() const { return DefaultArgument; }
820
821  /// \brief Retrieve the default argument, if any.
822  Expr *getDefaultArgument() const { return DefaultArgument; }
823
824  /// \brief Retrieve the location of the default argument, if any.
825  SourceLocation getDefaultArgumentLoc() const;
826
827  /// \brief Set the default argument for this template parameter.
828  void setDefaultArgument(Expr *DefArg) {
829    DefaultArgument = DefArg;
830  }
831
832  // Implement isa/cast/dyncast/etc.
833  static bool classof(const Decl *D) {
834    return D->getKind() == TemplateTemplateParm;
835  }
836  static bool classof(const TemplateTemplateParmDecl *D) { return true; }
837};
838
839// \brief Describes the kind of template specialization that a
840// particular template specialization declaration represents.
841enum TemplateSpecializationKind {
842  /// This template specialization was formed from a template-id but
843  /// has not yet been declared, defined, or instantiated.
844  TSK_Undeclared = 0,
845  /// This template specialization was declared or defined by an
846  /// explicit specialization (C++ [temp.expl.spec]) or partial
847  /// specialization (C++ [temp.class.spec]).
848  TSK_ExplicitSpecialization,
849  /// This template specialization was implicitly instantiated from a
850  /// template. (C++ [temp.inst]).
851  TSK_ImplicitInstantiation,
852  /// This template specialization was instantiated from a template
853  /// due to an explicit instantiation request (C++ [temp.explicit]).
854  TSK_ExplicitInstantiation
855};
856
857/// \brief Represents a class template specialization, which refers to
858/// a class template with a given set of template arguments.
859///
860/// Class template specializations represent both explicit
861/// specialization of class templates, as in the example below, and
862/// implicit instantiations of class templates.
863///
864/// \code
865/// template<typename T> class array;
866///
867/// template<>
868/// class array<bool> { }; // class template specialization array<bool>
869/// \endcode
870class ClassTemplateSpecializationDecl
871  : public CXXRecordDecl, public llvm::FoldingSetNode {
872
873  /// \brief Structure that stores information about a class template
874  /// specialization that was instantiated from a class template partial
875  /// specialization.
876  struct SpecializedPartialSpecialization {
877    /// \brief The class template partial specialization from which this
878    /// class template specialization was instantiated.
879    ClassTemplatePartialSpecializationDecl *PartialSpecialization;
880
881    /// \brief The template argument list deduced for the class template
882    /// partial specialization itself.
883    TemplateArgumentList *TemplateArgs;
884  };
885
886  /// \brief The template that this specialization specializes
887  llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
888    SpecializedTemplate;
889
890  /// \brief The template arguments used to describe this specialization.
891  TemplateArgumentList TemplateArgs;
892
893  /// \brief The kind of specialization this declaration refers to.
894  /// Really a value of type TemplateSpecializationKind.
895  unsigned SpecializationKind : 2;
896
897protected:
898  ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK,
899                                  DeclContext *DC, SourceLocation L,
900                                  ClassTemplateDecl *SpecializedTemplate,
901                                  TemplateArgumentListBuilder &Builder,
902                                  ClassTemplateSpecializationDecl *PrevDecl);
903
904public:
905  static ClassTemplateSpecializationDecl *
906  Create(ASTContext &Context, DeclContext *DC, SourceLocation L,
907         ClassTemplateDecl *SpecializedTemplate,
908         TemplateArgumentListBuilder &Builder,
909         ClassTemplateSpecializationDecl *PrevDecl);
910
911  virtual void Destroy(ASTContext& C);
912
913  /// \brief Retrieve the template that this specialization specializes.
914  ClassTemplateDecl *getSpecializedTemplate() const;
915
916  /// \brief Retrieve the template arguments of the class template
917  /// specialization.
918  const TemplateArgumentList &getTemplateArgs() const {
919    return TemplateArgs;
920  }
921
922  /// \brief Determine the kind of specialization that this
923  /// declaration represents.
924  TemplateSpecializationKind getSpecializationKind() const {
925    return static_cast<TemplateSpecializationKind>(SpecializationKind);
926  }
927
928  void setSpecializationKind(TemplateSpecializationKind TSK) {
929    SpecializationKind = TSK;
930  }
931
932  /// \brief If this class template specialization is an instantiation of
933  /// a template (rather than an explicit specialization), return the
934  /// class template or class template partial specialization from which it
935  /// was instantiated.
936  llvm::PointerUnion<ClassTemplateDecl *,
937                     ClassTemplatePartialSpecializationDecl *>
938  getInstantiatedFrom() const {
939    if (getSpecializationKind() != TSK_ImplicitInstantiation &&
940        getSpecializationKind() != TSK_ExplicitInstantiation)
941      return (ClassTemplateDecl*)0;
942
943    if (SpecializedPartialSpecialization *PartialSpec
944          = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
945      return PartialSpec->PartialSpecialization;
946
947    return const_cast<ClassTemplateDecl*>(
948                             SpecializedTemplate.get<ClassTemplateDecl*>());
949  }
950
951  /// \brief Retrieve the set of template arguments that should be used
952  /// to instantiate members of the class template or class template partial
953  /// specialization from which this class template specialization was
954  /// instantiated.
955  ///
956  /// \returns For a class template specialization instantiated from the primary
957  /// template, this function will return the same template arguments as
958  /// getTemplateArgs(). For a class template specialization instantiated from
959  /// a class template partial specialization, this function will return the
960  /// deduced template arguments for the class template partial specialization
961  /// itself.
962  const TemplateArgumentList &getTemplateInstantiationArgs() const {
963    if (SpecializedPartialSpecialization *PartialSpec
964        = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
965      return *PartialSpec->TemplateArgs;
966
967    return getTemplateArgs();
968  }
969
970  /// \brief Note that this class template specialization is actually an
971  /// instantiation of the given class template partial specialization whose
972  /// template arguments have been deduced.
973  void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
974                          TemplateArgumentList *TemplateArgs) {
975    SpecializedPartialSpecialization *PS
976      = new (getASTContext()) SpecializedPartialSpecialization();
977    PS->PartialSpecialization = PartialSpec;
978    PS->TemplateArgs = TemplateArgs;
979    SpecializedTemplate = PS;
980  }
981
982  /// \brief Sets the type of this specialization as it was written by
983  /// the user. This will be a class template specialization type.
984  void setTypeAsWritten(QualType T) {
985    TypeForDecl = T.getTypePtr();
986  }
987
988  void Profile(llvm::FoldingSetNodeID &ID) const {
989    Profile(ID, TemplateArgs.getFlatArgumentList(), TemplateArgs.flat_size(),
990            getASTContext());
991  }
992
993  static void
994  Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs,
995          unsigned NumTemplateArgs, ASTContext &Context) {
996    ID.AddInteger(NumTemplateArgs);
997    for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg)
998      TemplateArgs[Arg].Profile(ID, Context);
999  }
1000
1001  static bool classof(const Decl *D) {
1002    return D->getKind() == ClassTemplateSpecialization ||
1003           D->getKind() == ClassTemplatePartialSpecialization;
1004  }
1005
1006  static bool classof(const ClassTemplateSpecializationDecl *) {
1007    return true;
1008  }
1009
1010  static bool classof(const ClassTemplatePartialSpecializationDecl *) {
1011    return true;
1012  }
1013};
1014
1015class ClassTemplatePartialSpecializationDecl
1016  : public ClassTemplateSpecializationDecl
1017{
1018  /// \brief The list of template parameters
1019  TemplateParameterList* TemplateParams;
1020
1021  ClassTemplatePartialSpecializationDecl(ASTContext &Context,
1022                                         DeclContext *DC, SourceLocation L,
1023                                         TemplateParameterList *Params,
1024                                         ClassTemplateDecl *SpecializedTemplate,
1025                                         TemplateArgumentListBuilder &Builder,
1026                               ClassTemplatePartialSpecializationDecl *PrevDecl)
1027    : ClassTemplateSpecializationDecl(Context,
1028                                      ClassTemplatePartialSpecialization,
1029                                      DC, L, SpecializedTemplate, Builder,
1030                                      PrevDecl),
1031      TemplateParams(Params) { }
1032
1033public:
1034  static ClassTemplatePartialSpecializationDecl *
1035  Create(ASTContext &Context, DeclContext *DC, SourceLocation L,
1036         TemplateParameterList *Params,
1037         ClassTemplateDecl *SpecializedTemplate,
1038         TemplateArgumentListBuilder &Builder,
1039         ClassTemplatePartialSpecializationDecl *PrevDecl);
1040
1041  /// Get the list of template parameters
1042  TemplateParameterList *getTemplateParameters() const {
1043    return TemplateParams;
1044  }
1045
1046  // FIXME: Add Profile support!
1047
1048  static bool classof(const Decl *D) {
1049    return D->getKind() == ClassTemplatePartialSpecialization;
1050  }
1051
1052  static bool classof(const ClassTemplatePartialSpecializationDecl *) {
1053    return true;
1054  }
1055};
1056
1057/// Declaration of a class template.
1058class ClassTemplateDecl : public TemplateDecl {
1059protected:
1060  /// \brief Data that is common to all of the declarations of a given
1061  /// class template.
1062  struct Common {
1063    /// \brief The class template specializations for this class
1064    /// template, including explicit specializations and instantiations.
1065    llvm::FoldingSet<ClassTemplateSpecializationDecl> Specializations;
1066
1067    /// \brief The class template partial specializations for this class
1068    /// template.
1069    llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>
1070      PartialSpecializations;
1071
1072    /// \brief The injected-class-name type for this class template.
1073    QualType InjectedClassNameType;
1074  };
1075
1076  /// \brief Previous declaration of this class template.
1077  ClassTemplateDecl *PreviousDeclaration;
1078
1079  /// \brief Pointer to the data that is common to all of the
1080  /// declarations of this class template.
1081  ///
1082  /// The first declaration of a class template (e.g., the declaration
1083  /// with no "previous declaration") owns this pointer.
1084  Common *CommonPtr;
1085
1086  ClassTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
1087                    TemplateParameterList *Params, NamedDecl *Decl,
1088                    ClassTemplateDecl *PrevDecl, Common *CommonPtr)
1089    : TemplateDecl(ClassTemplate, DC, L, Name, Params, Decl),
1090      PreviousDeclaration(PrevDecl), CommonPtr(CommonPtr) { }
1091
1092  ~ClassTemplateDecl();
1093
1094public:
1095  /// Get the underlying class declarations of the template.
1096  CXXRecordDecl *getTemplatedDecl() const {
1097    return static_cast<CXXRecordDecl *>(TemplatedDecl);
1098  }
1099
1100  /// \brief Retrieve the previous declaration of this template.
1101  ClassTemplateDecl *getPreviousDeclaration() const {
1102    return PreviousDeclaration;
1103  }
1104
1105  virtual ClassTemplateDecl *getCanonicalDecl();
1106
1107  /// Create a class template node.
1108  static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1109                                   SourceLocation L,
1110                                   DeclarationName Name,
1111                                   TemplateParameterList *Params,
1112                                   NamedDecl *Decl,
1113                                   ClassTemplateDecl *PrevDecl);
1114
1115  /// \brief Retrieve the set of specializations of this class template.
1116  llvm::FoldingSet<ClassTemplateSpecializationDecl> &getSpecializations() {
1117    return CommonPtr->Specializations;
1118  }
1119
1120  /// \brief Retrieve the set of partial specializations of this class
1121  /// template.
1122  llvm::FoldingSet<ClassTemplatePartialSpecializationDecl> &
1123  getPartialSpecializations() {
1124    return CommonPtr->PartialSpecializations;
1125  }
1126
1127  /// \brief Find a class template partial specialization with the given
1128  /// type T.
1129  ///
1130  /// \brief A dependent type that names a specialization of this class
1131  /// template.
1132  ///
1133  /// \returns the class template partial specialization that exactly matches
1134  /// the type \p T, or NULL if no such partial specialization exists.
1135  ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
1136
1137  /// \brief Retrieve the type of the injected-class-name for this
1138  /// class template.
1139  ///
1140  /// The injected-class-name for a class template \c X is \c
1141  /// X<template-args>, where \c template-args is formed from the
1142  /// template arguments that correspond to the template parameters of
1143  /// \c X. For example:
1144  ///
1145  /// \code
1146  /// template<typename T, int N>
1147  /// struct array {
1148  ///   typedef array this_type; // "array" is equivalent to "array<T, N>"
1149  /// };
1150  /// \endcode
1151  QualType getInjectedClassNameType(ASTContext &Context);
1152
1153  // Implement isa/cast/dyncast support
1154  static bool classof(const Decl *D)
1155  { return D->getKind() == ClassTemplate; }
1156  static bool classof(const ClassTemplateDecl *D)
1157  { return true; }
1158
1159  virtual void Destroy(ASTContext& C);
1160};
1161
1162/// Implementation of inline functions that require the template declarations
1163inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
1164  : Function(FTD) { }
1165
1166} /* end of namespace clang */
1167
1168#endif
1169