1//===- TemplateName.h - C++ Template Name Representation --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9//  This file defines the TemplateName interface and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_TEMPLATENAME_H
14#define LLVM_CLANG_AST_TEMPLATENAME_H
15
16#include "clang/AST/NestedNameSpecifier.h"
17#include "clang/Basic/LLVM.h"
18#include "llvm/ADT/FoldingSet.h"
19#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/PointerUnion.h"
21#include "llvm/Support/PointerLikeTypeTraits.h"
22#include <cassert>
23
24namespace clang {
25
26class ASTContext;
27class DependentTemplateName;
28class DiagnosticBuilder;
29class IdentifierInfo;
30class NamedDecl;
31class NestedNameSpecifier;
32enum OverloadedOperatorKind : int;
33class OverloadedTemplateStorage;
34class AssumedTemplateStorage;
35class PartialDiagnostic;
36struct PrintingPolicy;
37class QualifiedTemplateName;
38class SubstTemplateTemplateParmPackStorage;
39class SubstTemplateTemplateParmStorage;
40class TemplateArgument;
41class TemplateDecl;
42class TemplateTemplateParmDecl;
43
44/// Implementation class used to describe either a set of overloaded
45/// template names or an already-substituted template template parameter pack.
46class UncommonTemplateNameStorage {
47protected:
48  enum Kind {
49    Overloaded,
50    Assumed, // defined in DeclarationName.h
51    SubstTemplateTemplateParm,
52    SubstTemplateTemplateParmPack
53  };
54
55  struct BitsTag {
56    /// A Kind.
57    unsigned Kind : 2;
58
59    /// The number of stored templates or template arguments,
60    /// depending on which subclass we have.
61    unsigned Size : 30;
62  };
63
64  union {
65    struct BitsTag Bits;
66    void *PointerAlignment;
67  };
68
69  UncommonTemplateNameStorage(Kind kind, unsigned size) {
70    Bits.Kind = kind;
71    Bits.Size = size;
72  }
73
74public:
75  unsigned size() const { return Bits.Size; }
76
77  OverloadedTemplateStorage *getAsOverloadedStorage()  {
78    return Bits.Kind == Overloaded
79             ? reinterpret_cast<OverloadedTemplateStorage *>(this)
80             : nullptr;
81  }
82
83  AssumedTemplateStorage *getAsAssumedTemplateName()  {
84    return Bits.Kind == Assumed
85             ? reinterpret_cast<AssumedTemplateStorage *>(this)
86             : nullptr;
87  }
88
89  SubstTemplateTemplateParmStorage *getAsSubstTemplateTemplateParm() {
90    return Bits.Kind == SubstTemplateTemplateParm
91             ? reinterpret_cast<SubstTemplateTemplateParmStorage *>(this)
92             : nullptr;
93  }
94
95  SubstTemplateTemplateParmPackStorage *getAsSubstTemplateTemplateParmPack() {
96    return Bits.Kind == SubstTemplateTemplateParmPack
97             ? reinterpret_cast<SubstTemplateTemplateParmPackStorage *>(this)
98             : nullptr;
99  }
100};
101
102/// A structure for storing the information associated with an
103/// overloaded template name.
104class OverloadedTemplateStorage : public UncommonTemplateNameStorage {
105  friend class ASTContext;
106
107  OverloadedTemplateStorage(unsigned size)
108      : UncommonTemplateNameStorage(Overloaded, size) {}
109
110  NamedDecl **getStorage() {
111    return reinterpret_cast<NamedDecl **>(this + 1);
112  }
113  NamedDecl * const *getStorage() const {
114    return reinterpret_cast<NamedDecl *const *>(this + 1);
115  }
116
117public:
118  using iterator = NamedDecl *const *;
119
120  iterator begin() const { return getStorage(); }
121  iterator end() const { return getStorage() + size(); }
122
123  llvm::ArrayRef<NamedDecl*> decls() const {
124    return llvm::makeArrayRef(begin(), end());
125  }
126};
127
128/// A structure for storing an already-substituted template template
129/// parameter pack.
130///
131/// This kind of template names occurs when the parameter pack has been
132/// provided with a template template argument pack in a context where its
133/// enclosing pack expansion could not be fully expanded.
134class SubstTemplateTemplateParmPackStorage
135  : public UncommonTemplateNameStorage, public llvm::FoldingSetNode
136{
137  TemplateTemplateParmDecl *Parameter;
138  const TemplateArgument *Arguments;
139
140public:
141  SubstTemplateTemplateParmPackStorage(TemplateTemplateParmDecl *Parameter,
142                                       unsigned Size,
143                                       const TemplateArgument *Arguments)
144      : UncommonTemplateNameStorage(SubstTemplateTemplateParmPack, Size),
145        Parameter(Parameter), Arguments(Arguments) {}
146
147  /// Retrieve the template template parameter pack being substituted.
148  TemplateTemplateParmDecl *getParameterPack() const {
149    return Parameter;
150  }
151
152  /// Retrieve the template template argument pack with which this
153  /// parameter was substituted.
154  TemplateArgument getArgumentPack() const;
155
156  void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context);
157
158  static void Profile(llvm::FoldingSetNodeID &ID,
159                      ASTContext &Context,
160                      TemplateTemplateParmDecl *Parameter,
161                      const TemplateArgument &ArgPack);
162};
163
164/// Represents a C++ template name within the type system.
165///
166/// A C++ template name refers to a template within the C++ type
167/// system. In most cases, a template name is simply a reference to a
168/// class template, e.g.
169///
170/// \code
171/// template<typename T> class X { };
172///
173/// X<int> xi;
174/// \endcode
175///
176/// Here, the 'X' in \c X<int> is a template name that refers to the
177/// declaration of the class template X, above. Template names can
178/// also refer to function templates, C++0x template aliases, etc.
179///
180/// Some template names are dependent. For example, consider:
181///
182/// \code
183/// template<typename MetaFun, typename T1, typename T2> struct apply2 {
184///   typedef typename MetaFun::template apply<T1, T2>::type type;
185/// };
186/// \endcode
187///
188/// Here, "apply" is treated as a template name within the typename
189/// specifier in the typedef. "apply" is a nested template, and can
190/// only be understood in the context of
191class TemplateName {
192  using StorageType =
193      llvm::PointerUnion<TemplateDecl *, UncommonTemplateNameStorage *,
194                         QualifiedTemplateName *, DependentTemplateName *>;
195
196  StorageType Storage;
197
198  explicit TemplateName(void *Ptr);
199
200public:
201  // Kind of name that is actually stored.
202  enum NameKind {
203    /// A single template declaration.
204    Template,
205
206    /// A set of overloaded template declarations.
207    OverloadedTemplate,
208
209    /// An unqualified-id that has been assumed to name a function template
210    /// that will be found by ADL.
211    AssumedTemplate,
212
213    /// A qualified template name, where the qualification is kept
214    /// to describe the source code as written.
215    QualifiedTemplate,
216
217    /// A dependent template name that has not been resolved to a
218    /// template (or set of templates).
219    DependentTemplate,
220
221    /// A template template parameter that has been substituted
222    /// for some other template name.
223    SubstTemplateTemplateParm,
224
225    /// A template template parameter pack that has been substituted for
226    /// a template template argument pack, but has not yet been expanded into
227    /// individual arguments.
228    SubstTemplateTemplateParmPack
229  };
230
231  TemplateName() = default;
232  explicit TemplateName(TemplateDecl *Template);
233  explicit TemplateName(OverloadedTemplateStorage *Storage);
234  explicit TemplateName(AssumedTemplateStorage *Storage);
235  explicit TemplateName(SubstTemplateTemplateParmStorage *Storage);
236  explicit TemplateName(SubstTemplateTemplateParmPackStorage *Storage);
237  explicit TemplateName(QualifiedTemplateName *Qual);
238  explicit TemplateName(DependentTemplateName *Dep);
239
240  /// Determine whether this template name is NULL.
241  bool isNull() const;
242
243  // Get the kind of name that is actually stored.
244  NameKind getKind() const;
245
246  /// Retrieve the underlying template declaration that
247  /// this template name refers to, if known.
248  ///
249  /// \returns The template declaration that this template name refers
250  /// to, if any. If the template name does not refer to a specific
251  /// declaration because it is a dependent name, or if it refers to a
252  /// set of function templates, returns NULL.
253  TemplateDecl *getAsTemplateDecl() const;
254
255  /// Retrieve the underlying, overloaded function template
256  /// declarations that this template name refers to, if known.
257  ///
258  /// \returns The set of overloaded function templates that this template
259  /// name refers to, if known. If the template name does not refer to a
260  /// specific set of function templates because it is a dependent name or
261  /// refers to a single template, returns NULL.
262  OverloadedTemplateStorage *getAsOverloadedTemplate() const;
263
264  /// Retrieve information on a name that has been assumed to be a
265  /// template-name in order to permit a call via ADL.
266  AssumedTemplateStorage *getAsAssumedTemplateName() const;
267
268  /// Retrieve the substituted template template parameter, if
269  /// known.
270  ///
271  /// \returns The storage for the substituted template template parameter,
272  /// if known. Otherwise, returns NULL.
273  SubstTemplateTemplateParmStorage *getAsSubstTemplateTemplateParm() const;
274
275  /// Retrieve the substituted template template parameter pack, if
276  /// known.
277  ///
278  /// \returns The storage for the substituted template template parameter pack,
279  /// if known. Otherwise, returns NULL.
280  SubstTemplateTemplateParmPackStorage *
281  getAsSubstTemplateTemplateParmPack() const;
282
283  /// Retrieve the underlying qualified template name
284  /// structure, if any.
285  QualifiedTemplateName *getAsQualifiedTemplateName() const;
286
287  /// Retrieve the underlying dependent template name
288  /// structure, if any.
289  DependentTemplateName *getAsDependentTemplateName() const;
290
291  TemplateName getUnderlying() const;
292
293  /// Get the template name to substitute when this template name is used as a
294  /// template template argument. This refers to the most recent declaration of
295  /// the template, including any default template arguments.
296  TemplateName getNameToSubstitute() const;
297
298  /// Determines whether this is a dependent template name.
299  bool isDependent() const;
300
301  /// Determines whether this is a template name that somehow
302  /// depends on a template parameter.
303  bool isInstantiationDependent() const;
304
305  /// Determines whether this template name contains an
306  /// unexpanded parameter pack (for C++0x variadic templates).
307  bool containsUnexpandedParameterPack() const;
308
309  /// Print the template name.
310  ///
311  /// \param OS the output stream to which the template name will be
312  /// printed.
313  ///
314  /// \param SuppressNNS if true, don't print the
315  /// nested-name-specifier that precedes the template name (if it has
316  /// one).
317  void print(raw_ostream &OS, const PrintingPolicy &Policy,
318             bool SuppressNNS = false) const;
319
320  /// Debugging aid that dumps the template name.
321  void dump(raw_ostream &OS) const;
322
323  /// Debugging aid that dumps the template name to standard
324  /// error.
325  void dump() const;
326
327  void Profile(llvm::FoldingSetNodeID &ID) {
328    ID.AddPointer(Storage.getOpaqueValue());
329  }
330
331  /// Retrieve the template name as a void pointer.
332  void *getAsVoidPointer() const { return Storage.getOpaqueValue(); }
333
334  /// Build a template name from a void pointer.
335  static TemplateName getFromVoidPointer(void *Ptr) {
336    return TemplateName(Ptr);
337  }
338};
339
340/// Insertion operator for diagnostics.  This allows sending TemplateName's
341/// into a diagnostic with <<.
342const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
343                                    TemplateName N);
344const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
345                                    TemplateName N);
346
347/// A structure for storing the information associated with a
348/// substituted template template parameter.
349class SubstTemplateTemplateParmStorage
350  : public UncommonTemplateNameStorage, public llvm::FoldingSetNode {
351  friend class ASTContext;
352
353  TemplateTemplateParmDecl *Parameter;
354  TemplateName Replacement;
355
356  SubstTemplateTemplateParmStorage(TemplateTemplateParmDecl *parameter,
357                                   TemplateName replacement)
358      : UncommonTemplateNameStorage(SubstTemplateTemplateParm, 0),
359        Parameter(parameter), Replacement(replacement) {}
360
361public:
362  TemplateTemplateParmDecl *getParameter() const { return Parameter; }
363  TemplateName getReplacement() const { return Replacement; }
364
365  void Profile(llvm::FoldingSetNodeID &ID);
366
367  static void Profile(llvm::FoldingSetNodeID &ID,
368                      TemplateTemplateParmDecl *parameter,
369                      TemplateName replacement);
370};
371
372inline TemplateName TemplateName::getUnderlying() const {
373  if (SubstTemplateTemplateParmStorage *subst
374        = getAsSubstTemplateTemplateParm())
375    return subst->getReplacement().getUnderlying();
376  return *this;
377}
378
379/// Represents a template name that was expressed as a
380/// qualified name.
381///
382/// This kind of template name refers to a template name that was
383/// preceded by a nested name specifier, e.g., \c std::vector. Here,
384/// the nested name specifier is "std::" and the template name is the
385/// declaration for "vector". The QualifiedTemplateName class is only
386/// used to provide "sugar" for template names that were expressed
387/// with a qualified name, and has no semantic meaning. In this
388/// manner, it is to TemplateName what ElaboratedType is to Type,
389/// providing extra syntactic sugar for downstream clients.
390class QualifiedTemplateName : public llvm::FoldingSetNode {
391  friend class ASTContext;
392
393  /// The nested name specifier that qualifies the template name.
394  ///
395  /// The bit is used to indicate whether the "template" keyword was
396  /// present before the template name itself. Note that the
397  /// "template" keyword is always redundant in this case (otherwise,
398  /// the template name would be a dependent name and we would express
399  /// this name with DependentTemplateName).
400  llvm::PointerIntPair<NestedNameSpecifier *, 1> Qualifier;
401
402  /// The template declaration or set of overloaded function templates
403  /// that this qualified name refers to.
404  TemplateDecl *Template;
405
406  QualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword,
407                        TemplateDecl *Template)
408      : Qualifier(NNS, TemplateKeyword? 1 : 0), Template(Template) {}
409
410public:
411  /// Return the nested name specifier that qualifies this name.
412  NestedNameSpecifier *getQualifier() const { return Qualifier.getPointer(); }
413
414  /// Whether the template name was prefixed by the "template"
415  /// keyword.
416  bool hasTemplateKeyword() const { return Qualifier.getInt(); }
417
418  /// The template declaration that this qualified name refers
419  /// to.
420  TemplateDecl *getDecl() const { return Template; }
421
422  /// The template declaration to which this qualified name
423  /// refers.
424  TemplateDecl *getTemplateDecl() const { return Template; }
425
426  void Profile(llvm::FoldingSetNodeID &ID) {
427    Profile(ID, getQualifier(), hasTemplateKeyword(), getTemplateDecl());
428  }
429
430  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
431                      bool TemplateKeyword, TemplateDecl *Template) {
432    ID.AddPointer(NNS);
433    ID.AddBoolean(TemplateKeyword);
434    ID.AddPointer(Template);
435  }
436};
437
438/// Represents a dependent template name that cannot be
439/// resolved prior to template instantiation.
440///
441/// This kind of template name refers to a dependent template name,
442/// including its nested name specifier (if any). For example,
443/// DependentTemplateName can refer to "MetaFun::template apply",
444/// where "MetaFun::" is the nested name specifier and "apply" is the
445/// template name referenced. The "template" keyword is implied.
446class DependentTemplateName : public llvm::FoldingSetNode {
447  friend class ASTContext;
448
449  /// The nested name specifier that qualifies the template
450  /// name.
451  ///
452  /// The bit stored in this qualifier describes whether the \c Name field
453  /// is interpreted as an IdentifierInfo pointer (when clear) or as an
454  /// overloaded operator kind (when set).
455  llvm::PointerIntPair<NestedNameSpecifier *, 1, bool> Qualifier;
456
457  /// The dependent template name.
458  union {
459    /// The identifier template name.
460    ///
461    /// Only valid when the bit on \c Qualifier is clear.
462    const IdentifierInfo *Identifier;
463
464    /// The overloaded operator name.
465    ///
466    /// Only valid when the bit on \c Qualifier is set.
467    OverloadedOperatorKind Operator;
468  };
469
470  /// The canonical template name to which this dependent
471  /// template name refers.
472  ///
473  /// The canonical template name for a dependent template name is
474  /// another dependent template name whose nested name specifier is
475  /// canonical.
476  TemplateName CanonicalTemplateName;
477
478  DependentTemplateName(NestedNameSpecifier *Qualifier,
479                        const IdentifierInfo *Identifier)
480      : Qualifier(Qualifier, false), Identifier(Identifier),
481        CanonicalTemplateName(this) {}
482
483  DependentTemplateName(NestedNameSpecifier *Qualifier,
484                        const IdentifierInfo *Identifier,
485                        TemplateName Canon)
486      : Qualifier(Qualifier, false), Identifier(Identifier),
487        CanonicalTemplateName(Canon) {}
488
489  DependentTemplateName(NestedNameSpecifier *Qualifier,
490                        OverloadedOperatorKind Operator)
491      : Qualifier(Qualifier, true), Operator(Operator),
492        CanonicalTemplateName(this) {}
493
494  DependentTemplateName(NestedNameSpecifier *Qualifier,
495                        OverloadedOperatorKind Operator,
496                        TemplateName Canon)
497       : Qualifier(Qualifier, true), Operator(Operator),
498         CanonicalTemplateName(Canon) {}
499
500public:
501  /// Return the nested name specifier that qualifies this name.
502  NestedNameSpecifier *getQualifier() const { return Qualifier.getPointer(); }
503
504  /// Determine whether this template name refers to an identifier.
505  bool isIdentifier() const { return !Qualifier.getInt(); }
506
507  /// Returns the identifier to which this template name refers.
508  const IdentifierInfo *getIdentifier() const {
509    assert(isIdentifier() && "Template name isn't an identifier?");
510    return Identifier;
511  }
512
513  /// Determine whether this template name refers to an overloaded
514  /// operator.
515  bool isOverloadedOperator() const { return Qualifier.getInt(); }
516
517  /// Return the overloaded operator to which this template name refers.
518  OverloadedOperatorKind getOperator() const {
519    assert(isOverloadedOperator() &&
520           "Template name isn't an overloaded operator?");
521    return Operator;
522  }
523
524  void Profile(llvm::FoldingSetNodeID &ID) {
525    if (isIdentifier())
526      Profile(ID, getQualifier(), getIdentifier());
527    else
528      Profile(ID, getQualifier(), getOperator());
529  }
530
531  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
532                      const IdentifierInfo *Identifier) {
533    ID.AddPointer(NNS);
534    ID.AddBoolean(false);
535    ID.AddPointer(Identifier);
536  }
537
538  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
539                      OverloadedOperatorKind Operator) {
540    ID.AddPointer(NNS);
541    ID.AddBoolean(true);
542    ID.AddInteger(Operator);
543  }
544};
545
546} // namespace clang.
547
548namespace llvm {
549
550/// The clang::TemplateName class is effectively a pointer.
551template<>
552struct PointerLikeTypeTraits<clang::TemplateName> {
553  static inline void *getAsVoidPointer(clang::TemplateName TN) {
554    return TN.getAsVoidPointer();
555  }
556
557  static inline clang::TemplateName getFromVoidPointer(void *Ptr) {
558    return clang::TemplateName::getFromVoidPointer(Ptr);
559  }
560
561  // No bits are available!
562  enum { NumLowBitsAvailable = 0 };
563};
564
565} // namespace llvm.
566
567#endif // LLVM_CLANG_AST_TEMPLATENAME_H
568