clang API Documentation

DeclBase.h
Go to the documentation of this file.
00001 //===-- DeclBase.h - Base Classes for representing declarations -*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the Decl and DeclContext interfaces.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_CLANG_AST_DECLBASE_H
00015 #define LLVM_CLANG_AST_DECLBASE_H
00016 
00017 #include "clang/AST/Attr.h"
00018 #include "clang/AST/DeclarationName.h"
00019 #include "clang/AST/Type.h"
00020 #include "clang/Basic/Specifiers.h"
00021 #include "llvm/ADT/PointerUnion.h"
00022 #include "llvm/Support/Compiler.h"
00023 #include "llvm/Support/PrettyStackTrace.h"
00024 
00025 namespace clang {
00026 class DeclContext;
00027 class TranslationUnitDecl;
00028 class NamespaceDecl;
00029 class UsingDirectiveDecl;
00030 class NamedDecl;
00031 class FunctionDecl;
00032 class CXXRecordDecl;
00033 class EnumDecl;
00034 class ObjCMethodDecl;
00035 class ObjCContainerDecl;
00036 class ObjCInterfaceDecl;
00037 class ObjCCategoryDecl;
00038 class ObjCProtocolDecl;
00039 class ObjCImplementationDecl;
00040 class ObjCCategoryImplDecl;
00041 class ObjCImplDecl;
00042 class LinkageSpecDecl;
00043 class BlockDecl;
00044 class DeclarationName;
00045 class CompoundStmt;
00046 class StoredDeclsMap;
00047 class DependentDiagnostic;
00048 class ASTMutationListener;
00049 }
00050 
00051 namespace llvm {
00052 // DeclContext* is only 4-byte aligned on 32-bit systems.
00053 template<>
00054   class PointerLikeTypeTraits<clang::DeclContext*> {
00055   typedef clang::DeclContext* PT;
00056 public:
00057   static inline void *getAsVoidPointer(PT P) { return P; }
00058   static inline PT getFromVoidPointer(void *P) {
00059     return static_cast<PT>(P);
00060   }
00061   enum { NumLowBitsAvailable = 2 };
00062 };
00063 }
00064 
00065 namespace clang {
00066 
00067   /// \brief Captures the result of checking the availability of a
00068   /// declaration.
00069   enum AvailabilityResult {
00070     AR_Available = 0,
00071     AR_NotYetIntroduced,
00072     AR_Deprecated,
00073     AR_Unavailable
00074   };
00075 
00076 /// Decl - This represents one declaration (or definition), e.g. a variable,
00077 /// typedef, function, struct, etc.
00078 ///
00079 class Decl {
00080 public:
00081   /// \brief Lists the kind of concrete classes of Decl.
00082   enum Kind {
00083 #define DECL(DERIVED, BASE) DERIVED,
00084 #define ABSTRACT_DECL(DECL)
00085 #define DECL_RANGE(BASE, START, END) \
00086         first##BASE = START, last##BASE = END,
00087 #define LAST_DECL_RANGE(BASE, START, END) \
00088         first##BASE = START, last##BASE = END
00089 #include "clang/AST/DeclNodes.inc"
00090   };
00091 
00092   /// \brief A placeholder type used to construct an empty shell of a
00093   /// decl-derived type that will be filled in later (e.g., by some
00094   /// deserialization method).
00095   struct EmptyShell { };
00096 
00097   /// IdentifierNamespace - The different namespaces in which
00098   /// declarations may appear.  According to C99 6.2.3, there are
00099   /// four namespaces, labels, tags, members and ordinary
00100   /// identifiers.  C++ describes lookup completely differently:
00101   /// certain lookups merely "ignore" certain kinds of declarations,
00102   /// usually based on whether the declaration is of a type, etc.
00103   ///
00104   /// These are meant as bitmasks, so that searches in
00105   /// C++ can look into the "tag" namespace during ordinary lookup.
00106   ///
00107   /// Decl currently provides 15 bits of IDNS bits.
00108   enum IdentifierNamespace {
00109     /// Labels, declared with 'x:' and referenced with 'goto x'.
00110     IDNS_Label               = 0x0001,
00111 
00112     /// Tags, declared with 'struct foo;' and referenced with
00113     /// 'struct foo'.  All tags are also types.  This is what
00114     /// elaborated-type-specifiers look for in C.
00115     IDNS_Tag                 = 0x0002,
00116 
00117     /// Types, declared with 'struct foo', typedefs, etc.
00118     /// This is what elaborated-type-specifiers look for in C++,
00119     /// but note that it's ill-formed to find a non-tag.
00120     IDNS_Type                = 0x0004,
00121 
00122     /// Members, declared with object declarations within tag
00123     /// definitions.  In C, these can only be found by "qualified"
00124     /// lookup in member expressions.  In C++, they're found by
00125     /// normal lookup.
00126     IDNS_Member              = 0x0008,
00127 
00128     /// Namespaces, declared with 'namespace foo {}'.
00129     /// Lookup for nested-name-specifiers find these.
00130     IDNS_Namespace           = 0x0010,
00131 
00132     /// Ordinary names.  In C, everything that's not a label, tag,
00133     /// or member ends up here.
00134     IDNS_Ordinary            = 0x0020,
00135 
00136     /// Objective C @protocol.
00137     IDNS_ObjCProtocol        = 0x0040,
00138 
00139     /// This declaration is a friend function.  A friend function
00140     /// declaration is always in this namespace but may also be in
00141     /// IDNS_Ordinary if it was previously declared.
00142     IDNS_OrdinaryFriend      = 0x0080,
00143 
00144     /// This declaration is a friend class.  A friend class
00145     /// declaration is always in this namespace but may also be in
00146     /// IDNS_Tag|IDNS_Type if it was previously declared.
00147     IDNS_TagFriend           = 0x0100,
00148 
00149     /// This declaration is a using declaration.  A using declaration
00150     /// *introduces* a number of other declarations into the current
00151     /// scope, and those declarations use the IDNS of their targets,
00152     /// but the actual using declarations go in this namespace.
00153     IDNS_Using               = 0x0200,
00154 
00155     /// This declaration is a C++ operator declared in a non-class
00156     /// context.  All such operators are also in IDNS_Ordinary.
00157     /// C++ lexical operator lookup looks for these.
00158     IDNS_NonMemberOperator   = 0x0400
00159   };
00160 
00161   /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
00162   /// parameter types in method declarations.  Other than remembering
00163   /// them and mangling them into the method's signature string, these
00164   /// are ignored by the compiler; they are consumed by certain
00165   /// remote-messaging frameworks.
00166   ///
00167   /// in, inout, and out are mutually exclusive and apply only to
00168   /// method parameters.  bycopy and byref are mutually exclusive and
00169   /// apply only to method parameters (?).  oneway applies only to
00170   /// results.  All of these expect their corresponding parameter to
00171   /// have a particular type.  None of this is currently enforced by
00172   /// clang.
00173   ///
00174   /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
00175   enum ObjCDeclQualifier {
00176     OBJC_TQ_None = 0x0,
00177     OBJC_TQ_In = 0x1,
00178     OBJC_TQ_Inout = 0x2,
00179     OBJC_TQ_Out = 0x4,
00180     OBJC_TQ_Bycopy = 0x8,
00181     OBJC_TQ_Byref = 0x10,
00182     OBJC_TQ_Oneway = 0x20
00183   };
00184 
00185 protected:
00186   // Enumeration values used in the bits stored in NextInContextAndBits.
00187   enum {
00188     /// \brief Whether this declaration is a top-level declaration (function,
00189     /// global variable, etc.) that is lexically inside an objc container
00190     /// definition.
00191     TopLevelDeclInObjCContainerFlag = 0x01,
00192     
00193     /// \brief Whether this declaration is private to the module in which it was
00194     /// defined.
00195     ModulePrivateFlag = 0x02
00196   };
00197   
00198   /// \brief The next declaration within the same lexical
00199   /// DeclContext. These pointers form the linked list that is
00200   /// traversed via DeclContext's decls_begin()/decls_end().
00201   ///
00202   /// The extra two bits are used for the TopLevelDeclInObjCContainer and
00203   /// ModulePrivate bits.
00204   llvm::PointerIntPair<Decl *, 2, unsigned> NextInContextAndBits;
00205 
00206 private:
00207   friend class DeclContext;
00208 
00209   struct MultipleDC {
00210     DeclContext *SemanticDC;
00211     DeclContext *LexicalDC;
00212   };
00213 
00214 
00215   /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
00216   /// For declarations that don't contain C++ scope specifiers, it contains
00217   /// the DeclContext where the Decl was declared.
00218   /// For declarations with C++ scope specifiers, it contains a MultipleDC*
00219   /// with the context where it semantically belongs (SemanticDC) and the
00220   /// context where it was lexically declared (LexicalDC).
00221   /// e.g.:
00222   ///
00223   ///   namespace A {
00224   ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
00225   ///   }
00226   ///   void A::f(); // SemanticDC == namespace 'A'
00227   ///                // LexicalDC == global namespace
00228   llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
00229 
00230   inline bool isInSemaDC() const    { return DeclCtx.is<DeclContext*>(); }
00231   inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
00232   inline MultipleDC *getMultipleDC() const {
00233     return DeclCtx.get<MultipleDC*>();
00234   }
00235   inline DeclContext *getSemanticDC() const {
00236     return DeclCtx.get<DeclContext*>();
00237   }
00238 
00239   /// Loc - The location of this decl.
00240   SourceLocation Loc;
00241 
00242   /// DeclKind - This indicates which class this is.
00243   unsigned DeclKind : 8;
00244 
00245   /// InvalidDecl - This indicates a semantic error occurred.
00246   unsigned InvalidDecl :  1;
00247 
00248   /// HasAttrs - This indicates whether the decl has attributes or not.
00249   unsigned HasAttrs : 1;
00250 
00251   /// Implicit - Whether this declaration was implicitly generated by
00252   /// the implementation rather than explicitly written by the user.
00253   unsigned Implicit : 1;
00254 
00255   /// \brief Whether this declaration was "used", meaning that a definition is
00256   /// required.
00257   unsigned Used : 1;
00258 
00259   /// \brief Whether this declaration was "referenced".
00260   /// The difference with 'Used' is whether the reference appears in a
00261   /// evaluated context or not, e.g. functions used in uninstantiated templates
00262   /// are regarded as "referenced" but not "used".
00263   unsigned Referenced : 1;
00264 
00265   /// \brief Whether statistic collection is enabled.
00266   static bool StatisticsEnabled;
00267 
00268 protected:
00269   /// Access - Used by C++ decls for the access specifier.
00270   // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
00271   unsigned Access : 2;
00272   friend class CXXClassMemberWrapper;
00273 
00274   /// \brief Whether this declaration was loaded from an AST file.
00275   unsigned FromASTFile : 1;
00276 
00277   /// \brief Whether this declaration is hidden from normal name lookup, e.g.,
00278   /// because it is was loaded from an AST file is either module-private or
00279   /// because its submodule has not been made visible.
00280   unsigned Hidden : 1;
00281   
00282   /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
00283   unsigned IdentifierNamespace : 12;
00284 
00285   /// \brief Whether the \c CachedLinkage field is active.
00286   ///
00287   /// This field is only valid for NamedDecls subclasses.
00288   mutable unsigned HasCachedLinkage : 1;
00289 
00290   /// \brief If \c HasCachedLinkage, the linkage of this declaration.
00291   ///
00292   /// This field is only valid for NamedDecls subclasses.
00293   mutable unsigned CachedLinkage : 2;
00294 
00295   friend class ASTDeclWriter;
00296   friend class ASTDeclReader;
00297   friend class ASTReader;
00298 
00299 private:
00300   void CheckAccessDeclContext() const;
00301 
00302 protected:
00303 
00304   Decl(Kind DK, DeclContext *DC, SourceLocation L)
00305     : NextInContextAndBits(), DeclCtx(DC),
00306       Loc(L), DeclKind(DK), InvalidDecl(0),
00307       HasAttrs(false), Implicit(false), Used(false), Referenced(false),
00308       Access(AS_none), FromASTFile(0), Hidden(0),
00309       IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
00310       HasCachedLinkage(0)
00311   {
00312     if (StatisticsEnabled) add(DK);
00313   }
00314 
00315   Decl(Kind DK, EmptyShell Empty)
00316     : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0),
00317       HasAttrs(false), Implicit(false), Used(false), Referenced(false),
00318       Access(AS_none), FromASTFile(0), Hidden(0),
00319       IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
00320       HasCachedLinkage(0)
00321   {
00322     if (StatisticsEnabled) add(DK);
00323   }
00324 
00325   virtual ~Decl();
00326 
00327   /// \brief Allocate memory for a deserialized declaration.
00328   ///
00329   /// This routine must be used to allocate memory for any declaration that is
00330   /// deserialized from a module file.
00331   ///
00332   /// \param Context The context in which we will allocate memory.
00333   /// \param ID The global ID of the deserialized declaration.
00334   /// \param Size The size of the allocated object.
00335   static void *AllocateDeserializedDecl(const ASTContext &Context,
00336                                         unsigned ID,
00337                                         unsigned Size);
00338   
00339 public:
00340 
00341   /// \brief Source range that this declaration covers.
00342   virtual SourceRange getSourceRange() const LLVM_READONLY {
00343     return SourceRange(getLocation(), getLocation());
00344   }
00345   SourceLocation getLocStart() const LLVM_READONLY {
00346     return getSourceRange().getBegin();
00347   }
00348   SourceLocation getLocEnd() const LLVM_READONLY {
00349     return getSourceRange().getEnd();
00350   }
00351 
00352   SourceLocation getLocation() const { return Loc; }
00353   void setLocation(SourceLocation L) { Loc = L; }
00354 
00355   Kind getKind() const { return static_cast<Kind>(DeclKind); }
00356   const char *getDeclKindName() const;
00357 
00358   Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
00359   const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
00360 
00361   DeclContext *getDeclContext() {
00362     if (isInSemaDC())
00363       return getSemanticDC();
00364     return getMultipleDC()->SemanticDC;
00365   }
00366   const DeclContext *getDeclContext() const {
00367     return const_cast<Decl*>(this)->getDeclContext();
00368   }
00369 
00370   /// Finds the innermost non-closure context of this declaration.
00371   /// That is, walk out the DeclContext chain, skipping any blocks.
00372   DeclContext *getNonClosureContext();
00373   const DeclContext *getNonClosureContext() const {
00374     return const_cast<Decl*>(this)->getNonClosureContext();
00375   }
00376 
00377   TranslationUnitDecl *getTranslationUnitDecl();
00378   const TranslationUnitDecl *getTranslationUnitDecl() const {
00379     return const_cast<Decl*>(this)->getTranslationUnitDecl();
00380   }
00381 
00382   bool isInAnonymousNamespace() const;
00383 
00384   ASTContext &getASTContext() const LLVM_READONLY;
00385 
00386   void setAccess(AccessSpecifier AS) {
00387     Access = AS;
00388 #ifndef NDEBUG
00389     CheckAccessDeclContext();
00390 #endif
00391   }
00392 
00393   AccessSpecifier getAccess() const {
00394 #ifndef NDEBUG
00395     CheckAccessDeclContext();
00396 #endif
00397     return AccessSpecifier(Access);
00398   }
00399 
00400   bool hasAttrs() const { return HasAttrs; }
00401   void setAttrs(const AttrVec& Attrs) {
00402     return setAttrsImpl(Attrs, getASTContext());
00403   }
00404   AttrVec &getAttrs() {
00405     return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
00406   }
00407   const AttrVec &getAttrs() const;
00408   void swapAttrs(Decl *D);
00409   void dropAttrs();
00410 
00411   void addAttr(Attr *A) {
00412     if (hasAttrs())
00413       getAttrs().push_back(A);
00414     else
00415       setAttrs(AttrVec(1, A));
00416   }
00417 
00418   typedef AttrVec::const_iterator attr_iterator;
00419 
00420   // FIXME: Do not rely on iterators having comparable singular values.
00421   //        Note that this should error out if they do not.
00422   attr_iterator attr_begin() const {
00423     return hasAttrs() ? getAttrs().begin() : 0;
00424   }
00425   attr_iterator attr_end() const {
00426     return hasAttrs() ? getAttrs().end() : 0;
00427   }
00428 
00429   template <typename T>
00430   void dropAttr() {
00431     if (!HasAttrs) return;
00432 
00433     AttrVec &Attrs = getAttrs();
00434     for (unsigned i = 0, e = Attrs.size(); i != e; /* in loop */) {
00435       if (isa<T>(Attrs[i])) {
00436         Attrs.erase(Attrs.begin() + i);
00437         --e;
00438       }
00439       else
00440         ++i;
00441     }
00442     if (Attrs.empty())
00443       HasAttrs = false;
00444   }
00445 
00446   template <typename T>
00447   specific_attr_iterator<T> specific_attr_begin() const {
00448     return specific_attr_iterator<T>(attr_begin());
00449   }
00450   template <typename T>
00451   specific_attr_iterator<T> specific_attr_end() const {
00452     return specific_attr_iterator<T>(attr_end());
00453   }
00454 
00455   template<typename T> T *getAttr() const {
00456     return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : 0;
00457   }
00458   template<typename T> bool hasAttr() const {
00459     return hasAttrs() && hasSpecificAttr<T>(getAttrs());
00460   }
00461 
00462   /// getMaxAlignment - return the maximum alignment specified by attributes
00463   /// on this decl, 0 if there are none.
00464   unsigned getMaxAlignment() const {
00465     return hasAttrs() ? getMaxAttrAlignment(getAttrs(), getASTContext()) : 0;
00466   }
00467 
00468   /// setInvalidDecl - Indicates the Decl had a semantic error. This
00469   /// allows for graceful error recovery.
00470   void setInvalidDecl(bool Invalid = true);
00471   bool isInvalidDecl() const { return (bool) InvalidDecl; }
00472 
00473   /// isImplicit - Indicates whether the declaration was implicitly
00474   /// generated by the implementation. If false, this declaration
00475   /// was written explicitly in the source code.
00476   bool isImplicit() const { return Implicit; }
00477   void setImplicit(bool I = true) { Implicit = I; }
00478 
00479   /// \brief Whether this declaration was used, meaning that a definition
00480   /// is required.
00481   ///
00482   /// \param CheckUsedAttr When true, also consider the "used" attribute
00483   /// (in addition to the "used" bit set by \c setUsed()) when determining
00484   /// whether the function is used.
00485   bool isUsed(bool CheckUsedAttr = true) const;
00486 
00487   void setUsed(bool U = true) { Used = U; }
00488 
00489   /// \brief Whether this declaration was referenced.
00490   bool isReferenced() const;
00491 
00492   void setReferenced(bool R = true) { Referenced = R; }
00493 
00494   /// \brief Whether this declaration is a top-level declaration (function,
00495   /// global variable, etc.) that is lexically inside an objc container
00496   /// definition.
00497   bool isTopLevelDeclInObjCContainer() const {
00498     return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag;
00499   }
00500 
00501   void setTopLevelDeclInObjCContainer(bool V = true) {
00502     unsigned Bits = NextInContextAndBits.getInt();
00503     if (V)
00504       Bits |= TopLevelDeclInObjCContainerFlag;
00505     else
00506       Bits &= ~TopLevelDeclInObjCContainerFlag;
00507     NextInContextAndBits.setInt(Bits);
00508   }
00509 
00510 protected:
00511   /// \brief Whether this declaration was marked as being private to the
00512   /// module in which it was defined.
00513   bool isModulePrivate() const { 
00514     return NextInContextAndBits.getInt() & ModulePrivateFlag;
00515   }
00516   
00517   /// \brief Specify whether this declaration was marked as being private
00518   /// to the module in which it was defined.
00519   void setModulePrivate(bool MP = true) {
00520     unsigned Bits = NextInContextAndBits.getInt();
00521     if (MP)
00522       Bits |= ModulePrivateFlag;
00523     else
00524       Bits &= ~ModulePrivateFlag;
00525     NextInContextAndBits.setInt(Bits);
00526   }
00527 
00528   /// \brief Set the owning module ID.
00529   void setOwningModuleID(unsigned ID) {
00530     assert(isFromASTFile() && "Only works on a deserialized declaration");
00531     *((unsigned*)this - 2) = ID;
00532   }
00533   
00534 public:
00535   
00536   /// \brief Determine the availability of the given declaration.
00537   ///
00538   /// This routine will determine the most restrictive availability of
00539   /// the given declaration (e.g., preferring 'unavailable' to
00540   /// 'deprecated').
00541   ///
00542   /// \param Message If non-NULL and the result is not \c
00543   /// AR_Available, will be set to a (possibly empty) message
00544   /// describing why the declaration has not been introduced, is
00545   /// deprecated, or is unavailable.
00546   AvailabilityResult getAvailability(std::string *Message = 0) const;
00547 
00548   /// \brief Determine whether this declaration is marked 'deprecated'.
00549   ///
00550   /// \param Message If non-NULL and the declaration is deprecated,
00551   /// this will be set to the message describing why the declaration
00552   /// was deprecated (which may be empty).
00553   bool isDeprecated(std::string *Message = 0) const {
00554     return getAvailability(Message) == AR_Deprecated;
00555   }
00556 
00557   /// \brief Determine whether this declaration is marked 'unavailable'.
00558   ///
00559   /// \param Message If non-NULL and the declaration is unavailable,
00560   /// this will be set to the message describing why the declaration
00561   /// was made unavailable (which may be empty).
00562   bool isUnavailable(std::string *Message = 0) const {
00563     return getAvailability(Message) == AR_Unavailable;
00564   }
00565 
00566   /// \brief Determine whether this is a weak-imported symbol.
00567   ///
00568   /// Weak-imported symbols are typically marked with the
00569   /// 'weak_import' attribute, but may also be marked with an
00570   /// 'availability' attribute where we're targing a platform prior to
00571   /// the introduction of this feature.
00572   bool isWeakImported() const;
00573 
00574   /// \brief Determines whether this symbol can be weak-imported,
00575   /// e.g., whether it would be well-formed to add the weak_import
00576   /// attribute.
00577   ///
00578   /// \param IsDefinition Set to \c true to indicate that this
00579   /// declaration cannot be weak-imported because it has a definition.
00580   bool canBeWeakImported(bool &IsDefinition) const;
00581 
00582   /// \brief Determine whether this declaration came from an AST file (such as
00583   /// a precompiled header or module) rather than having been parsed.
00584   bool isFromASTFile() const { return FromASTFile; }
00585 
00586   /// \brief Retrieve the global declaration ID associated with this 
00587   /// declaration, which specifies where in the 
00588   unsigned getGlobalID() const { 
00589     if (isFromASTFile())
00590       return *((const unsigned*)this - 1);
00591     return 0;
00592   }
00593   
00594   /// \brief Retrieve the global ID of the module that owns this particular
00595   /// declaration.
00596   unsigned getOwningModuleID() const {
00597     if (isFromASTFile())
00598       return *((const unsigned*)this - 2);
00599     
00600     return 0;
00601   }
00602   
00603   unsigned getIdentifierNamespace() const {
00604     return IdentifierNamespace;
00605   }
00606   bool isInIdentifierNamespace(unsigned NS) const {
00607     return getIdentifierNamespace() & NS;
00608   }
00609   static unsigned getIdentifierNamespaceForKind(Kind DK);
00610 
00611   bool hasTagIdentifierNamespace() const {
00612     return isTagIdentifierNamespace(getIdentifierNamespace());
00613   }
00614   static bool isTagIdentifierNamespace(unsigned NS) {
00615     // TagDecls have Tag and Type set and may also have TagFriend.
00616     return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
00617   }
00618 
00619   /// getLexicalDeclContext - The declaration context where this Decl was
00620   /// lexically declared (LexicalDC). May be different from
00621   /// getDeclContext() (SemanticDC).
00622   /// e.g.:
00623   ///
00624   ///   namespace A {
00625   ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
00626   ///   }
00627   ///   void A::f(); // SemanticDC == namespace 'A'
00628   ///                // LexicalDC == global namespace
00629   DeclContext *getLexicalDeclContext() {
00630     if (isInSemaDC())
00631       return getSemanticDC();
00632     return getMultipleDC()->LexicalDC;
00633   }
00634   const DeclContext *getLexicalDeclContext() const {
00635     return const_cast<Decl*>(this)->getLexicalDeclContext();
00636   }
00637 
00638   virtual bool isOutOfLine() const {
00639     return getLexicalDeclContext() != getDeclContext();
00640   }
00641 
00642   /// setDeclContext - Set both the semantic and lexical DeclContext
00643   /// to DC.
00644   void setDeclContext(DeclContext *DC);
00645 
00646   void setLexicalDeclContext(DeclContext *DC);
00647 
00648   /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
00649   /// scoped decl is defined outside the current function or method.  This is
00650   /// roughly global variables and functions, but also handles enums (which
00651   /// could be defined inside or outside a function etc).
00652   bool isDefinedOutsideFunctionOrMethod() const {
00653     return getParentFunctionOrMethod() == 0;
00654   }
00655 
00656   /// \brief If this decl is defined inside a function/method/block it returns
00657   /// the corresponding DeclContext, otherwise it returns null.
00658   const DeclContext *getParentFunctionOrMethod() const;
00659   DeclContext *getParentFunctionOrMethod() {
00660     return const_cast<DeclContext*>(
00661                     const_cast<const Decl*>(this)->getParentFunctionOrMethod());
00662   }
00663 
00664   /// \brief Retrieves the "canonical" declaration of the given declaration.
00665   virtual Decl *getCanonicalDecl() { return this; }
00666   const Decl *getCanonicalDecl() const {
00667     return const_cast<Decl*>(this)->getCanonicalDecl();
00668   }
00669 
00670   /// \brief Whether this particular Decl is a canonical one.
00671   bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
00672   
00673 protected:
00674   /// \brief Returns the next redeclaration or itself if this is the only decl.
00675   ///
00676   /// Decl subclasses that can be redeclared should override this method so that
00677   /// Decl::redecl_iterator can iterate over them.
00678   virtual Decl *getNextRedeclaration() { return this; }
00679 
00680   /// \brief Implementation of getPreviousDecl(), to be overridden by any
00681   /// subclass that has a redeclaration chain.
00682   virtual Decl *getPreviousDeclImpl() { return 0; }
00683   
00684   /// \brief Implementation of getMostRecentDecl(), to be overridden by any
00685   /// subclass that has a redeclaration chain.  
00686   virtual Decl *getMostRecentDeclImpl() { return this; }
00687   
00688 public:
00689   /// \brief Iterates through all the redeclarations of the same decl.
00690   class redecl_iterator {
00691     /// Current - The current declaration.
00692     Decl *Current;
00693     Decl *Starter;
00694 
00695   public:
00696     typedef Decl                     value_type;
00697     typedef value_type&              reference;
00698     typedef value_type*              pointer;
00699     typedef std::forward_iterator_tag iterator_category;
00700     typedef std::ptrdiff_t            difference_type;
00701 
00702     redecl_iterator() : Current(0) { }
00703     explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
00704 
00705     reference operator*() const { return *Current; }
00706     pointer operator->() const { return Current; }
00707     operator pointer() const { return Current; }
00708 
00709     redecl_iterator& operator++() {
00710       assert(Current && "Advancing while iterator has reached end");
00711       // Get either previous decl or latest decl.
00712       Decl *Next = Current->getNextRedeclaration();
00713       assert(Next && "Should return next redeclaration or itself, never null!");
00714       Current = (Next != Starter ? Next : 0);
00715       return *this;
00716     }
00717 
00718     redecl_iterator operator++(int) {
00719       redecl_iterator tmp(*this);
00720       ++(*this);
00721       return tmp;
00722     }
00723 
00724     friend bool operator==(redecl_iterator x, redecl_iterator y) {
00725       return x.Current == y.Current;
00726     }
00727     friend bool operator!=(redecl_iterator x, redecl_iterator y) {
00728       return x.Current != y.Current;
00729     }
00730   };
00731 
00732   /// \brief Returns iterator for all the redeclarations of the same decl.
00733   /// It will iterate at least once (when this decl is the only one).
00734   redecl_iterator redecls_begin() const {
00735     return redecl_iterator(const_cast<Decl*>(this));
00736   }
00737   redecl_iterator redecls_end() const { return redecl_iterator(); }
00738 
00739   /// \brief Retrieve the previous declaration that declares the same entity
00740   /// as this declaration, or NULL if there is no previous declaration.
00741   Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
00742   
00743   /// \brief Retrieve the most recent declaration that declares the same entity
00744   /// as this declaration, or NULL if there is no previous declaration.
00745   const Decl *getPreviousDecl() const { 
00746     return const_cast<Decl *>(this)->getPreviousDeclImpl();
00747   }
00748   
00749   /// \brief Retrieve the most recent declaration that declares the same entity
00750   /// as this declaration (which may be this declaration).
00751   Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
00752 
00753   /// \brief Retrieve the most recent declaration that declares the same entity
00754   /// as this declaration (which may be this declaration).
00755   const Decl *getMostRecentDecl() const { 
00756     return const_cast<Decl *>(this)->getMostRecentDeclImpl();
00757   }
00758 
00759   /// getBody - If this Decl represents a declaration for a body of code,
00760   ///  such as a function or method definition, this method returns the
00761   ///  top-level Stmt* of that body.  Otherwise this method returns null.
00762   virtual Stmt* getBody() const { return 0; }
00763 
00764   /// \brief Returns true if this Decl represents a declaration for a body of
00765   /// code, such as a function or method definition.
00766   virtual bool hasBody() const { return getBody() != 0; }
00767 
00768   /// getBodyRBrace - Gets the right brace of the body, if a body exists.
00769   /// This works whether the body is a CompoundStmt or a CXXTryStmt.
00770   SourceLocation getBodyRBrace() const;
00771 
00772   // global temp stats (until we have a per-module visitor)
00773   static void add(Kind k);
00774   static void EnableStatistics();
00775   static void PrintStats();
00776 
00777   /// isTemplateParameter - Determines whether this declaration is a
00778   /// template parameter.
00779   bool isTemplateParameter() const;
00780 
00781   /// isTemplateParameter - Determines whether this declaration is a
00782   /// template parameter pack.
00783   bool isTemplateParameterPack() const;
00784 
00785   /// \brief Whether this declaration is a parameter pack.
00786   bool isParameterPack() const;
00787 
00788   /// \brief returns true if this declaration is a template
00789   bool isTemplateDecl() const;
00790 
00791   /// \brief Whether this declaration is a function or function template.
00792   bool isFunctionOrFunctionTemplate() const;
00793 
00794   /// \brief Changes the namespace of this declaration to reflect that it's
00795   /// the object of a friend declaration.
00796   ///
00797   /// These declarations appear in the lexical context of the friending
00798   /// class, but in the semantic context of the actual entity.  This property
00799   /// applies only to a specific decl object;  other redeclarations of the
00800   /// same entity may not (and probably don't) share this property.
00801   void setObjectOfFriendDecl(bool PreviouslyDeclared) {
00802     unsigned OldNS = IdentifierNamespace;
00803     assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
00804                      IDNS_TagFriend | IDNS_OrdinaryFriend)) &&
00805            "namespace includes neither ordinary nor tag");
00806     assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
00807                        IDNS_TagFriend | IDNS_OrdinaryFriend)) &&
00808            "namespace includes other than ordinary or tag");
00809 
00810     IdentifierNamespace = 0;
00811     if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
00812       IdentifierNamespace |= IDNS_TagFriend;
00813       if (PreviouslyDeclared) IdentifierNamespace |= IDNS_Tag | IDNS_Type;
00814     }
00815 
00816     if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend)) {
00817       IdentifierNamespace |= IDNS_OrdinaryFriend;
00818       if (PreviouslyDeclared) IdentifierNamespace |= IDNS_Ordinary;
00819     }
00820   }
00821 
00822   enum FriendObjectKind {
00823     FOK_None, // not a friend object
00824     FOK_Declared, // a friend of a previously-declared entity
00825     FOK_Undeclared // a friend of a previously-undeclared entity
00826   };
00827 
00828   /// \brief Determines whether this declaration is the object of a
00829   /// friend declaration and, if so, what kind.
00830   ///
00831   /// There is currently no direct way to find the associated FriendDecl.
00832   FriendObjectKind getFriendObjectKind() const {
00833     unsigned mask
00834       = (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
00835     if (!mask) return FOK_None;
00836     return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ?
00837               FOK_Declared : FOK_Undeclared);
00838   }
00839 
00840   /// Specifies that this declaration is a C++ overloaded non-member.
00841   void setNonMemberOperator() {
00842     assert(getKind() == Function || getKind() == FunctionTemplate);
00843     assert((IdentifierNamespace & IDNS_Ordinary) &&
00844            "visible non-member operators should be in ordinary namespace");
00845     IdentifierNamespace |= IDNS_NonMemberOperator;
00846   }
00847 
00848   // Implement isa/cast/dyncast/etc.
00849   static bool classof(const Decl *) { return true; }
00850   static bool classofKind(Kind K) { return true; }
00851   static DeclContext *castToDeclContext(const Decl *);
00852   static Decl *castFromDeclContext(const DeclContext *);
00853 
00854   void print(raw_ostream &Out, unsigned Indentation = 0,
00855              bool PrintInstantiation = false) const;
00856   void print(raw_ostream &Out, const PrintingPolicy &Policy,
00857              unsigned Indentation = 0, bool PrintInstantiation = false) const;
00858   static void printGroup(Decl** Begin, unsigned NumDecls,
00859                          raw_ostream &Out, const PrintingPolicy &Policy,
00860                          unsigned Indentation = 0);
00861   LLVM_ATTRIBUTE_USED void dump() const;
00862   LLVM_ATTRIBUTE_USED void dumpXML() const;
00863   void dumpXML(raw_ostream &OS) const;
00864 
00865 private:
00866   void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
00867   void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
00868                            ASTContext &Ctx);
00869 
00870 protected:
00871   ASTMutationListener *getASTMutationListener() const;
00872 };
00873 
00874 /// \brief Determine whether two declarations declare the same entity.
00875 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
00876   if (!D1 || !D2)
00877     return false;
00878   
00879   if (D1 == D2)
00880     return true;
00881   
00882   return D1->getCanonicalDecl() == D2->getCanonicalDecl();
00883 }
00884   
00885 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
00886 /// doing something to a specific decl.
00887 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
00888   const Decl *TheDecl;
00889   SourceLocation Loc;
00890   SourceManager &SM;
00891   const char *Message;
00892 public:
00893   PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
00894                        SourceManager &sm, const char *Msg)
00895   : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
00896 
00897   virtual void print(raw_ostream &OS) const;
00898 };
00899 
00900 class DeclContextLookupResult
00901   : public std::pair<NamedDecl**,NamedDecl**> {
00902 public:
00903   DeclContextLookupResult(NamedDecl **I, NamedDecl **E)
00904     : std::pair<NamedDecl**,NamedDecl**>(I, E) {}
00905   DeclContextLookupResult()
00906     : std::pair<NamedDecl**,NamedDecl**>() {}
00907 
00908   using std::pair<NamedDecl**,NamedDecl**>::operator=;
00909 };
00910 
00911 class DeclContextLookupConstResult
00912   : public std::pair<NamedDecl*const*, NamedDecl*const*> {
00913 public:
00914   DeclContextLookupConstResult(std::pair<NamedDecl**,NamedDecl**> R)
00915     : std::pair<NamedDecl*const*, NamedDecl*const*>(R) {}
00916   DeclContextLookupConstResult(NamedDecl * const *I, NamedDecl * const *E)
00917     : std::pair<NamedDecl*const*, NamedDecl*const*>(I, E) {}
00918   DeclContextLookupConstResult()
00919     : std::pair<NamedDecl*const*, NamedDecl*const*>() {}
00920 
00921   using std::pair<NamedDecl*const*,NamedDecl*const*>::operator=;
00922 };
00923 
00924 /// DeclContext - This is used only as base class of specific decl types that
00925 /// can act as declaration contexts. These decls are (only the top classes
00926 /// that directly derive from DeclContext are mentioned, not their subclasses):
00927 ///
00928 ///   TranslationUnitDecl
00929 ///   NamespaceDecl
00930 ///   FunctionDecl
00931 ///   TagDecl
00932 ///   ObjCMethodDecl
00933 ///   ObjCContainerDecl
00934 ///   LinkageSpecDecl
00935 ///   BlockDecl
00936 ///
00937 class DeclContext {
00938   /// DeclKind - This indicates which class this is.
00939   unsigned DeclKind : 8;
00940 
00941   /// \brief Whether this declaration context also has some external
00942   /// storage that contains additional declarations that are lexically
00943   /// part of this context.
00944   mutable unsigned ExternalLexicalStorage : 1;
00945 
00946   /// \brief Whether this declaration context also has some external
00947   /// storage that contains additional declarations that are visible
00948   /// in this context.
00949   mutable unsigned ExternalVisibleStorage : 1;
00950 
00951   /// \brief Pointer to the data structure used to lookup declarations
00952   /// within this context (or a DependentStoredDeclsMap if this is a
00953   /// dependent context), and a bool indicating whether we have lazily
00954   /// omitted any declarations from the map. We maintain the invariant
00955   /// that, if the map contains an entry for a DeclarationName, then it
00956   /// contains all relevant entries for that name.
00957   mutable llvm::PointerIntPair<StoredDeclsMap*, 1, bool> LookupPtr;
00958 
00959 protected:
00960   /// FirstDecl - The first declaration stored within this declaration
00961   /// context.
00962   mutable Decl *FirstDecl;
00963 
00964   /// LastDecl - The last declaration stored within this declaration
00965   /// context. FIXME: We could probably cache this value somewhere
00966   /// outside of the DeclContext, to reduce the size of DeclContext by
00967   /// another pointer.
00968   mutable Decl *LastDecl;
00969 
00970   friend class ExternalASTSource;
00971   friend class ASTWriter;
00972 
00973   /// \brief Build up a chain of declarations.
00974   ///
00975   /// \returns the first/last pair of declarations.
00976   static std::pair<Decl *, Decl *>
00977   BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
00978 
00979    DeclContext(Decl::Kind K)
00980      : DeclKind(K), ExternalLexicalStorage(false),
00981        ExternalVisibleStorage(false), LookupPtr(0, false), FirstDecl(0),
00982        LastDecl(0) { }
00983 
00984 public:
00985   ~DeclContext();
00986 
00987   Decl::Kind getDeclKind() const {
00988     return static_cast<Decl::Kind>(DeclKind);
00989   }
00990   const char *getDeclKindName() const;
00991 
00992   /// getParent - Returns the containing DeclContext.
00993   DeclContext *getParent() {
00994     return cast<Decl>(this)->getDeclContext();
00995   }
00996   const DeclContext *getParent() const {
00997     return const_cast<DeclContext*>(this)->getParent();
00998   }
00999 
01000   /// getLexicalParent - Returns the containing lexical DeclContext. May be
01001   /// different from getParent, e.g.:
01002   ///
01003   ///   namespace A {
01004   ///      struct S;
01005   ///   }
01006   ///   struct A::S {}; // getParent() == namespace 'A'
01007   ///                   // getLexicalParent() == translation unit
01008   ///
01009   DeclContext *getLexicalParent() {
01010     return cast<Decl>(this)->getLexicalDeclContext();
01011   }
01012   const DeclContext *getLexicalParent() const {
01013     return const_cast<DeclContext*>(this)->getLexicalParent();
01014   }
01015 
01016   DeclContext *getLookupParent();
01017 
01018   const DeclContext *getLookupParent() const {
01019     return const_cast<DeclContext*>(this)->getLookupParent();
01020   }
01021 
01022   ASTContext &getParentASTContext() const {
01023     return cast<Decl>(this)->getASTContext();
01024   }
01025 
01026   bool isClosure() const {
01027     return DeclKind == Decl::Block;
01028   }
01029 
01030   bool isObjCContainer() const {
01031     switch (DeclKind) {
01032         case Decl::ObjCCategory:
01033         case Decl::ObjCCategoryImpl:
01034         case Decl::ObjCImplementation:
01035         case Decl::ObjCInterface:
01036         case Decl::ObjCProtocol:
01037             return true;
01038     }
01039     return false;
01040   }
01041 
01042   bool isFunctionOrMethod() const {
01043     switch (DeclKind) {
01044     case Decl::Block:
01045     case Decl::ObjCMethod:
01046       return true;
01047     default:
01048       return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
01049     }
01050   }
01051 
01052   bool isFileContext() const {
01053     return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
01054   }
01055 
01056   bool isTranslationUnit() const {
01057     return DeclKind == Decl::TranslationUnit;
01058   }
01059 
01060   bool isRecord() const {
01061     return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
01062   }
01063 
01064   bool isNamespace() const {
01065     return DeclKind == Decl::Namespace;
01066   }
01067 
01068   bool isInlineNamespace() const;
01069 
01070   /// \brief Determines whether this context is dependent on a
01071   /// template parameter.
01072   bool isDependentContext() const;
01073 
01074   /// isTransparentContext - Determines whether this context is a
01075   /// "transparent" context, meaning that the members declared in this
01076   /// context are semantically declared in the nearest enclosing
01077   /// non-transparent (opaque) context but are lexically declared in
01078   /// this context. For example, consider the enumerators of an
01079   /// enumeration type:
01080   /// @code
01081   /// enum E {
01082   ///   Val1
01083   /// };
01084   /// @endcode
01085   /// Here, E is a transparent context, so its enumerator (Val1) will
01086   /// appear (semantically) that it is in the same context of E.
01087   /// Examples of transparent contexts include: enumerations (except for
01088   /// C++0x scoped enums), and C++ linkage specifications.
01089   bool isTransparentContext() const;
01090 
01091   /// \brief Determines whether this context is, or is nested within,
01092   /// a C++ extern "C" linkage spec.
01093   bool isExternCContext() const;
01094 
01095   /// \brief Determine whether this declaration context is equivalent
01096   /// to the declaration context DC.
01097   bool Equals(const DeclContext *DC) const {
01098     return DC && this->getPrimaryContext() == DC->getPrimaryContext();
01099   }
01100 
01101   /// \brief Determine whether this declaration context encloses the
01102   /// declaration context DC.
01103   bool Encloses(const DeclContext *DC) const;
01104 
01105   /// \brief Find the nearest non-closure ancestor of this context,
01106   /// i.e. the innermost semantic parent of this context which is not
01107   /// a closure.  A context may be its own non-closure ancestor.
01108   DeclContext *getNonClosureAncestor();
01109   const DeclContext *getNonClosureAncestor() const {
01110     return const_cast<DeclContext*>(this)->getNonClosureAncestor();
01111   }
01112 
01113   /// getPrimaryContext - There may be many different
01114   /// declarations of the same entity (including forward declarations
01115   /// of classes, multiple definitions of namespaces, etc.), each with
01116   /// a different set of declarations. This routine returns the
01117   /// "primary" DeclContext structure, which will contain the
01118   /// information needed to perform name lookup into this context.
01119   DeclContext *getPrimaryContext();
01120   const DeclContext *getPrimaryContext() const {
01121     return const_cast<DeclContext*>(this)->getPrimaryContext();
01122   }
01123 
01124   /// getRedeclContext - Retrieve the context in which an entity conflicts with
01125   /// other entities of the same name, or where it is a redeclaration if the
01126   /// two entities are compatible. This skips through transparent contexts.
01127   DeclContext *getRedeclContext();
01128   const DeclContext *getRedeclContext() const {
01129     return const_cast<DeclContext *>(this)->getRedeclContext();
01130   }
01131 
01132   /// \brief Retrieve the nearest enclosing namespace context.
01133   DeclContext *getEnclosingNamespaceContext();
01134   const DeclContext *getEnclosingNamespaceContext() const {
01135     return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
01136   }
01137 
01138   /// \brief Test if this context is part of the enclosing namespace set of
01139   /// the context NS, as defined in C++0x [namespace.def]p9. If either context
01140   /// isn't a namespace, this is equivalent to Equals().
01141   ///
01142   /// The enclosing namespace set of a namespace is the namespace and, if it is
01143   /// inline, its enclosing namespace, recursively.
01144   bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
01145 
01146   /// \\brief Collects all of the declaration contexts that are semantically
01147   /// connected to this declaration context.
01148   ///
01149   /// For declaration contexts that have multiple semantically connected but
01150   /// syntactically distinct contexts, such as C++ namespaces, this routine 
01151   /// retrieves the complete set of such declaration contexts in source order.
01152   /// For example, given:
01153   ///
01154   /// \code
01155   /// namespace N {
01156   ///   int x;
01157   /// }
01158   /// namespace N {
01159   ///   int y;
01160   /// }
01161   /// \endcode
01162   ///
01163   /// The \c Contexts parameter will contain both definitions of N.
01164   ///
01165   /// \param Contexts Will be cleared and set to the set of declaration
01166   /// contexts that are semanticaly connected to this declaration context,
01167   /// in source order, including this context (which may be the only result,
01168   /// for non-namespace contexts).
01169   void collectAllContexts(llvm::SmallVectorImpl<DeclContext *> &Contexts);
01170 
01171   /// decl_iterator - Iterates through the declarations stored
01172   /// within this context.
01173   class decl_iterator {
01174     /// Current - The current declaration.
01175     Decl *Current;
01176 
01177   public:
01178     typedef Decl*                     value_type;
01179     typedef Decl*                     reference;
01180     typedef Decl*                     pointer;
01181     typedef std::forward_iterator_tag iterator_category;
01182     typedef std::ptrdiff_t            difference_type;
01183 
01184     decl_iterator() : Current(0) { }
01185     explicit decl_iterator(Decl *C) : Current(C) { }
01186 
01187     reference operator*() const { return Current; }
01188     pointer operator->() const { return Current; }
01189 
01190     decl_iterator& operator++() {
01191       Current = Current->getNextDeclInContext();
01192       return *this;
01193     }
01194 
01195     decl_iterator operator++(int) {
01196       decl_iterator tmp(*this);
01197       ++(*this);
01198       return tmp;
01199     }
01200 
01201     friend bool operator==(decl_iterator x, decl_iterator y) {
01202       return x.Current == y.Current;
01203     }
01204     friend bool operator!=(decl_iterator x, decl_iterator y) {
01205       return x.Current != y.Current;
01206     }
01207   };
01208 
01209   /// decls_begin/decls_end - Iterate over the declarations stored in
01210   /// this context.
01211   decl_iterator decls_begin() const;
01212   decl_iterator decls_end() const;
01213   bool decls_empty() const;
01214 
01215   /// noload_decls_begin/end - Iterate over the declarations stored in this
01216   /// context that are currently loaded; don't attempt to retrieve anything
01217   /// from an external source.
01218   decl_iterator noload_decls_begin() const;
01219   decl_iterator noload_decls_end() const;
01220 
01221   /// specific_decl_iterator - Iterates over a subrange of
01222   /// declarations stored in a DeclContext, providing only those that
01223   /// are of type SpecificDecl (or a class derived from it). This
01224   /// iterator is used, for example, to provide iteration over just
01225   /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
01226   template<typename SpecificDecl>
01227   class specific_decl_iterator {
01228     /// Current - The current, underlying declaration iterator, which
01229     /// will either be NULL or will point to a declaration of
01230     /// type SpecificDecl.
01231     DeclContext::decl_iterator Current;
01232 
01233     /// SkipToNextDecl - Advances the current position up to the next
01234     /// declaration of type SpecificDecl that also meets the criteria
01235     /// required by Acceptable.
01236     void SkipToNextDecl() {
01237       while (*Current && !isa<SpecificDecl>(*Current))
01238         ++Current;
01239     }
01240 
01241   public:
01242     typedef SpecificDecl value_type;
01243     typedef SpecificDecl& reference;
01244     typedef SpecificDecl* pointer;
01245     typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
01246       difference_type;
01247     typedef std::forward_iterator_tag iterator_category;
01248 
01249     specific_decl_iterator() : Current() { }
01250 
01251     /// specific_decl_iterator - Construct a new iterator over a
01252     /// subset of the declarations the range [C,
01253     /// end-of-declarations). If A is non-NULL, it is a pointer to a
01254     /// member function of SpecificDecl that should return true for
01255     /// all of the SpecificDecl instances that will be in the subset
01256     /// of iterators. For example, if you want Objective-C instance
01257     /// methods, SpecificDecl will be ObjCMethodDecl and A will be
01258     /// &ObjCMethodDecl::isInstanceMethod.
01259     explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
01260       SkipToNextDecl();
01261     }
01262 
01263     reference operator*() const { return *cast<SpecificDecl>(*Current); }
01264     pointer operator->() const { return &**this; }
01265 
01266     specific_decl_iterator& operator++() {
01267       ++Current;
01268       SkipToNextDecl();
01269       return *this;
01270     }
01271 
01272     specific_decl_iterator operator++(int) {
01273       specific_decl_iterator tmp(*this);
01274       ++(*this);
01275       return tmp;
01276     }
01277 
01278     friend bool operator==(const specific_decl_iterator& x,
01279                            const specific_decl_iterator& y) {
01280       return x.Current == y.Current;
01281     }
01282 
01283     friend bool operator!=(const specific_decl_iterator& x,
01284                            const specific_decl_iterator& y) {
01285       return x.Current != y.Current;
01286     }
01287   };
01288 
01289   /// \brief Iterates over a filtered subrange of declarations stored
01290   /// in a DeclContext.
01291   ///
01292   /// This iterator visits only those declarations that are of type
01293   /// SpecificDecl (or a class derived from it) and that meet some
01294   /// additional run-time criteria. This iterator is used, for
01295   /// example, to provide access to the instance methods within an
01296   /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
01297   /// Acceptable = ObjCMethodDecl::isInstanceMethod).
01298   template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
01299   class filtered_decl_iterator {
01300     /// Current - The current, underlying declaration iterator, which
01301     /// will either be NULL or will point to a declaration of
01302     /// type SpecificDecl.
01303     DeclContext::decl_iterator Current;
01304 
01305     /// SkipToNextDecl - Advances the current position up to the next
01306     /// declaration of type SpecificDecl that also meets the criteria
01307     /// required by Acceptable.
01308     void SkipToNextDecl() {
01309       while (*Current &&
01310              (!isa<SpecificDecl>(*Current) ||
01311               (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
01312         ++Current;
01313     }
01314 
01315   public:
01316     typedef SpecificDecl* value_type;
01317     typedef SpecificDecl* reference;
01318     typedef SpecificDecl* pointer;
01319     typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
01320       difference_type;
01321     typedef std::forward_iterator_tag iterator_category;
01322 
01323     filtered_decl_iterator() : Current() { }
01324 
01325     /// filtered_decl_iterator - Construct a new iterator over a
01326     /// subset of the declarations the range [C,
01327     /// end-of-declarations). If A is non-NULL, it is a pointer to a
01328     /// member function of SpecificDecl that should return true for
01329     /// all of the SpecificDecl instances that will be in the subset
01330     /// of iterators. For example, if you want Objective-C instance
01331     /// methods, SpecificDecl will be ObjCMethodDecl and A will be
01332     /// &ObjCMethodDecl::isInstanceMethod.
01333     explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
01334       SkipToNextDecl();
01335     }
01336 
01337     reference operator*() const { return cast<SpecificDecl>(*Current); }
01338     pointer operator->() const { return cast<SpecificDecl>(*Current); }
01339 
01340     filtered_decl_iterator& operator++() {
01341       ++Current;
01342       SkipToNextDecl();
01343       return *this;
01344     }
01345 
01346     filtered_decl_iterator operator++(int) {
01347       filtered_decl_iterator tmp(*this);
01348       ++(*this);
01349       return tmp;
01350     }
01351 
01352     friend bool operator==(const filtered_decl_iterator& x,
01353                            const filtered_decl_iterator& y) {
01354       return x.Current == y.Current;
01355     }
01356 
01357     friend bool operator!=(const filtered_decl_iterator& x,
01358                            const filtered_decl_iterator& y) {
01359       return x.Current != y.Current;
01360     }
01361   };
01362 
01363   /// @brief Add the declaration D into this context.
01364   ///
01365   /// This routine should be invoked when the declaration D has first
01366   /// been declared, to place D into the context where it was
01367   /// (lexically) defined. Every declaration must be added to one
01368   /// (and only one!) context, where it can be visited via
01369   /// [decls_begin(), decls_end()). Once a declaration has been added
01370   /// to its lexical context, the corresponding DeclContext owns the
01371   /// declaration.
01372   ///
01373   /// If D is also a NamedDecl, it will be made visible within its
01374   /// semantic context via makeDeclVisibleInContext.
01375   void addDecl(Decl *D);
01376 
01377   /// @brief Add the declaration D into this context, but suppress
01378   /// searches for external declarations with the same name.
01379   ///
01380   /// Although analogous in function to addDecl, this removes an
01381   /// important check.  This is only useful if the Decl is being
01382   /// added in response to an external search; in all other cases,
01383   /// addDecl() is the right function to use.
01384   /// See the ASTImporter for use cases.
01385   void addDeclInternal(Decl *D);
01386 
01387   /// @brief Add the declaration D to this context without modifying
01388   /// any lookup tables.
01389   ///
01390   /// This is useful for some operations in dependent contexts where
01391   /// the semantic context might not be dependent;  this basically
01392   /// only happens with friends.
01393   void addHiddenDecl(Decl *D);
01394 
01395   /// @brief Removes a declaration from this context.
01396   void removeDecl(Decl *D);
01397 
01398   /// lookup_iterator - An iterator that provides access to the results
01399   /// of looking up a name within this context.
01400   typedef NamedDecl **lookup_iterator;
01401 
01402   /// lookup_const_iterator - An iterator that provides non-mutable
01403   /// access to the results of lookup up a name within this context.
01404   typedef NamedDecl * const * lookup_const_iterator;
01405 
01406   typedef DeclContextLookupResult lookup_result;
01407   typedef DeclContextLookupConstResult lookup_const_result;
01408 
01409   /// lookup - Find the declarations (if any) with the given Name in
01410   /// this context. Returns a range of iterators that contains all of
01411   /// the declarations with this name, with object, function, member,
01412   /// and enumerator names preceding any tag name. Note that this
01413   /// routine will not look into parent contexts.
01414   lookup_result lookup(DeclarationName Name);
01415   lookup_const_result lookup(DeclarationName Name) const {
01416     return const_cast<DeclContext*>(this)->lookup(Name);
01417   }
01418 
01419   /// \brief A simplistic name lookup mechanism that performs name lookup
01420   /// into this declaration context without consulting the external source.
01421   ///
01422   /// This function should almost never be used, because it subverts the
01423   /// usual relationship between a DeclContext and the external source.
01424   /// See the ASTImporter for the (few, but important) use cases.
01425   void localUncachedLookup(DeclarationName Name,
01426                            llvm::SmallVectorImpl<NamedDecl *> &Results);
01427 
01428   /// @brief Makes a declaration visible within this context.
01429   ///
01430   /// This routine makes the declaration D visible to name lookup
01431   /// within this context and, if this is a transparent context,
01432   /// within its parent contexts up to the first enclosing
01433   /// non-transparent context. Making a declaration visible within a
01434   /// context does not transfer ownership of a declaration, and a
01435   /// declaration can be visible in many contexts that aren't its
01436   /// lexical context.
01437   ///
01438   /// If D is a redeclaration of an existing declaration that is
01439   /// visible from this context, as determined by
01440   /// NamedDecl::declarationReplaces, the previous declaration will be
01441   /// replaced with D.
01442   void makeDeclVisibleInContext(NamedDecl *D);
01443 
01444   /// all_lookups_iterator - An iterator that provides a view over the results
01445   /// of looking up every possible name.
01446   class all_lookups_iterator;
01447 
01448   all_lookups_iterator lookups_begin() const;
01449 
01450   all_lookups_iterator lookups_end() const;
01451 
01452   /// udir_iterator - Iterates through the using-directives stored
01453   /// within this context.
01454   typedef UsingDirectiveDecl * const * udir_iterator;
01455 
01456   typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
01457 
01458   udir_iterator_range getUsingDirectives() const;
01459 
01460   udir_iterator using_directives_begin() const {
01461     return getUsingDirectives().first;
01462   }
01463 
01464   udir_iterator using_directives_end() const {
01465     return getUsingDirectives().second;
01466   }
01467 
01468   // These are all defined in DependentDiagnostic.h.
01469   class ddiag_iterator;
01470   inline ddiag_iterator ddiag_begin() const;
01471   inline ddiag_iterator ddiag_end() const;
01472 
01473   // Low-level accessors
01474 
01475   /// \brief Retrieve the internal representation of the lookup structure.
01476   /// This may omit some names if we are lazily building the structure.
01477   StoredDeclsMap *getLookupPtr() const { return LookupPtr.getPointer(); }
01478 
01479   /// \brief Ensure the lookup structure is fully-built and return it.
01480   StoredDeclsMap *buildLookup();
01481 
01482   /// \brief Whether this DeclContext has external storage containing
01483   /// additional declarations that are lexically in this context.
01484   bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
01485 
01486   /// \brief State whether this DeclContext has external storage for
01487   /// declarations lexically in this context.
01488   void setHasExternalLexicalStorage(bool ES = true) {
01489     ExternalLexicalStorage = ES;
01490   }
01491 
01492   /// \brief Whether this DeclContext has external storage containing
01493   /// additional declarations that are visible in this context.
01494   bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
01495 
01496   /// \brief State whether this DeclContext has external storage for
01497   /// declarations visible in this context.
01498   void setHasExternalVisibleStorage(bool ES = true) {
01499     ExternalVisibleStorage = ES;
01500   }
01501 
01502   /// \brief Determine whether the given declaration is stored in the list of
01503   /// declarations lexically within this context.
01504   bool isDeclInLexicalTraversal(const Decl *D) const {
01505     return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl || 
01506                  D == LastDecl);
01507   }
01508 
01509   static bool classof(const Decl *D);
01510   static bool classof(const DeclContext *D) { return true; }
01511 #define DECL(NAME, BASE)
01512 #define DECL_CONTEXT(NAME) \
01513   static bool classof(const NAME##Decl *D) { return true; }
01514 #include "clang/AST/DeclNodes.inc"
01515 
01516   LLVM_ATTRIBUTE_USED void dumpDeclContext() const;
01517 
01518 private:
01519   void LoadLexicalDeclsFromExternalStorage() const;
01520 
01521   /// @brief Makes a declaration visible within this context, but
01522   /// suppresses searches for external declarations with the same
01523   /// name.
01524   ///
01525   /// Analogous to makeDeclVisibleInContext, but for the exclusive
01526   /// use of addDeclInternal().
01527   void makeDeclVisibleInContextInternal(NamedDecl *D);
01528 
01529   friend class DependentDiagnostic;
01530   StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
01531 
01532   void buildLookupImpl(DeclContext *DCtx);
01533   void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
01534                                          bool Rediscoverable);
01535   void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
01536 };
01537 
01538 inline bool Decl::isTemplateParameter() const {
01539   return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
01540          getKind() == TemplateTemplateParm;
01541 }
01542 
01543 // Specialization selected when ToTy is not a known subclass of DeclContext.
01544 template <class ToTy,
01545           bool IsKnownSubtype = ::llvm::is_base_of< DeclContext, ToTy>::value>
01546 struct cast_convert_decl_context {
01547   static const ToTy *doit(const DeclContext *Val) {
01548     return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
01549   }
01550 
01551   static ToTy *doit(DeclContext *Val) {
01552     return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
01553   }
01554 };
01555 
01556 // Specialization selected when ToTy is a known subclass of DeclContext.
01557 template <class ToTy>
01558 struct cast_convert_decl_context<ToTy, true> {
01559   static const ToTy *doit(const DeclContext *Val) {
01560     return static_cast<const ToTy*>(Val);
01561   }
01562 
01563   static ToTy *doit(DeclContext *Val) {
01564     return static_cast<ToTy*>(Val);
01565   }
01566 };
01567 
01568 
01569 } // end clang.
01570 
01571 namespace llvm {
01572 
01573 /// isa<T>(DeclContext*)
01574 template <typename To>
01575 struct isa_impl<To, ::clang::DeclContext> {
01576   static bool doit(const ::clang::DeclContext &Val) {
01577     return To::classofKind(Val.getDeclKind());
01578   }
01579 };
01580 
01581 /// cast<T>(DeclContext*)
01582 template<class ToTy>
01583 struct cast_convert_val<ToTy,
01584                         const ::clang::DeclContext,const ::clang::DeclContext> {
01585   static const ToTy &doit(const ::clang::DeclContext &Val) {
01586     return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
01587   }
01588 };
01589 template<class ToTy>
01590 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
01591   static ToTy &doit(::clang::DeclContext &Val) {
01592     return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
01593   }
01594 };
01595 template<class ToTy>
01596 struct cast_convert_val<ToTy,
01597                      const ::clang::DeclContext*, const ::clang::DeclContext*> {
01598   static const ToTy *doit(const ::clang::DeclContext *Val) {
01599     return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
01600   }
01601 };
01602 template<class ToTy>
01603 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
01604   static ToTy *doit(::clang::DeclContext *Val) {
01605     return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
01606   }
01607 };
01608 
01609 /// Implement cast_convert_val for Decl -> DeclContext conversions.
01610 template<class FromTy>
01611 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
01612   static ::clang::DeclContext &doit(const FromTy &Val) {
01613     return *FromTy::castToDeclContext(&Val);
01614   }
01615 };
01616 
01617 template<class FromTy>
01618 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
01619   static ::clang::DeclContext *doit(const FromTy *Val) {
01620     return FromTy::castToDeclContext(Val);
01621   }
01622 };
01623 
01624 template<class FromTy>
01625 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
01626   static const ::clang::DeclContext &doit(const FromTy &Val) {
01627     return *FromTy::castToDeclContext(&Val);
01628   }
01629 };
01630 
01631 template<class FromTy>
01632 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
01633   static const ::clang::DeclContext *doit(const FromTy *Val) {
01634     return FromTy::castToDeclContext(Val);
01635   }
01636 };
01637 
01638 // simplify_type - Allow clients to treat redecl_iterators just like Decl
01639 // pointers when using casting operators.
01640 template<> struct simplify_type< ::clang::Decl::redecl_iterator> {
01641   typedef ::clang::Decl *SimpleType;
01642   static SimpleType getSimplifiedValue(const ::clang::Decl::redecl_iterator
01643       &Val) {
01644     return Val;
01645   }
01646 };
01647 template<> struct simplify_type<const ::clang::Decl::redecl_iterator> {
01648   typedef ::clang::Decl *SimpleType;
01649   static SimpleType getSimplifiedValue(const ::clang::Decl::redecl_iterator
01650       &Val) {
01651     return Val;
01652   }
01653 };
01654 
01655 } // end namespace llvm
01656 
01657 #endif