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