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