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