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