DeclBase.h revision 3f9a8a60614b763785d54ad08821745d03a4af70
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    IDNS_Friend = 0x80
92  };
93
94  /// ObjCDeclQualifier - Qualifier used on types in method declarations
95  /// for remote messaging. They are meant for the arguments though and
96  /// applied to the Decls (ObjCMethodDecl and ParmVarDecl).
97  enum ObjCDeclQualifier {
98    OBJC_TQ_None = 0x0,
99    OBJC_TQ_In = 0x1,
100    OBJC_TQ_Inout = 0x2,
101    OBJC_TQ_Out = 0x4,
102    OBJC_TQ_Bycopy = 0x8,
103    OBJC_TQ_Byref = 0x10,
104    OBJC_TQ_Oneway = 0x20
105  };
106
107private:
108  /// NextDeclInContext - The next declaration within the same lexical
109  /// DeclContext. These pointers form the linked list that is
110  /// traversed via DeclContext's decls_begin()/decls_end().
111  Decl *NextDeclInContext;
112
113  friend class DeclContext;
114
115  struct MultipleDC {
116    DeclContext *SemanticDC;
117    DeclContext *LexicalDC;
118  };
119
120
121  /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
122  /// For declarations that don't contain C++ scope specifiers, it contains
123  /// the DeclContext where the Decl was declared.
124  /// For declarations with C++ scope specifiers, it contains a MultipleDC*
125  /// with the context where it semantically belongs (SemanticDC) and the
126  /// context where it was lexically declared (LexicalDC).
127  /// e.g.:
128  ///
129  ///   namespace A {
130  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
131  ///   }
132  ///   void A::f(); // SemanticDC == namespace 'A'
133  ///                // LexicalDC == global namespace
134  llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
135
136  inline bool isInSemaDC() const    { return DeclCtx.is<DeclContext*>(); }
137  inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
138  inline MultipleDC *getMultipleDC() const {
139    return DeclCtx.get<MultipleDC*>();
140  }
141  inline DeclContext *getSemanticDC() const {
142    return DeclCtx.get<DeclContext*>();
143  }
144
145  /// Loc - The location that this decl.
146  SourceLocation Loc;
147
148  /// DeclKind - This indicates which class this is.
149  Kind DeclKind   :  8;
150
151  /// InvalidDecl - This indicates a semantic error occurred.
152  unsigned int InvalidDecl :  1;
153
154  /// HasAttrs - This indicates whether the decl has attributes or not.
155  unsigned int HasAttrs : 1;
156
157  /// Implicit - Whether this declaration was implicitly generated by
158  /// the implementation rather than explicitly written by the user.
159  bool Implicit : 1;
160
161  /// \brief Whether this declaration was "used", meaning that a definition is
162  /// required.
163  bool Used : 1;
164
165protected:
166  /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
167  unsigned IdentifierNamespace : 8;
168
169private:
170#ifndef NDEBUG
171  void CheckAccessDeclContext() const;
172#else
173  void CheckAccessDeclContext() const { }
174#endif
175
176protected:
177  /// Access - Used by C++ decls for the access specifier.
178  // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
179  unsigned Access : 2;
180  friend class CXXClassMemberWrapper;
181
182  Decl(Kind DK, DeclContext *DC, SourceLocation L)
183    : NextDeclInContext(0), DeclCtx(DC),
184      Loc(L), DeclKind(DK), InvalidDecl(0),
185      HasAttrs(false), Implicit(false), Used(false),
186      IdentifierNamespace(getIdentifierNamespaceForKind(DK)), Access(AS_none) {
187    if (Decl::CollectingStats()) addDeclKind(DK);
188  }
189
190  virtual ~Decl();
191
192public:
193
194  /// \brief Source range that this declaration covers.
195  virtual SourceRange getSourceRange() const {
196    return SourceRange(getLocation(), getLocation());
197  }
198  SourceLocation getLocStart() const { return getSourceRange().getBegin(); }
199  SourceLocation getLocEnd() const { return getSourceRange().getEnd(); }
200
201  SourceLocation getLocation() const { return Loc; }
202  void setLocation(SourceLocation L) { Loc = L; }
203
204  Kind getKind() const { return DeclKind; }
205  const char *getDeclKindName() const;
206
207  Decl *getNextDeclInContext() { return NextDeclInContext; }
208  const Decl *getNextDeclInContext() const { return NextDeclInContext; }
209
210  DeclContext *getDeclContext() {
211    if (isInSemaDC())
212      return getSemanticDC();
213    return getMultipleDC()->SemanticDC;
214  }
215  const DeclContext *getDeclContext() const {
216    return const_cast<Decl*>(this)->getDeclContext();
217  }
218
219  TranslationUnitDecl *getTranslationUnitDecl();
220  const TranslationUnitDecl *getTranslationUnitDecl() const {
221    return const_cast<Decl*>(this)->getTranslationUnitDecl();
222  }
223
224  ASTContext &getASTContext() const;
225
226  void setAccess(AccessSpecifier AS) {
227    Access = AS;
228    CheckAccessDeclContext();
229  }
230
231  AccessSpecifier getAccess() const {
232    CheckAccessDeclContext();
233    return AccessSpecifier(Access);
234  }
235
236  bool hasAttrs() const { return HasAttrs; }
237  void addAttr(Attr *attr);
238  const Attr *getAttrs() const {
239    if (!HasAttrs) return 0;  // common case, no attributes.
240    return getAttrsImpl();    // Uncommon case, out of line hash lookup.
241  }
242  void swapAttrs(Decl *D);
243  void invalidateAttrs();
244
245  template<typename T> const T *getAttr() const {
246    for (const Attr *attr = getAttrs(); attr; attr = attr->getNext())
247      if (const T *V = dyn_cast<T>(attr))
248        return V;
249    return 0;
250  }
251
252  template<typename T> bool hasAttr() const {
253    return getAttr<T>() != 0;
254  }
255
256  /// setInvalidDecl - Indicates the Decl had a semantic error. This
257  /// allows for graceful error recovery.
258  void setInvalidDecl(bool Invalid = true) { InvalidDecl = Invalid; }
259  bool isInvalidDecl() const { return (bool) InvalidDecl; }
260
261  /// isImplicit - Indicates whether the declaration was implicitly
262  /// generated by the implementation. If false, this declaration
263  /// was written explicitly in the source code.
264  bool isImplicit() const { return Implicit; }
265  void setImplicit(bool I = true) { Implicit = I; }
266
267  /// \brief Whether this declaration was used, meaning that a definition
268  /// is required.
269  bool isUsed() const { return Used; }
270  void setUsed(bool U = true) { Used = U; }
271
272  unsigned getIdentifierNamespace() const {
273    return IdentifierNamespace;
274  }
275  bool isInIdentifierNamespace(unsigned NS) const {
276    return getIdentifierNamespace() & NS;
277  }
278  static unsigned getIdentifierNamespaceForKind(Kind DK);
279
280
281  /// getLexicalDeclContext - The declaration context where this Decl was
282  /// lexically declared (LexicalDC). May be different from
283  /// getDeclContext() (SemanticDC).
284  /// e.g.:
285  ///
286  ///   namespace A {
287  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
288  ///   }
289  ///   void A::f(); // SemanticDC == namespace 'A'
290  ///                // LexicalDC == global namespace
291  DeclContext *getLexicalDeclContext() {
292    if (isInSemaDC())
293      return getSemanticDC();
294    return getMultipleDC()->LexicalDC;
295  }
296  const DeclContext *getLexicalDeclContext() const {
297    return const_cast<Decl*>(this)->getLexicalDeclContext();
298  }
299
300  bool isOutOfLine() const {
301    return getLexicalDeclContext() != getDeclContext();
302  }
303
304  /// setDeclContext - Set both the semantic and lexical DeclContext
305  /// to DC.
306  void setDeclContext(DeclContext *DC);
307
308  void setLexicalDeclContext(DeclContext *DC);
309
310  // isDefinedOutsideFunctionOrMethod - This predicate returns true if this
311  // scoped decl is defined outside the current function or method.  This is
312  // roughly global variables and functions, but also handles enums (which could
313  // be defined inside or outside a function etc).
314  bool isDefinedOutsideFunctionOrMethod() const;
315
316  /// \brief Retrieves the "canonical" declaration of the given declaration.
317  virtual Decl *getCanonicalDecl() { return this; }
318  const Decl *getCanonicalDecl() const {
319    return const_cast<Decl*>(this)->getCanonicalDecl();
320  }
321
322  /// \brief Whether this particular Decl is a canonical one.
323  bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
324
325protected:
326  /// \brief Returns the next redeclaration or itself if this is the only decl.
327  ///
328  /// Decl subclasses that can be redeclared should override this method so that
329  /// Decl::redecl_iterator can iterate over them.
330  virtual Decl *getNextRedeclaration() { return this; }
331
332public:
333  /// \brief Iterates through all the redeclarations of the same decl.
334  class redecl_iterator {
335    /// Current - The current declaration.
336    Decl *Current;
337    Decl *Starter;
338
339  public:
340    typedef Decl*                     value_type;
341    typedef Decl*                     reference;
342    typedef Decl*                     pointer;
343    typedef std::forward_iterator_tag iterator_category;
344    typedef std::ptrdiff_t            difference_type;
345
346    redecl_iterator() : Current(0) { }
347    explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
348
349    reference operator*() const { return Current; }
350    pointer operator->() const { return Current; }
351
352    redecl_iterator& operator++() {
353      assert(Current && "Advancing while iterator has reached end");
354      // Get either previous decl or latest decl.
355      Decl *Next = Current->getNextRedeclaration();
356      assert(Next && "Should return next redeclaration or itself, never null!");
357      Current = (Next != Starter ? Next : 0);
358      return *this;
359    }
360
361    redecl_iterator operator++(int) {
362      redecl_iterator tmp(*this);
363      ++(*this);
364      return tmp;
365    }
366
367    friend bool operator==(redecl_iterator x, redecl_iterator y) {
368      return x.Current == y.Current;
369    }
370    friend bool operator!=(redecl_iterator x, redecl_iterator y) {
371      return x.Current != y.Current;
372    }
373  };
374
375  /// \brief Returns iterator for all the redeclarations of the same decl.
376  /// It will iterate at least once (when this decl is the only one).
377  redecl_iterator redecls_begin() const {
378    return redecl_iterator(const_cast<Decl*>(this));
379  }
380  redecl_iterator redecls_end() const { return redecl_iterator(); }
381
382  /// getBody - If this Decl represents a declaration for a body of code,
383  ///  such as a function or method definition, this method returns the
384  ///  top-level Stmt* of that body.  Otherwise this method returns null.
385  virtual Stmt* getBody() const { return 0; }
386
387  /// getCompoundBody - Returns getBody(), dyn_casted to a CompoundStmt.
388  CompoundStmt* getCompoundBody() const;
389
390  /// getBodyRBrace - Gets the right brace of the body, if a body exists.
391  /// This works whether the body is a CompoundStmt or a CXXTryStmt.
392  SourceLocation getBodyRBrace() const;
393
394  // global temp stats (until we have a per-module visitor)
395  static void addDeclKind(Kind k);
396  static bool CollectingStats(bool Enable = false);
397  static void PrintStats();
398
399  /// isTemplateParameter - Determines whether this declaration is a
400  /// template parameter.
401  bool isTemplateParameter() const;
402
403  /// isTemplateParameter - Determines whether this declaration is a
404  /// template parameter pack.
405  bool isTemplateParameterPack() const;
406
407  /// \brief Whether this declaration is a function or function template.
408  bool isFunctionOrFunctionTemplate() const;
409
410  // Implement isa/cast/dyncast/etc.
411  static bool classof(const Decl *) { return true; }
412  static DeclContext *castToDeclContext(const Decl *);
413  static Decl *castFromDeclContext(const DeclContext *);
414
415  /// Destroy - Call destructors and release memory.
416  virtual void Destroy(ASTContext& C);
417
418  void print(llvm::raw_ostream &Out, unsigned Indentation = 0);
419  void print(llvm::raw_ostream &Out, const PrintingPolicy &Policy,
420             unsigned Indentation = 0);
421  static void printGroup(Decl** Begin, unsigned NumDecls,
422                         llvm::raw_ostream &Out, const PrintingPolicy &Policy,
423                         unsigned Indentation = 0);
424  void dump();
425
426private:
427  const Attr *getAttrsImpl() const;
428
429};
430
431/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
432/// doing something to a specific decl.
433class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
434  Decl *TheDecl;
435  SourceLocation Loc;
436  SourceManager &SM;
437  const char *Message;
438public:
439  PrettyStackTraceDecl(Decl *theDecl, SourceLocation L,
440                       SourceManager &sm, const char *Msg)
441  : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
442
443  virtual void print(llvm::raw_ostream &OS) const;
444};
445
446
447/// DeclContext - This is used only as base class of specific decl types that
448/// can act as declaration contexts. These decls are (only the top classes
449/// that directly derive from DeclContext are mentioned, not their subclasses):
450///
451///   TranslationUnitDecl
452///   NamespaceDecl
453///   FunctionDecl
454///   TagDecl
455///   ObjCMethodDecl
456///   ObjCContainerDecl
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  /// @brief Add the declaration D to this context without modifying
831  /// any lookup tables.
832  ///
833  /// This is useful for some operations in dependent contexts where
834  /// the semantic context might not be dependent;  this basically
835  /// only happens with friends.
836  void addHiddenDecl(Decl *D);
837
838  /// lookup_iterator - An iterator that provides access to the results
839  /// of looking up a name within this context.
840  typedef NamedDecl **lookup_iterator;
841
842  /// lookup_const_iterator - An iterator that provides non-mutable
843  /// access to the results of lookup up a name within this context.
844  typedef NamedDecl * const * lookup_const_iterator;
845
846  typedef std::pair<lookup_iterator, lookup_iterator> lookup_result;
847  typedef std::pair<lookup_const_iterator, lookup_const_iterator>
848    lookup_const_result;
849
850  /// lookup - Find the declarations (if any) with the given Name in
851  /// this context. Returns a range of iterators that contains all of
852  /// the declarations with this name, with object, function, member,
853  /// and enumerator names preceding any tag name. Note that this
854  /// routine will not look into parent contexts.
855  lookup_result lookup(DeclarationName Name);
856  lookup_const_result lookup(DeclarationName Name) const;
857
858  /// @brief Makes a declaration visible within this context.
859  ///
860  /// This routine makes the declaration D visible to name lookup
861  /// within this context and, if this is a transparent context,
862  /// within its parent contexts up to the first enclosing
863  /// non-transparent context. Making a declaration visible within a
864  /// context does not transfer ownership of a declaration, and a
865  /// declaration can be visible in many contexts that aren't its
866  /// lexical context.
867  ///
868  /// If D is a redeclaration of an existing declaration that is
869  /// visible from this context, as determined by
870  /// NamedDecl::declarationReplaces, the previous declaration will be
871  /// replaced with D.
872  void makeDeclVisibleInContext(NamedDecl *D);
873
874  /// udir_iterator - Iterates through the using-directives stored
875  /// within this context.
876  typedef UsingDirectiveDecl * const * udir_iterator;
877
878  typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
879
880  udir_iterator_range getUsingDirectives() const;
881
882  udir_iterator using_directives_begin() const {
883    return getUsingDirectives().first;
884  }
885
886  udir_iterator using_directives_end() const {
887    return getUsingDirectives().second;
888  }
889
890  // Low-level accessors
891
892  /// \brief Retrieve the internal representation of the lookup structure.
893  void* getLookupPtr() const { return LookupPtr; }
894
895  /// \brief Whether this DeclContext has external storage containing
896  /// additional declarations that are lexically in this context.
897  bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
898
899  /// \brief State whether this DeclContext has external storage for
900  /// declarations lexically in this context.
901  void setHasExternalLexicalStorage(bool ES = true) {
902    ExternalLexicalStorage = ES;
903  }
904
905  /// \brief Whether this DeclContext has external storage containing
906  /// additional declarations that are visible in this context.
907  bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
908
909  /// \brief State whether this DeclContext has external storage for
910  /// declarations visible in this context.
911  void setHasExternalVisibleStorage(bool ES = true) {
912    ExternalVisibleStorage = ES;
913  }
914
915  static bool classof(const Decl *D);
916  static bool classof(const DeclContext *D) { return true; }
917#define DECL_CONTEXT(Name) \
918  static bool classof(const Name##Decl *D) { return true; }
919#include "clang/AST/DeclNodes.def"
920
921private:
922  void LoadLexicalDeclsFromExternalStorage() const;
923  void LoadVisibleDeclsFromExternalStorage() const;
924
925  void buildLookup(DeclContext *DCtx);
926  void makeDeclVisibleInContextImpl(NamedDecl *D);
927};
928
929inline bool Decl::isTemplateParameter() const {
930  return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm;
931}
932
933inline bool Decl::isDefinedOutsideFunctionOrMethod() const {
934  if (getDeclContext())
935    return !getDeclContext()->getLookupContext()->isFunctionOrMethod();
936  return true;
937}
938
939} // end clang.
940
941namespace llvm {
942
943/// Implement a isa_impl_wrap specialization to check whether a DeclContext is
944/// a specific Decl.
945template<class ToTy>
946struct isa_impl_wrap<ToTy,
947                     const ::clang::DeclContext,const ::clang::DeclContext> {
948  static bool doit(const ::clang::DeclContext &Val) {
949    return ToTy::classof(::clang::Decl::castFromDeclContext(&Val));
950  }
951};
952template<class ToTy>
953struct isa_impl_wrap<ToTy, ::clang::DeclContext, ::clang::DeclContext>
954  : public isa_impl_wrap<ToTy,
955                      const ::clang::DeclContext,const ::clang::DeclContext> {};
956
957/// Implement cast_convert_val for Decl -> DeclContext conversions.
958template<class FromTy>
959struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
960  static ::clang::DeclContext &doit(const FromTy &Val) {
961    return *FromTy::castToDeclContext(&Val);
962  }
963};
964
965template<class FromTy>
966struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
967  static ::clang::DeclContext *doit(const FromTy *Val) {
968    return FromTy::castToDeclContext(Val);
969  }
970};
971
972template<class FromTy>
973struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
974  static const ::clang::DeclContext &doit(const FromTy &Val) {
975    return *FromTy::castToDeclContext(&Val);
976  }
977};
978
979template<class FromTy>
980struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
981  static const ::clang::DeclContext *doit(const FromTy *Val) {
982    return FromTy::castToDeclContext(Val);
983  }
984};
985
986/// Implement cast_convert_val for DeclContext -> Decl conversions.
987template<class ToTy>
988struct cast_convert_val<ToTy,
989                        const ::clang::DeclContext,const ::clang::DeclContext> {
990  static ToTy &doit(const ::clang::DeclContext &Val) {
991    return *reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(&Val));
992  }
993};
994template<class ToTy>
995struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext>
996  : public cast_convert_val<ToTy,
997                      const ::clang::DeclContext,const ::clang::DeclContext> {};
998
999template<class ToTy>
1000struct cast_convert_val<ToTy,
1001                     const ::clang::DeclContext*, const ::clang::DeclContext*> {
1002  static ToTy *doit(const ::clang::DeclContext *Val) {
1003    return reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(Val));
1004  }
1005};
1006template<class ToTy>
1007struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*>
1008  : public cast_convert_val<ToTy,
1009                    const ::clang::DeclContext*,const ::clang::DeclContext*> {};
1010
1011} // end namespace llvm
1012
1013#endif
1014