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