DeclBase.h revision 02892a65b18875a04c7ed5eadb3a13be801ab477
1//===-- DeclBase.h - Base Classes for representing declarations -*- 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 Decl and DeclContext interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECLBASE_H
15#define LLVM_CLANG_AST_DECLBASE_H
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/Type.h"
19#include "clang/Basic/Specifiers.h"
20#include "llvm/Support/PrettyStackTrace.h"
21#include "llvm/ADT/PointerUnion.h"
22
23namespace clang {
24class DeclContext;
25class TranslationUnitDecl;
26class NamespaceDecl;
27class UsingDirectiveDecl;
28class NamedDecl;
29class FunctionDecl;
30class CXXRecordDecl;
31class EnumDecl;
32class ObjCMethodDecl;
33class ObjCContainerDecl;
34class ObjCInterfaceDecl;
35class ObjCCategoryDecl;
36class ObjCProtocolDecl;
37class ObjCImplementationDecl;
38class ObjCCategoryImplDecl;
39class ObjCImplDecl;
40class LinkageSpecDecl;
41class BlockDecl;
42class DeclarationName;
43class CompoundStmt;
44class StoredDeclsMap;
45class DependentDiagnostic;
46class ASTMutationListener;
47}
48
49namespace llvm {
50// DeclContext* is only 4-byte aligned on 32-bit systems.
51template<>
52  class PointerLikeTypeTraits<clang::DeclContext*> {
53  typedef clang::DeclContext* PT;
54public:
55  static inline void *getAsVoidPointer(PT P) { return P; }
56  static inline PT getFromVoidPointer(void *P) {
57    return static_cast<PT>(P);
58  }
59  enum { NumLowBitsAvailable = 2 };
60};
61}
62
63namespace clang {
64
65  /// \brief Captures the result of checking the availability of a
66  /// declaration.
67  enum AvailabilityResult {
68    AR_Available = 0,
69    AR_NotYetIntroduced,
70    AR_Deprecated,
71    AR_Unavailable
72  };
73
74/// Decl - This represents one declaration (or definition), e.g. a variable,
75/// typedef, function, struct, etc.
76///
77class Decl {
78public:
79  /// \brief Lists the kind of concrete classes of Decl.
80  enum Kind {
81#define DECL(DERIVED, BASE) DERIVED,
82#define ABSTRACT_DECL(DECL)
83#define DECL_RANGE(BASE, START, END) \
84        first##BASE = START, last##BASE = END,
85#define LAST_DECL_RANGE(BASE, START, END) \
86        first##BASE = START, last##BASE = END
87#include "clang/AST/DeclNodes.inc"
88  };
89
90  /// \brief A placeholder type used to construct an empty shell of a
91  /// decl-derived type that will be filled in later (e.g., by some
92  /// deserialization method).
93  struct EmptyShell { };
94
95  /// IdentifierNamespace - The different namespaces in which
96  /// declarations may appear.  According to C99 6.2.3, there are
97  /// four namespaces, labels, tags, members and ordinary
98  /// identifiers.  C++ describes lookup completely differently:
99  /// certain lookups merely "ignore" certain kinds of declarations,
100  /// usually based on whether the declaration is of a type, etc.
101  ///
102  /// These are meant as bitmasks, so that searches in
103  /// C++ can look into the "tag" namespace during ordinary lookup.
104  ///
105  /// Decl currently provides 15 bits of IDNS bits.
106  enum IdentifierNamespace {
107    /// Labels, declared with 'x:' and referenced with 'goto x'.
108    IDNS_Label               = 0x0001,
109
110    /// Tags, declared with 'struct foo;' and referenced with
111    /// 'struct foo'.  All tags are also types.  This is what
112    /// elaborated-type-specifiers look for in C.
113    IDNS_Tag                 = 0x0002,
114
115    /// Types, declared with 'struct foo', typedefs, etc.
116    /// This is what elaborated-type-specifiers look for in C++,
117    /// but note that it's ill-formed to find a non-tag.
118    IDNS_Type                = 0x0004,
119
120    /// Members, declared with object declarations within tag
121    /// definitions.  In C, these can only be found by "qualified"
122    /// lookup in member expressions.  In C++, they're found by
123    /// normal lookup.
124    IDNS_Member              = 0x0008,
125
126    /// Namespaces, declared with 'namespace foo {}'.
127    /// Lookup for nested-name-specifiers find these.
128    IDNS_Namespace           = 0x0010,
129
130    /// Ordinary names.  In C, everything that's not a label, tag,
131    /// or member ends up here.
132    IDNS_Ordinary            = 0x0020,
133
134    /// Objective C @protocol.
135    IDNS_ObjCProtocol        = 0x0040,
136
137    /// This declaration is a friend function.  A friend function
138    /// declaration is always in this namespace but may also be in
139    /// IDNS_Ordinary if it was previously declared.
140    IDNS_OrdinaryFriend      = 0x0080,
141
142    /// This declaration is a friend class.  A friend class
143    /// declaration is always in this namespace but may also be in
144    /// IDNS_Tag|IDNS_Type if it was previously declared.
145    IDNS_TagFriend           = 0x0100,
146
147    /// This declaration is a using declaration.  A using declaration
148    /// *introduces* a number of other declarations into the current
149    /// scope, and those declarations use the IDNS of their targets,
150    /// but the actual using declarations go in this namespace.
151    IDNS_Using               = 0x0200,
152
153    /// This declaration is a C++ operator declared in a non-class
154    /// context.  All such operators are also in IDNS_Ordinary.
155    /// C++ lexical operator lookup looks for these.
156    IDNS_NonMemberOperator   = 0x0400
157  };
158
159  /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
160  /// parameter types in method declarations.  Other than remembering
161  /// them and mangling them into the method's signature string, these
162  /// are ignored by the compiler; they are consumed by certain
163  /// remote-messaging frameworks.
164  ///
165  /// in, inout, and out are mutually exclusive and apply only to
166  /// method parameters.  bycopy and byref are mutually exclusive and
167  /// apply only to method parameters (?).  oneway applies only to
168  /// results.  All of these expect their corresponding parameter to
169  /// have a particular type.  None of this is currently enforced by
170  /// clang.
171  ///
172  /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
173  enum ObjCDeclQualifier {
174    OBJC_TQ_None = 0x0,
175    OBJC_TQ_In = 0x1,
176    OBJC_TQ_Inout = 0x2,
177    OBJC_TQ_Out = 0x4,
178    OBJC_TQ_Bycopy = 0x8,
179    OBJC_TQ_Byref = 0x10,
180    OBJC_TQ_Oneway = 0x20
181  };
182
183protected:
184  // Enumeration values used in the bits stored in NextInContextAndBits.
185  enum {
186    /// \brief Whether this declaration is a top-level declaration (function,
187    /// global variable, etc.) that is lexically inside an objc container
188    /// definition.
189    TopLevelDeclInObjCContainerFlag = 0x01,
190
191    /// \brief Whether this declaration is private to the module in which it was
192    /// defined.
193    ModulePrivateFlag = 0x02
194  };
195
196  /// \brief The next declaration within the same lexical
197  /// DeclContext. These pointers form the linked list that is
198  /// traversed via DeclContext's decls_begin()/decls_end().
199  ///
200  /// The extra two bits are used for the TopLevelDeclInObjCContainer and
201  /// ModulePrivate bits.
202  llvm::PointerIntPair<Decl *, 2, unsigned> NextInContextAndBits;
203
204private:
205  friend class DeclContext;
206
207  struct MultipleDC {
208    DeclContext *SemanticDC;
209    DeclContext *LexicalDC;
210  };
211
212
213  /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
214  /// For declarations that don't contain C++ scope specifiers, it contains
215  /// the DeclContext where the Decl was declared.
216  /// For declarations with C++ scope specifiers, it contains a MultipleDC*
217  /// with the context where it semantically belongs (SemanticDC) and the
218  /// context where it was lexically declared (LexicalDC).
219  /// e.g.:
220  ///
221  ///   namespace A {
222  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
223  ///   }
224  ///   void A::f(); // SemanticDC == namespace 'A'
225  ///                // LexicalDC == global namespace
226  llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
227
228  inline bool isInSemaDC() const    { return DeclCtx.is<DeclContext*>(); }
229  inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
230  inline MultipleDC *getMultipleDC() const {
231    return DeclCtx.get<MultipleDC*>();
232  }
233  inline DeclContext *getSemanticDC() const {
234    return DeclCtx.get<DeclContext*>();
235  }
236
237  /// Loc - The location of this decl.
238  SourceLocation Loc;
239
240  /// DeclKind - This indicates which class this is.
241  unsigned DeclKind : 8;
242
243  /// InvalidDecl - This indicates a semantic error occurred.
244  unsigned InvalidDecl :  1;
245
246  /// HasAttrs - This indicates whether the decl has attributes or not.
247  unsigned HasAttrs : 1;
248
249  /// Implicit - Whether this declaration was implicitly generated by
250  /// the implementation rather than explicitly written by the user.
251  unsigned Implicit : 1;
252
253  /// \brief Whether this declaration was "used", meaning that a definition is
254  /// required.
255  unsigned Used : 1;
256
257  /// \brief Whether this declaration was "referenced".
258  /// The difference with 'Used' is whether the reference appears in a
259  /// evaluated context or not, e.g. functions used in uninstantiated templates
260  /// are regarded as "referenced" but not "used".
261  unsigned Referenced : 1;
262
263  /// \brief Whether statistic collection is enabled.
264  static bool StatisticsEnabled;
265
266protected:
267  /// Access - Used by C++ decls for the access specifier.
268  // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
269  unsigned Access : 2;
270  friend class CXXClassMemberWrapper;
271
272  /// \brief Whether this declaration was loaded from an AST file.
273  unsigned FromASTFile : 1;
274
275  /// \brief Whether this declaration is hidden from normal name lookup, e.g.,
276  /// because it is was loaded from an AST file is either module-private or
277  /// because its submodule has not been made visible.
278  unsigned Hidden : 1;
279
280  /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
281  unsigned IdentifierNamespace : 12;
282
283  /// \brief Whether the \c CachedLinkage field is active.
284  ///
285  /// This field is only valid for NamedDecls subclasses.
286  mutable unsigned HasCachedLinkage : 1;
287
288  /// \brief If \c HasCachedLinkage, the linkage of this declaration.
289  ///
290  /// This field is only valid for NamedDecls subclasses.
291  mutable unsigned CachedLinkage : 2;
292
293  friend class ASTDeclWriter;
294  friend class ASTDeclReader;
295  friend class ASTReader;
296
297private:
298  void CheckAccessDeclContext() const;
299
300protected:
301
302  Decl(Kind DK, DeclContext *DC, SourceLocation L)
303    : NextInContextAndBits(), DeclCtx(DC),
304      Loc(L), DeclKind(DK), InvalidDecl(0),
305      HasAttrs(false), Implicit(false), Used(false), Referenced(false),
306      Access(AS_none), FromASTFile(0), Hidden(0),
307      IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
308      HasCachedLinkage(0)
309  {
310    if (StatisticsEnabled) add(DK);
311  }
312
313  Decl(Kind DK, EmptyShell Empty)
314    : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0),
315      HasAttrs(false), Implicit(false), Used(false), Referenced(false),
316      Access(AS_none), FromASTFile(0), Hidden(0),
317      IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
318      HasCachedLinkage(0)
319  {
320    if (StatisticsEnabled) add(DK);
321  }
322
323  virtual ~Decl();
324
325  /// \brief Allocate memory for a deserialized declaration.
326  ///
327  /// This routine must be used to allocate memory for any declaration that is
328  /// deserialized from a module file.
329  ///
330  /// \param Context The context in which we will allocate memory.
331  /// \param ID The global ID of the deserialized declaration.
332  /// \param Size The size of the allocated object.
333  static void *AllocateDeserializedDecl(const ASTContext &Context,
334                                        unsigned ID,
335                                        unsigned Size);
336
337public:
338
339  /// \brief Source range that this declaration covers.
340  virtual SourceRange getSourceRange() const {
341    return SourceRange(getLocation(), getLocation());
342  }
343  SourceLocation getLocStart() const { return getSourceRange().getBegin(); }
344  SourceLocation getLocEnd() const { return getSourceRange().getEnd(); }
345
346  SourceLocation getLocation() const { return Loc; }
347  void setLocation(SourceLocation L) { Loc = L; }
348
349  Kind getKind() const { return static_cast<Kind>(DeclKind); }
350  const char *getDeclKindName() const;
351
352  Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
353  const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
354
355  DeclContext *getDeclContext() {
356    if (isInSemaDC())
357      return getSemanticDC();
358    return getMultipleDC()->SemanticDC;
359  }
360  const DeclContext *getDeclContext() const {
361    return const_cast<Decl*>(this)->getDeclContext();
362  }
363
364  /// Finds the innermost non-closure context of this declaration.
365  /// That is, walk out the DeclContext chain, skipping any blocks.
366  DeclContext *getNonClosureContext();
367  const DeclContext *getNonClosureContext() const {
368    return const_cast<Decl*>(this)->getNonClosureContext();
369  }
370
371  TranslationUnitDecl *getTranslationUnitDecl();
372  const TranslationUnitDecl *getTranslationUnitDecl() const {
373    return const_cast<Decl*>(this)->getTranslationUnitDecl();
374  }
375
376  bool isInAnonymousNamespace() const;
377
378  ASTContext &getASTContext() const;
379
380  void setAccess(AccessSpecifier AS) {
381    Access = AS;
382#ifndef NDEBUG
383    CheckAccessDeclContext();
384#endif
385  }
386
387  AccessSpecifier getAccess() const {
388#ifndef NDEBUG
389    CheckAccessDeclContext();
390#endif
391    return AccessSpecifier(Access);
392  }
393
394  bool hasAttrs() const { return HasAttrs; }
395  void setAttrs(const AttrVec& Attrs) {
396    return setAttrsImpl(Attrs, getASTContext());
397  }
398  AttrVec &getAttrs() {
399    return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
400  }
401  const AttrVec &getAttrs() const;
402  void swapAttrs(Decl *D);
403  void dropAttrs();
404
405  void addAttr(Attr *A) {
406    if (hasAttrs())
407      getAttrs().push_back(A);
408    else
409      setAttrs(AttrVec(1, A));
410  }
411
412  typedef AttrVec::const_iterator attr_iterator;
413
414  // FIXME: Do not rely on iterators having comparable singular values.
415  //        Note that this should error out if they do not.
416  attr_iterator attr_begin() const {
417    return hasAttrs() ? getAttrs().begin() : 0;
418  }
419  attr_iterator attr_end() const {
420    return hasAttrs() ? getAttrs().end() : 0;
421  }
422
423  template <typename T>
424  void dropAttr() {
425    if (!HasAttrs) return;
426
427    AttrVec &Attrs = getAttrs();
428    for (unsigned i = 0, e = Attrs.size(); i != e; /* in loop */) {
429      if (isa<T>(Attrs[i])) {
430        Attrs.erase(Attrs.begin() + i);
431        --e;
432      }
433      else
434        ++i;
435    }
436    if (Attrs.empty())
437      HasAttrs = false;
438  }
439
440  template <typename T>
441  specific_attr_iterator<T> specific_attr_begin() const {
442    return specific_attr_iterator<T>(attr_begin());
443  }
444  template <typename T>
445  specific_attr_iterator<T> specific_attr_end() const {
446    return specific_attr_iterator<T>(attr_end());
447  }
448
449  template<typename T> T *getAttr() const {
450    return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : 0;
451  }
452  template<typename T> bool hasAttr() const {
453    return hasAttrs() && hasSpecificAttr<T>(getAttrs());
454  }
455
456  /// getMaxAlignment - return the maximum alignment specified by attributes
457  /// on this decl, 0 if there are none.
458  unsigned getMaxAlignment() const {
459    return hasAttrs() ? getMaxAttrAlignment(getAttrs(), getASTContext()) : 0;
460  }
461
462  /// setInvalidDecl - Indicates the Decl had a semantic error. This
463  /// allows for graceful error recovery.
464  void setInvalidDecl(bool Invalid = true);
465  bool isInvalidDecl() const { return (bool) InvalidDecl; }
466
467  /// isImplicit - Indicates whether the declaration was implicitly
468  /// generated by the implementation. If false, this declaration
469  /// was written explicitly in the source code.
470  bool isImplicit() const { return Implicit; }
471  void setImplicit(bool I = true) { Implicit = I; }
472
473  /// \brief Whether this declaration was used, meaning that a definition
474  /// is required.
475  ///
476  /// \param CheckUsedAttr When true, also consider the "used" attribute
477  /// (in addition to the "used" bit set by \c setUsed()) when determining
478  /// whether the function is used.
479  bool isUsed(bool CheckUsedAttr = true) const;
480
481  void setUsed(bool U = true) { Used = U; }
482
483  /// \brief Whether this declaration was referenced.
484  bool isReferenced() const;
485
486  void setReferenced(bool R = true) { Referenced = R; }
487
488  /// \brief Whether this declaration is a top-level declaration (function,
489  /// global variable, etc.) that is lexically inside an objc container
490  /// definition.
491  bool isTopLevelDeclInObjCContainer() const {
492    return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag;
493  }
494
495  void setTopLevelDeclInObjCContainer(bool V = true) {
496    unsigned Bits = NextInContextAndBits.getInt();
497    if (V)
498      Bits |= TopLevelDeclInObjCContainerFlag;
499    else
500      Bits &= ~TopLevelDeclInObjCContainerFlag;
501    NextInContextAndBits.setInt(Bits);
502  }
503
504protected:
505  /// \brief Whether this declaration was marked as being private to the
506  /// module in which it was defined.
507  bool isModulePrivate() const {
508    return NextInContextAndBits.getInt() & ModulePrivateFlag;
509  }
510
511  /// \brief Specify whether this declaration was marked as being private
512  /// to the module in which it was defined.
513  void setModulePrivate(bool MP = true) {
514    unsigned Bits = NextInContextAndBits.getInt();
515    if (MP)
516      Bits |= ModulePrivateFlag;
517    else
518      Bits &= ~ModulePrivateFlag;
519    NextInContextAndBits.setInt(Bits);
520  }
521
522  /// \brief Set the owning module ID.
523  void setOwningModuleID(unsigned ID) {
524    assert(isFromASTFile() && "Only works on a deserialized declaration");
525    *((unsigned*)this - 2) = ID;
526  }
527
528public:
529
530  /// \brief Determine the availability of the given declaration.
531  ///
532  /// This routine will determine the most restrictive availability of
533  /// the given declaration (e.g., preferring 'unavailable' to
534  /// 'deprecated').
535  ///
536  /// \param Message If non-NULL and the result is not \c
537  /// AR_Available, will be set to a (possibly empty) message
538  /// describing why the declaration has not been introduced, is
539  /// deprecated, or is unavailable.
540  AvailabilityResult getAvailability(std::string *Message = 0) const;
541
542  /// \brief Determine whether this declaration is marked 'deprecated'.
543  ///
544  /// \param Message If non-NULL and the declaration is deprecated,
545  /// this will be set to the message describing why the declaration
546  /// was deprecated (which may be empty).
547  bool isDeprecated(std::string *Message = 0) const {
548    return getAvailability(Message) == AR_Deprecated;
549  }
550
551  /// \brief Determine whether this declaration is marked 'unavailable'.
552  ///
553  /// \param Message If non-NULL and the declaration is unavailable,
554  /// this will be set to the message describing why the declaration
555  /// was made unavailable (which may be empty).
556  bool isUnavailable(std::string *Message = 0) const {
557    return getAvailability(Message) == AR_Unavailable;
558  }
559
560  /// \brief Determine whether this is a weak-imported symbol.
561  ///
562  /// Weak-imported symbols are typically marked with the
563  /// 'weak_import' attribute, but may also be marked with an
564  /// 'availability' attribute where we're targing a platform prior to
565  /// the introduction of this feature.
566  bool isWeakImported() const;
567
568  /// \brief Determines whether this symbol can be weak-imported,
569  /// e.g., whether it would be well-formed to add the weak_import
570  /// attribute.
571  ///
572  /// \param IsDefinition Set to \c true to indicate that this
573  /// declaration cannot be weak-imported because it has a definition.
574  bool canBeWeakImported(bool &IsDefinition) const;
575
576  /// \brief Determine whether this declaration came from an AST file (such as
577  /// a precompiled header or module) rather than having been parsed.
578  bool isFromASTFile() const { return FromASTFile; }
579
580  /// \brief Retrieve the global declaration ID associated with this
581  /// declaration, which specifies where in the
582  unsigned getGlobalID() const {
583    if (isFromASTFile())
584      return *((const unsigned*)this - 1);
585    return 0;
586  }
587
588  /// \brief Retrieve the global ID of the module that owns this particular
589  /// declaration.
590  unsigned getOwningModuleID() const {
591    if (isFromASTFile())
592      return *((const unsigned*)this - 2);
593
594    return 0;
595  }
596
597  unsigned getIdentifierNamespace() const {
598    return IdentifierNamespace;
599  }
600  bool isInIdentifierNamespace(unsigned NS) const {
601    return getIdentifierNamespace() & NS;
602  }
603  static unsigned getIdentifierNamespaceForKind(Kind DK);
604
605  bool hasTagIdentifierNamespace() const {
606    return isTagIdentifierNamespace(getIdentifierNamespace());
607  }
608  static bool isTagIdentifierNamespace(unsigned NS) {
609    // TagDecls have Tag and Type set and may also have TagFriend.
610    return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
611  }
612
613  /// getLexicalDeclContext - The declaration context where this Decl was
614  /// lexically declared (LexicalDC). May be different from
615  /// getDeclContext() (SemanticDC).
616  /// e.g.:
617  ///
618  ///   namespace A {
619  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
620  ///   }
621  ///   void A::f(); // SemanticDC == namespace 'A'
622  ///                // LexicalDC == global namespace
623  DeclContext *getLexicalDeclContext() {
624    if (isInSemaDC())
625      return getSemanticDC();
626    return getMultipleDC()->LexicalDC;
627  }
628  const DeclContext *getLexicalDeclContext() const {
629    return const_cast<Decl*>(this)->getLexicalDeclContext();
630  }
631
632  virtual bool isOutOfLine() const {
633    return getLexicalDeclContext() != getDeclContext();
634  }
635
636  /// setDeclContext - Set both the semantic and lexical DeclContext
637  /// to DC.
638  void setDeclContext(DeclContext *DC);
639
640  void setLexicalDeclContext(DeclContext *DC);
641
642  /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
643  /// scoped decl is defined outside the current function or method.  This is
644  /// roughly global variables and functions, but also handles enums (which
645  /// could be defined inside or outside a function etc).
646  bool isDefinedOutsideFunctionOrMethod() const {
647    return getParentFunctionOrMethod() == 0;
648  }
649
650  /// \brief If this decl is defined inside a function/method/block it returns
651  /// the corresponding DeclContext, otherwise it returns null.
652  const DeclContext *getParentFunctionOrMethod() const;
653  DeclContext *getParentFunctionOrMethod() {
654    return const_cast<DeclContext*>(
655                    const_cast<const Decl*>(this)->getParentFunctionOrMethod());
656  }
657
658  /// \brief Retrieves the "canonical" declaration of the given declaration.
659  virtual Decl *getCanonicalDecl() { return this; }
660  const Decl *getCanonicalDecl() const {
661    return const_cast<Decl*>(this)->getCanonicalDecl();
662  }
663
664  /// \brief Whether this particular Decl is a canonical one.
665  bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
666
667protected:
668  /// \brief Returns the next redeclaration or itself if this is the only decl.
669  ///
670  /// Decl subclasses that can be redeclared should override this method so that
671  /// Decl::redecl_iterator can iterate over them.
672  virtual Decl *getNextRedeclaration() { return this; }
673
674  /// \brief Implementation of getPreviousDecl(), to be overridden by any
675  /// subclass that has a redeclaration chain.
676  virtual Decl *getPreviousDeclImpl() { return 0; }
677
678  /// \brief Implementation of getMostRecentDecl(), to be overridden by any
679  /// subclass that has a redeclaration chain.
680  virtual Decl *getMostRecentDeclImpl() { return this; }
681
682public:
683  /// \brief Iterates through all the redeclarations of the same decl.
684  class redecl_iterator {
685    /// Current - The current declaration.
686    Decl *Current;
687    Decl *Starter;
688
689  public:
690    typedef Decl*                     value_type;
691    typedef Decl*                     reference;
692    typedef Decl*                     pointer;
693    typedef std::forward_iterator_tag iterator_category;
694    typedef std::ptrdiff_t            difference_type;
695
696    redecl_iterator() : Current(0) { }
697    explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
698
699    reference operator*() const { return Current; }
700    pointer operator->() const { return Current; }
701
702    redecl_iterator& operator++() {
703      assert(Current && "Advancing while iterator has reached end");
704      // Get either previous decl or latest decl.
705      Decl *Next = Current->getNextRedeclaration();
706      assert(Next && "Should return next redeclaration or itself, never null!");
707      Current = (Next != Starter ? Next : 0);
708      return *this;
709    }
710
711    redecl_iterator operator++(int) {
712      redecl_iterator tmp(*this);
713      ++(*this);
714      return tmp;
715    }
716
717    friend bool operator==(redecl_iterator x, redecl_iterator y) {
718      return x.Current == y.Current;
719    }
720    friend bool operator!=(redecl_iterator x, redecl_iterator y) {
721      return x.Current != y.Current;
722    }
723  };
724
725  /// \brief Returns iterator for all the redeclarations of the same decl.
726  /// It will iterate at least once (when this decl is the only one).
727  redecl_iterator redecls_begin() const {
728    return redecl_iterator(const_cast<Decl*>(this));
729  }
730  redecl_iterator redecls_end() const { return redecl_iterator(); }
731
732  /// \brief Retrieve the previous declaration that declares the same entity
733  /// as this declaration, or NULL if there is no previous declaration.
734  Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
735
736  /// \brief Retrieve the most recent declaration that declares the same entity
737  /// as this declaration, or NULL if there is no previous declaration.
738  const Decl *getPreviousDecl() const {
739    return const_cast<Decl *>(this)->getPreviousDeclImpl();
740  }
741
742  /// \brief Retrieve the most recent declaration that declares the same entity
743  /// as this declaration (which may be this declaration).
744  Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
745
746  /// \brief Retrieve the most recent declaration that declares the same entity
747  /// as this declaration (which may be this declaration).
748  const Decl *getMostRecentDecl() const {
749    return const_cast<Decl *>(this)->getMostRecentDeclImpl();
750  }
751
752  /// getBody - If this Decl represents a declaration for a body of code,
753  ///  such as a function or method definition, this method returns the
754  ///  top-level Stmt* of that body.  Otherwise this method returns null.
755  virtual Stmt* getBody() const { return 0; }
756
757  /// \brief Returns true if this Decl represents a declaration for a body of
758  /// code, such as a function or method definition.
759  virtual bool hasBody() const { return getBody() != 0; }
760
761  /// getBodyRBrace - Gets the right brace of the body, if a body exists.
762  /// This works whether the body is a CompoundStmt or a CXXTryStmt.
763  SourceLocation getBodyRBrace() const;
764
765  // global temp stats (until we have a per-module visitor)
766  static void add(Kind k);
767  static void EnableStatistics();
768  static void PrintStats();
769
770  /// isTemplateParameter - Determines whether this declaration is a
771  /// template parameter.
772  bool isTemplateParameter() const;
773
774  /// isTemplateParameter - Determines whether this declaration is a
775  /// template parameter pack.
776  bool isTemplateParameterPack() const;
777
778  /// \brief Whether this declaration is a parameter pack.
779  bool isParameterPack() const;
780
781  /// \brief returns true if this declaration is a template
782  bool isTemplateDecl() const;
783
784  /// \brief Whether this declaration is a function or function template.
785  bool isFunctionOrFunctionTemplate() const;
786
787  /// \brief Changes the namespace of this declaration to reflect that it's
788  /// the object of a friend declaration.
789  ///
790  /// These declarations appear in the lexical context of the friending
791  /// class, but in the semantic context of the actual entity.  This property
792  /// applies only to a specific decl object;  other redeclarations of the
793  /// same entity may not (and probably don't) share this property.
794  void setObjectOfFriendDecl(bool PreviouslyDeclared) {
795    unsigned OldNS = IdentifierNamespace;
796    assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
797                     IDNS_TagFriend | IDNS_OrdinaryFriend)) &&
798           "namespace includes neither ordinary nor tag");
799    assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
800                       IDNS_TagFriend | IDNS_OrdinaryFriend)) &&
801           "namespace includes other than ordinary or tag");
802
803    IdentifierNamespace = 0;
804    if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
805      IdentifierNamespace |= IDNS_TagFriend;
806      if (PreviouslyDeclared) IdentifierNamespace |= IDNS_Tag | IDNS_Type;
807    }
808
809    if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend)) {
810      IdentifierNamespace |= IDNS_OrdinaryFriend;
811      if (PreviouslyDeclared) IdentifierNamespace |= IDNS_Ordinary;
812    }
813  }
814
815  enum FriendObjectKind {
816    FOK_None, // not a friend object
817    FOK_Declared, // a friend of a previously-declared entity
818    FOK_Undeclared // a friend of a previously-undeclared entity
819  };
820
821  /// \brief Determines whether this declaration is the object of a
822  /// friend declaration and, if so, what kind.
823  ///
824  /// There is currently no direct way to find the associated FriendDecl.
825  FriendObjectKind getFriendObjectKind() const {
826    unsigned mask
827      = (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
828    if (!mask) return FOK_None;
829    return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ?
830              FOK_Declared : FOK_Undeclared);
831  }
832
833  /// Specifies that this declaration is a C++ overloaded non-member.
834  void setNonMemberOperator() {
835    assert(getKind() == Function || getKind() == FunctionTemplate);
836    assert((IdentifierNamespace & IDNS_Ordinary) &&
837           "visible non-member operators should be in ordinary namespace");
838    IdentifierNamespace |= IDNS_NonMemberOperator;
839  }
840
841  // Implement isa/cast/dyncast/etc.
842  static bool classof(const Decl *) { return true; }
843  static bool classofKind(Kind K) { return true; }
844  static DeclContext *castToDeclContext(const Decl *);
845  static Decl *castFromDeclContext(const DeclContext *);
846
847  void print(raw_ostream &Out, unsigned Indentation = 0,
848             bool PrintInstantiation = false) const;
849  void print(raw_ostream &Out, const PrintingPolicy &Policy,
850             unsigned Indentation = 0, bool PrintInstantiation = false) const;
851  static void printGroup(Decl** Begin, unsigned NumDecls,
852                         raw_ostream &Out, const PrintingPolicy &Policy,
853                         unsigned Indentation = 0);
854  LLVM_ATTRIBUTE_USED void dump() const;
855  LLVM_ATTRIBUTE_USED void dumpXML() const;
856  void dumpXML(raw_ostream &OS) const;
857
858private:
859  const Attr *getAttrsImpl() const;
860  void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
861  void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
862                           ASTContext &Ctx);
863
864protected:
865  ASTMutationListener *getASTMutationListener() const;
866};
867
868/// \brief Determine whether two declarations declare the same entity.
869inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
870  if (!D1 || !D2)
871    return false;
872
873  if (D1 == D2)
874    return true;
875
876  return D1->getCanonicalDecl() == D2->getCanonicalDecl();
877}
878
879/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
880/// doing something to a specific decl.
881class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
882  const Decl *TheDecl;
883  SourceLocation Loc;
884  SourceManager &SM;
885  const char *Message;
886public:
887  PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
888                       SourceManager &sm, const char *Msg)
889  : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
890
891  virtual void print(raw_ostream &OS) const;
892};
893
894class DeclContextLookupResult
895  : public std::pair<NamedDecl**,NamedDecl**> {
896public:
897  DeclContextLookupResult(NamedDecl **I, NamedDecl **E)
898    : std::pair<NamedDecl**,NamedDecl**>(I, E) {}
899  DeclContextLookupResult()
900    : std::pair<NamedDecl**,NamedDecl**>() {}
901
902  using std::pair<NamedDecl**,NamedDecl**>::operator=;
903};
904
905class DeclContextLookupConstResult
906  : public std::pair<NamedDecl*const*, NamedDecl*const*> {
907public:
908  DeclContextLookupConstResult(std::pair<NamedDecl**,NamedDecl**> R)
909    : std::pair<NamedDecl*const*, NamedDecl*const*>(R) {}
910  DeclContextLookupConstResult(NamedDecl * const *I, NamedDecl * const *E)
911    : std::pair<NamedDecl*const*, NamedDecl*const*>(I, E) {}
912  DeclContextLookupConstResult()
913    : std::pair<NamedDecl*const*, NamedDecl*const*>() {}
914
915  using std::pair<NamedDecl*const*,NamedDecl*const*>::operator=;
916};
917
918/// DeclContext - This is used only as base class of specific decl types that
919/// can act as declaration contexts. These decls are (only the top classes
920/// that directly derive from DeclContext are mentioned, not their subclasses):
921///
922///   TranslationUnitDecl
923///   NamespaceDecl
924///   FunctionDecl
925///   TagDecl
926///   ObjCMethodDecl
927///   ObjCContainerDecl
928///   LinkageSpecDecl
929///   BlockDecl
930///
931class DeclContext {
932  /// DeclKind - This indicates which class this is.
933  unsigned DeclKind : 8;
934
935  /// \brief Whether this declaration context also has some external
936  /// storage that contains additional declarations that are lexically
937  /// part of this context.
938  mutable unsigned ExternalLexicalStorage : 1;
939
940  /// \brief Whether this declaration context also has some external
941  /// storage that contains additional declarations that are visible
942  /// in this context.
943  mutable unsigned ExternalVisibleStorage : 1;
944
945  /// \brief Pointer to the data structure used to lookup declarations
946  /// within this context (or a DependentStoredDeclsMap if this is a
947  /// dependent context).
948  mutable StoredDeclsMap *LookupPtr;
949
950protected:
951  /// FirstDecl - The first declaration stored within this declaration
952  /// context.
953  mutable Decl *FirstDecl;
954
955  /// LastDecl - The last declaration stored within this declaration
956  /// context. FIXME: We could probably cache this value somewhere
957  /// outside of the DeclContext, to reduce the size of DeclContext by
958  /// another pointer.
959  mutable Decl *LastDecl;
960
961  friend class ExternalASTSource;
962
963  /// \brief Build up a chain of declarations.
964  ///
965  /// \returns the first/last pair of declarations.
966  static std::pair<Decl *, Decl *>
967  BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
968
969   DeclContext(Decl::Kind K)
970     : DeclKind(K), ExternalLexicalStorage(false),
971       ExternalVisibleStorage(false), LookupPtr(0), FirstDecl(0),
972       LastDecl(0) { }
973
974public:
975  ~DeclContext();
976
977  Decl::Kind getDeclKind() const {
978    return static_cast<Decl::Kind>(DeclKind);
979  }
980  const char *getDeclKindName() const;
981
982  /// getParent - Returns the containing DeclContext.
983  DeclContext *getParent() {
984    return cast<Decl>(this)->getDeclContext();
985  }
986  const DeclContext *getParent() const {
987    return const_cast<DeclContext*>(this)->getParent();
988  }
989
990  /// getLexicalParent - Returns the containing lexical DeclContext. May be
991  /// different from getParent, e.g.:
992  ///
993  ///   namespace A {
994  ///      struct S;
995  ///   }
996  ///   struct A::S {}; // getParent() == namespace 'A'
997  ///                   // getLexicalParent() == translation unit
998  ///
999  DeclContext *getLexicalParent() {
1000    return cast<Decl>(this)->getLexicalDeclContext();
1001  }
1002  const DeclContext *getLexicalParent() const {
1003    return const_cast<DeclContext*>(this)->getLexicalParent();
1004  }
1005
1006  DeclContext *getLookupParent();
1007
1008  const DeclContext *getLookupParent() const {
1009    return const_cast<DeclContext*>(this)->getLookupParent();
1010  }
1011
1012  ASTContext &getParentASTContext() const {
1013    return cast<Decl>(this)->getASTContext();
1014  }
1015
1016  bool isClosure() const {
1017    return DeclKind == Decl::Block;
1018  }
1019
1020  bool isObjCContainer() const {
1021    switch (DeclKind) {
1022        case Decl::ObjCCategory:
1023        case Decl::ObjCCategoryImpl:
1024        case Decl::ObjCImplementation:
1025        case Decl::ObjCInterface:
1026        case Decl::ObjCProtocol:
1027            return true;
1028    }
1029    return false;
1030  }
1031
1032  bool isFunctionOrMethod() const {
1033    switch (DeclKind) {
1034    case Decl::Block:
1035    case Decl::ObjCMethod:
1036      return true;
1037    default:
1038      return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1039    }
1040  }
1041
1042  bool isFileContext() const {
1043    return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1044  }
1045
1046  bool isTranslationUnit() const {
1047    return DeclKind == Decl::TranslationUnit;
1048  }
1049
1050  bool isRecord() const {
1051    return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1052  }
1053
1054  bool isNamespace() const {
1055    return DeclKind == Decl::Namespace;
1056  }
1057
1058  bool isInlineNamespace() const;
1059
1060  /// \brief Determines whether this context is dependent on a
1061  /// template parameter.
1062  bool isDependentContext() const;
1063
1064  /// isTransparentContext - Determines whether this context is a
1065  /// "transparent" context, meaning that the members declared in this
1066  /// context are semantically declared in the nearest enclosing
1067  /// non-transparent (opaque) context but are lexically declared in
1068  /// this context. For example, consider the enumerators of an
1069  /// enumeration type:
1070  /// @code
1071  /// enum E {
1072  ///   Val1
1073  /// };
1074  /// @endcode
1075  /// Here, E is a transparent context, so its enumerator (Val1) will
1076  /// appear (semantically) that it is in the same context of E.
1077  /// Examples of transparent contexts include: enumerations (except for
1078  /// C++0x scoped enums), and C++ linkage specifications.
1079  bool isTransparentContext() const;
1080
1081  /// \brief Determines whether this context is, or is nested within,
1082  /// a C++ extern "C" linkage spec.
1083  bool isExternCContext() const;
1084
1085  /// \brief Determine whether this declaration context is equivalent
1086  /// to the declaration context DC.
1087  bool Equals(const DeclContext *DC) const {
1088    return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1089  }
1090
1091  /// \brief Determine whether this declaration context encloses the
1092  /// declaration context DC.
1093  bool Encloses(const DeclContext *DC) const;
1094
1095  /// \brief Find the nearest non-closure ancestor of this context,
1096  /// i.e. the innermost semantic parent of this context which is not
1097  /// a closure.  A context may be its own non-closure ancestor.
1098  DeclContext *getNonClosureAncestor();
1099  const DeclContext *getNonClosureAncestor() const {
1100    return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1101  }
1102
1103  /// getPrimaryContext - There may be many different
1104  /// declarations of the same entity (including forward declarations
1105  /// of classes, multiple definitions of namespaces, etc.), each with
1106  /// a different set of declarations. This routine returns the
1107  /// "primary" DeclContext structure, which will contain the
1108  /// information needed to perform name lookup into this context.
1109  DeclContext *getPrimaryContext();
1110  const DeclContext *getPrimaryContext() const {
1111    return const_cast<DeclContext*>(this)->getPrimaryContext();
1112  }
1113
1114  /// getRedeclContext - Retrieve the context in which an entity conflicts with
1115  /// other entities of the same name, or where it is a redeclaration if the
1116  /// two entities are compatible. This skips through transparent contexts.
1117  DeclContext *getRedeclContext();
1118  const DeclContext *getRedeclContext() const {
1119    return const_cast<DeclContext *>(this)->getRedeclContext();
1120  }
1121
1122  /// \brief Retrieve the nearest enclosing namespace context.
1123  DeclContext *getEnclosingNamespaceContext();
1124  const DeclContext *getEnclosingNamespaceContext() const {
1125    return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1126  }
1127
1128  /// \brief Test if this context is part of the enclosing namespace set of
1129  /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1130  /// isn't a namespace, this is equivalent to Equals().
1131  ///
1132  /// The enclosing namespace set of a namespace is the namespace and, if it is
1133  /// inline, its enclosing namespace, recursively.
1134  bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1135
1136  /// \\brief Collects all of the declaration contexts that are semantically
1137  /// connected to this declaration context.
1138  ///
1139  /// For declaration contexts that have multiple semantically connected but
1140  /// syntactically distinct contexts, such as C++ namespaces, this routine
1141  /// retrieves the complete set of such declaration contexts in source order.
1142  /// For example, given:
1143  ///
1144  /// \code
1145  /// namespace N {
1146  ///   int x;
1147  /// }
1148  /// namespace N {
1149  ///   int y;
1150  /// }
1151  /// \endcode
1152  ///
1153  /// The \c Contexts parameter will contain both definitions of N.
1154  ///
1155  /// \param Contexts Will be cleared and set to the set of declaration
1156  /// contexts that are semanticaly connected to this declaration context,
1157  /// in source order, including this context (which may be the only result,
1158  /// for non-namespace contexts).
1159  void collectAllContexts(llvm::SmallVectorImpl<DeclContext *> &Contexts);
1160
1161  /// decl_iterator - Iterates through the declarations stored
1162  /// within this context.
1163  class decl_iterator {
1164    /// Current - The current declaration.
1165    Decl *Current;
1166
1167  public:
1168    typedef Decl*                     value_type;
1169    typedef Decl*                     reference;
1170    typedef Decl*                     pointer;
1171    typedef std::forward_iterator_tag iterator_category;
1172    typedef std::ptrdiff_t            difference_type;
1173
1174    decl_iterator() : Current(0) { }
1175    explicit decl_iterator(Decl *C) : Current(C) { }
1176
1177    reference operator*() const { return Current; }
1178    pointer operator->() const { return Current; }
1179
1180    decl_iterator& operator++() {
1181      Current = Current->getNextDeclInContext();
1182      return *this;
1183    }
1184
1185    decl_iterator operator++(int) {
1186      decl_iterator tmp(*this);
1187      ++(*this);
1188      return tmp;
1189    }
1190
1191    friend bool operator==(decl_iterator x, decl_iterator y) {
1192      return x.Current == y.Current;
1193    }
1194    friend bool operator!=(decl_iterator x, decl_iterator y) {
1195      return x.Current != y.Current;
1196    }
1197  };
1198
1199  /// decls_begin/decls_end - Iterate over the declarations stored in
1200  /// this context.
1201  decl_iterator decls_begin() const;
1202  decl_iterator decls_end() const;
1203  bool decls_empty() const;
1204
1205  /// noload_decls_begin/end - Iterate over the declarations stored in this
1206  /// context that are currently loaded; don't attempt to retrieve anything
1207  /// from an external source.
1208  decl_iterator noload_decls_begin() const;
1209  decl_iterator noload_decls_end() const;
1210
1211  /// specific_decl_iterator - Iterates over a subrange of
1212  /// declarations stored in a DeclContext, providing only those that
1213  /// are of type SpecificDecl (or a class derived from it). This
1214  /// iterator is used, for example, to provide iteration over just
1215  /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1216  template<typename SpecificDecl>
1217  class specific_decl_iterator {
1218    /// Current - The current, underlying declaration iterator, which
1219    /// will either be NULL or will point to a declaration of
1220    /// type SpecificDecl.
1221    DeclContext::decl_iterator Current;
1222
1223    /// SkipToNextDecl - Advances the current position up to the next
1224    /// declaration of type SpecificDecl that also meets the criteria
1225    /// required by Acceptable.
1226    void SkipToNextDecl() {
1227      while (*Current && !isa<SpecificDecl>(*Current))
1228        ++Current;
1229    }
1230
1231  public:
1232    typedef SpecificDecl* value_type;
1233    typedef SpecificDecl* reference;
1234    typedef SpecificDecl* pointer;
1235    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1236      difference_type;
1237    typedef std::forward_iterator_tag iterator_category;
1238
1239    specific_decl_iterator() : Current() { }
1240
1241    /// specific_decl_iterator - Construct a new iterator over a
1242    /// subset of the declarations the range [C,
1243    /// end-of-declarations). If A is non-NULL, it is a pointer to a
1244    /// member function of SpecificDecl that should return true for
1245    /// all of the SpecificDecl instances that will be in the subset
1246    /// of iterators. For example, if you want Objective-C instance
1247    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1248    /// &ObjCMethodDecl::isInstanceMethod.
1249    explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1250      SkipToNextDecl();
1251    }
1252
1253    reference operator*() const { return cast<SpecificDecl>(*Current); }
1254    pointer operator->() const { return cast<SpecificDecl>(*Current); }
1255
1256    specific_decl_iterator& operator++() {
1257      ++Current;
1258      SkipToNextDecl();
1259      return *this;
1260    }
1261
1262    specific_decl_iterator operator++(int) {
1263      specific_decl_iterator tmp(*this);
1264      ++(*this);
1265      return tmp;
1266    }
1267
1268    friend bool operator==(const specific_decl_iterator& x,
1269                           const specific_decl_iterator& y) {
1270      return x.Current == y.Current;
1271    }
1272
1273    friend bool operator!=(const specific_decl_iterator& x,
1274                           const specific_decl_iterator& y) {
1275      return x.Current != y.Current;
1276    }
1277  };
1278
1279  /// \brief Iterates over a filtered subrange of declarations stored
1280  /// in a DeclContext.
1281  ///
1282  /// This iterator visits only those declarations that are of type
1283  /// SpecificDecl (or a class derived from it) and that meet some
1284  /// additional run-time criteria. This iterator is used, for
1285  /// example, to provide access to the instance methods within an
1286  /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1287  /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1288  template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1289  class filtered_decl_iterator {
1290    /// Current - The current, underlying declaration iterator, which
1291    /// will either be NULL or will point to a declaration of
1292    /// type SpecificDecl.
1293    DeclContext::decl_iterator Current;
1294
1295    /// SkipToNextDecl - Advances the current position up to the next
1296    /// declaration of type SpecificDecl that also meets the criteria
1297    /// required by Acceptable.
1298    void SkipToNextDecl() {
1299      while (*Current &&
1300             (!isa<SpecificDecl>(*Current) ||
1301              (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1302        ++Current;
1303    }
1304
1305  public:
1306    typedef SpecificDecl* value_type;
1307    typedef SpecificDecl* reference;
1308    typedef SpecificDecl* pointer;
1309    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1310      difference_type;
1311    typedef std::forward_iterator_tag iterator_category;
1312
1313    filtered_decl_iterator() : Current() { }
1314
1315    /// specific_decl_iterator - Construct a new iterator over a
1316    /// subset of the declarations the range [C,
1317    /// end-of-declarations). If A is non-NULL, it is a pointer to a
1318    /// member function of SpecificDecl that should return true for
1319    /// all of the SpecificDecl instances that will be in the subset
1320    /// of iterators. For example, if you want Objective-C instance
1321    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1322    /// &ObjCMethodDecl::isInstanceMethod.
1323    explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1324      SkipToNextDecl();
1325    }
1326
1327    reference operator*() const { return cast<SpecificDecl>(*Current); }
1328    pointer operator->() const { return cast<SpecificDecl>(*Current); }
1329
1330    filtered_decl_iterator& operator++() {
1331      ++Current;
1332      SkipToNextDecl();
1333      return *this;
1334    }
1335
1336    filtered_decl_iterator operator++(int) {
1337      filtered_decl_iterator tmp(*this);
1338      ++(*this);
1339      return tmp;
1340    }
1341
1342    friend bool operator==(const filtered_decl_iterator& x,
1343                           const filtered_decl_iterator& y) {
1344      return x.Current == y.Current;
1345    }
1346
1347    friend bool operator!=(const filtered_decl_iterator& x,
1348                           const filtered_decl_iterator& y) {
1349      return x.Current != y.Current;
1350    }
1351  };
1352
1353  /// @brief Add the declaration D into this context.
1354  ///
1355  /// This routine should be invoked when the declaration D has first
1356  /// been declared, to place D into the context where it was
1357  /// (lexically) defined. Every declaration must be added to one
1358  /// (and only one!) context, where it can be visited via
1359  /// [decls_begin(), decls_end()). Once a declaration has been added
1360  /// to its lexical context, the corresponding DeclContext owns the
1361  /// declaration.
1362  ///
1363  /// If D is also a NamedDecl, it will be made visible within its
1364  /// semantic context via makeDeclVisibleInContext.
1365  void addDecl(Decl *D);
1366
1367  /// @brief Add the declaration D into this context, but suppress
1368  /// searches for external declarations with the same name.
1369  ///
1370  /// Although analogous in function to addDecl, this removes an
1371  /// important check.  This is only useful if the Decl is being
1372  /// added in response to an external search; in all other cases,
1373  /// addDecl() is the right function to use.
1374  /// See the ASTImporter for use cases.
1375  void addDeclInternal(Decl *D);
1376
1377  /// @brief Add the declaration D to this context without modifying
1378  /// any lookup tables.
1379  ///
1380  /// This is useful for some operations in dependent contexts where
1381  /// the semantic context might not be dependent;  this basically
1382  /// only happens with friends.
1383  void addHiddenDecl(Decl *D);
1384
1385  /// @brief Removes a declaration from this context.
1386  void removeDecl(Decl *D);
1387
1388  /// lookup_iterator - An iterator that provides access to the results
1389  /// of looking up a name within this context.
1390  typedef NamedDecl **lookup_iterator;
1391
1392  /// lookup_const_iterator - An iterator that provides non-mutable
1393  /// access to the results of lookup up a name within this context.
1394  typedef NamedDecl * const * lookup_const_iterator;
1395
1396  typedef DeclContextLookupResult lookup_result;
1397  typedef DeclContextLookupConstResult lookup_const_result;
1398
1399  /// lookup - Find the declarations (if any) with the given Name in
1400  /// this context. Returns a range of iterators that contains all of
1401  /// the declarations with this name, with object, function, member,
1402  /// and enumerator names preceding any tag name. Note that this
1403  /// routine will not look into parent contexts.
1404  lookup_result lookup(DeclarationName Name);
1405  lookup_const_result lookup(DeclarationName Name) const;
1406
1407  /// \brief A simplistic name lookup mechanism that performs name lookup
1408  /// into this declaration context without consulting the external source.
1409  ///
1410  /// This function should almost never be used, because it subverts the
1411  /// usual relationship between a DeclContext and the external source.
1412  /// See the ASTImporter for the (few, but important) use cases.
1413  void localUncachedLookup(DeclarationName Name,
1414                           llvm::SmallVectorImpl<NamedDecl *> &Results);
1415
1416  /// @brief Makes a declaration visible within this context.
1417  ///
1418  /// This routine makes the declaration D visible to name lookup
1419  /// within this context and, if this is a transparent context,
1420  /// within its parent contexts up to the first enclosing
1421  /// non-transparent context. Making a declaration visible within a
1422  /// context does not transfer ownership of a declaration, and a
1423  /// declaration can be visible in many contexts that aren't its
1424  /// lexical context.
1425  ///
1426  /// If D is a redeclaration of an existing declaration that is
1427  /// visible from this context, as determined by
1428  /// NamedDecl::declarationReplaces, the previous declaration will be
1429  /// replaced with D.
1430  ///
1431  /// @param Recoverable true if it's okay to not add this decl to
1432  /// the lookup tables because it can be easily recovered by walking
1433  /// the declaration chains.
1434  void makeDeclVisibleInContext(NamedDecl *D, bool Recoverable = true);
1435
1436  /// udir_iterator - Iterates through the using-directives stored
1437  /// within this context.
1438  typedef UsingDirectiveDecl * const * udir_iterator;
1439
1440  typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
1441
1442  udir_iterator_range getUsingDirectives() const;
1443
1444  udir_iterator using_directives_begin() const {
1445    return getUsingDirectives().first;
1446  }
1447
1448  udir_iterator using_directives_end() const {
1449    return getUsingDirectives().second;
1450  }
1451
1452  // These are all defined in DependentDiagnostic.h.
1453  class ddiag_iterator;
1454  inline ddiag_iterator ddiag_begin() const;
1455  inline ddiag_iterator ddiag_end() const;
1456
1457  // Low-level accessors
1458
1459  /// \brief Retrieve the internal representation of the lookup structure.
1460  StoredDeclsMap* getLookupPtr() const { return LookupPtr; }
1461
1462  /// \brief Whether this DeclContext has external storage containing
1463  /// additional declarations that are lexically in this context.
1464  bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1465
1466  /// \brief State whether this DeclContext has external storage for
1467  /// declarations lexically in this context.
1468  void setHasExternalLexicalStorage(bool ES = true) {
1469    ExternalLexicalStorage = ES;
1470  }
1471
1472  /// \brief Whether this DeclContext has external storage containing
1473  /// additional declarations that are visible in this context.
1474  bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1475
1476  /// \brief State whether this DeclContext has external storage for
1477  /// declarations visible in this context.
1478  void setHasExternalVisibleStorage(bool ES = true) {
1479    ExternalVisibleStorage = ES;
1480  }
1481
1482  /// \brief Determine whether the given declaration is stored in the list of
1483  /// declarations lexically within this context.
1484  bool isDeclInLexicalTraversal(const Decl *D) const {
1485    return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1486                 D == LastDecl);
1487  }
1488
1489  static bool classof(const Decl *D);
1490  static bool classof(const DeclContext *D) { return true; }
1491#define DECL(NAME, BASE)
1492#define DECL_CONTEXT(NAME) \
1493  static bool classof(const NAME##Decl *D) { return true; }
1494#include "clang/AST/DeclNodes.inc"
1495
1496  LLVM_ATTRIBUTE_USED void dumpDeclContext() const;
1497
1498private:
1499  void LoadLexicalDeclsFromExternalStorage() const;
1500
1501  /// @brief Makes a declaration visible within this context, but
1502  /// suppresses searches for external declarations with the same
1503  /// name.
1504  ///
1505  /// Analogous to makeDeclVisibleInContext, but for the exclusive
1506  /// use of addDeclInternal().
1507  void makeDeclVisibleInContextInternal(NamedDecl *D,
1508                                        bool Recoverable = true);
1509
1510  friend class DependentDiagnostic;
1511  StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1512
1513  void buildLookup(DeclContext *DCtx);
1514  void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1515                                         bool Recoverable);
1516  void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1517};
1518
1519inline bool Decl::isTemplateParameter() const {
1520  return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1521         getKind() == TemplateTemplateParm;
1522}
1523
1524// Specialization selected when ToTy is not a known subclass of DeclContext.
1525template <class ToTy,
1526          bool IsKnownSubtype = ::llvm::is_base_of< DeclContext, ToTy>::value>
1527struct cast_convert_decl_context {
1528  static const ToTy *doit(const DeclContext *Val) {
1529    return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1530  }
1531
1532  static ToTy *doit(DeclContext *Val) {
1533    return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1534  }
1535};
1536
1537// Specialization selected when ToTy is a known subclass of DeclContext.
1538template <class ToTy>
1539struct cast_convert_decl_context<ToTy, true> {
1540  static const ToTy *doit(const DeclContext *Val) {
1541    return static_cast<const ToTy*>(Val);
1542  }
1543
1544  static ToTy *doit(DeclContext *Val) {
1545    return static_cast<ToTy*>(Val);
1546  }
1547};
1548
1549
1550} // end clang.
1551
1552namespace llvm {
1553
1554/// isa<T>(DeclContext*)
1555template <typename To>
1556struct isa_impl<To, ::clang::DeclContext> {
1557  static bool doit(const ::clang::DeclContext &Val) {
1558    return To::classofKind(Val.getDeclKind());
1559  }
1560};
1561
1562/// cast<T>(DeclContext*)
1563template<class ToTy>
1564struct cast_convert_val<ToTy,
1565                        const ::clang::DeclContext,const ::clang::DeclContext> {
1566  static const ToTy &doit(const ::clang::DeclContext &Val) {
1567    return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1568  }
1569};
1570template<class ToTy>
1571struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
1572  static ToTy &doit(::clang::DeclContext &Val) {
1573    return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1574  }
1575};
1576template<class ToTy>
1577struct cast_convert_val<ToTy,
1578                     const ::clang::DeclContext*, const ::clang::DeclContext*> {
1579  static const ToTy *doit(const ::clang::DeclContext *Val) {
1580    return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1581  }
1582};
1583template<class ToTy>
1584struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
1585  static ToTy *doit(::clang::DeclContext *Val) {
1586    return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1587  }
1588};
1589
1590/// Implement cast_convert_val for Decl -> DeclContext conversions.
1591template<class FromTy>
1592struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1593  static ::clang::DeclContext &doit(const FromTy &Val) {
1594    return *FromTy::castToDeclContext(&Val);
1595  }
1596};
1597
1598template<class FromTy>
1599struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1600  static ::clang::DeclContext *doit(const FromTy *Val) {
1601    return FromTy::castToDeclContext(Val);
1602  }
1603};
1604
1605template<class FromTy>
1606struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1607  static const ::clang::DeclContext &doit(const FromTy &Val) {
1608    return *FromTy::castToDeclContext(&Val);
1609  }
1610};
1611
1612template<class FromTy>
1613struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1614  static const ::clang::DeclContext *doit(const FromTy *Val) {
1615    return FromTy::castToDeclContext(Val);
1616  }
1617};
1618
1619} // end namespace llvm
1620
1621#endif
1622