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