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