DeclBase.h revision 279272e63b321f89c8fa0bb198acd3a834459aeb
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 "clang/Basic/SourceLocation.h"
22#include "llvm/ADT/PointerIntPair.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 LinkageSpecDecl;
41class BlockDecl;
42class DeclarationName;
43
44/// Decl - This represents one declaration (or definition), e.g. a variable,
45/// typedef, function, struct, etc.
46///
47class Decl {
48public:
49  /// \brief Lists the kind of concrete classes of Decl.
50  enum Kind {
51#define DECL(Derived, Base) Derived,
52#define DECL_RANGE(CommonBase, Start, End) \
53    CommonBase##First = Start, CommonBase##Last = End,
54#define LAST_DECL_RANGE(CommonBase, Start, End) \
55    CommonBase##First = Start, CommonBase##Last = End
56#include "clang/AST/DeclNodes.def"
57  };
58
59  /// IdentifierNamespace - According to C99 6.2.3, there are four namespaces,
60  /// labels, tags, members and ordinary identifiers. These are meant
61  /// as bitmasks, so that searches in C++ can look into the "tag" namespace
62  /// during ordinary lookup.
63  enum IdentifierNamespace {
64    IDNS_Label = 0x1,
65    IDNS_Tag = 0x2,
66    IDNS_Member = 0x4,
67    IDNS_Ordinary = 0x8
68  };
69
70  /// ObjCDeclQualifier - Qualifier used on types in method declarations
71  /// for remote messaging. They are meant for the arguments though and
72  /// applied to the Decls (ObjCMethodDecl and ParmVarDecl).
73  enum ObjCDeclQualifier {
74    OBJC_TQ_None = 0x0,
75    OBJC_TQ_In = 0x1,
76    OBJC_TQ_Inout = 0x2,
77    OBJC_TQ_Out = 0x4,
78    OBJC_TQ_Bycopy = 0x8,
79    OBJC_TQ_Byref = 0x10,
80    OBJC_TQ_Oneway = 0x20
81  };
82
83private:
84  /// Loc - The location that this decl.
85  SourceLocation Loc;
86
87  /// NextDeclarator - If this decl was part of a multi-declarator declaration,
88  /// such as "int X, Y, *Z;" this indicates Decl for the next declarator.
89  Decl *NextDeclarator;
90
91  /// NextDeclInScope - The next declaration within the same lexical
92  /// DeclContext. These pointers form the linked list that is
93  /// traversed via DeclContext's decls_begin()/decls_end().
94  /// FIXME: If NextDeclarator is non-NULL, will it always be the same
95  /// as NextDeclInScope? If so, we can use a
96  /// PointerIntPair<Decl*, 1> to make Decl smaller.
97  Decl *NextDeclInScope;
98
99  friend class DeclContext;
100
101  /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
102  /// For declarations that don't contain C++ scope specifiers, it contains
103  /// the DeclContext where the Decl was declared.
104  /// For declarations with C++ scope specifiers, it contains a MultipleDC*
105  /// with the context where it semantically belongs (SemanticDC) and the
106  /// context where it was lexically declared (LexicalDC).
107  /// e.g.:
108  ///
109  ///   namespace A {
110  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
111  ///   }
112  ///   void A::f(); // SemanticDC == namespace 'A'
113  ///                // LexicalDC == global namespace
114  uintptr_t DeclCtx;
115
116  struct MultipleDC {
117    DeclContext *SemanticDC;
118    DeclContext *LexicalDC;
119  };
120
121  inline bool isInSemaDC() const { return (DeclCtx & 0x1) == 0; }
122  inline bool isOutOfSemaDC() const { return (DeclCtx & 0x1) != 0; }
123  inline MultipleDC *getMultipleDC() const {
124    return reinterpret_cast<MultipleDC*>(DeclCtx & ~0x1);
125  }
126
127  /// DeclKind - This indicates which class this is.
128  Kind DeclKind   :  8;
129
130  /// InvalidDecl - This indicates a semantic error occurred.
131  unsigned int InvalidDecl :  1;
132
133  /// HasAttrs - This indicates whether the decl has attributes or not.
134  unsigned int HasAttrs : 1;
135
136  /// Implicit - Whether this declaration was implicitly generated by
137  /// the implementation rather than explicitly written by the user.
138  bool Implicit : 1;
139
140protected:
141  /// Access - Used by C++ decls for the access specifier.
142  // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
143  unsigned Access : 2;
144  friend class CXXClassMemberWrapper;
145
146  Decl(Kind DK, DeclContext *DC, SourceLocation L)
147    : Loc(L), NextDeclarator(0), NextDeclInScope(0),
148      DeclCtx(reinterpret_cast<uintptr_t>(DC)), DeclKind(DK), InvalidDecl(0),
149      HasAttrs(false), Implicit(false) {
150    if (Decl::CollectingStats()) addDeclKind(DK);
151  }
152
153  virtual ~Decl();
154
155  /// setDeclContext - Set both the semantic and lexical DeclContext
156  /// to DC.
157  void setDeclContext(DeclContext *DC);
158
159public:
160  SourceLocation getLocation() const { return Loc; }
161  void setLocation(SourceLocation L) { Loc = L; }
162
163  Kind getKind() const { return DeclKind; }
164  const char *getDeclKindName() const;
165
166  const DeclContext *getDeclContext() const {
167    if (isInSemaDC())
168      return reinterpret_cast<DeclContext*>(DeclCtx);
169    return getMultipleDC()->SemanticDC;
170  }
171  DeclContext *getDeclContext() {
172    return const_cast<DeclContext*>(
173                         const_cast<const Decl*>(this)->getDeclContext());
174  }
175
176  void setAccess(AccessSpecifier AS) { Access = AS; }
177  AccessSpecifier getAccess() const { return AccessSpecifier(Access); }
178
179  void addAttr(Attr *attr);
180  const Attr *getAttrs() const;
181  void swapAttrs(Decl *D);
182  void invalidateAttrs();
183
184  template<typename T> const T *getAttr() const {
185    for (const Attr *attr = getAttrs(); attr; attr = attr->getNext())
186      if (const T *V = dyn_cast<T>(attr))
187        return V;
188
189    return 0;
190  }
191
192  /// setInvalidDecl - Indicates the Decl had a semantic error. This
193  /// allows for graceful error recovery.
194  void setInvalidDecl() { InvalidDecl = 1; }
195  bool isInvalidDecl() const { return (bool) InvalidDecl; }
196
197  /// isImplicit - Indicates whether the declaration was implicitly
198  /// generated by the implementation. If false, this declaration
199  /// was written explicitly in the source code.
200  bool isImplicit() const { return Implicit; }
201  void setImplicit(bool I = true) { Implicit = I; }
202
203  IdentifierNamespace getIdentifierNamespace() const {
204    switch (DeclKind) {
205    default:
206      if (DeclKind >= FunctionFirst && DeclKind <= FunctionLast)
207        return IDNS_Ordinary;
208      assert(0 && "Unknown decl kind!");
209    case OverloadedFunction:
210    case Typedef:
211    case EnumConstant:
212    case Var:
213    case CXXClassVar:
214    case ImplicitParam:
215    case ParmVar:
216    case OriginalParmVar:
217    case NonTypeTemplateParm:
218    case ObjCMethod:
219    case ObjCContainer:
220    case ObjCCategory:
221    case ObjCProtocol:
222    case ObjCInterface:
223    case ObjCCategoryImpl:
224    case ObjCProperty:
225    case ObjCCompatibleAlias:
226      return IDNS_Ordinary;
227
228    case Field:
229    case ObjCAtDefsField:
230    case ObjCIvar:
231      return IDNS_Member;
232
233    case Record:
234    case CXXRecord:
235    case Enum:
236    case TemplateTypeParm:
237      return IDNS_Tag;
238
239    case Namespace:
240    case Template:
241    case FunctionTemplate:
242    case ClassTemplate:
243    case TemplateTemplateParm:
244      return IdentifierNamespace(IDNS_Tag | IDNS_Ordinary);
245    }
246  }
247
248  bool isInIdentifierNamespace(unsigned NS) const {
249    return getIdentifierNamespace() & NS;
250  }
251
252  /// getLexicalDeclContext - The declaration context where this Decl was
253  /// lexically declared (LexicalDC). May be different from
254  /// getDeclContext() (SemanticDC).
255  /// e.g.:
256  ///
257  ///   namespace A {
258  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
259  ///   }
260  ///   void A::f(); // SemanticDC == namespace 'A'
261  ///                // LexicalDC == global namespace
262  const DeclContext *getLexicalDeclContext() const {
263    if (isInSemaDC())
264      return reinterpret_cast<DeclContext*>(DeclCtx);
265    return getMultipleDC()->LexicalDC;
266  }
267  DeclContext *getLexicalDeclContext() {
268    return const_cast<DeclContext*>(
269                  const_cast<const Decl*>(this)->getLexicalDeclContext());
270  }
271
272  void setLexicalDeclContext(DeclContext *DC);
273
274  /// getNextDeclarator - If this decl was part of a multi-declarator
275  /// declaration, such as "int X, Y, *Z;" this returns the decl for the next
276  /// declarator.  Otherwise it returns null.
277  Decl *getNextDeclarator() { return NextDeclarator; }
278  const Decl *getNextDeclarator() const { return NextDeclarator; }
279  void setNextDeclarator(Decl *N) { NextDeclarator = N; }
280
281  // isDefinedOutsideFunctionOrMethod - This predicate returns true if this
282  // scoped decl is defined outside the current function or method.  This is
283  // roughly global variables and functions, but also handles enums (which could
284  // be defined inside or outside a function etc).
285  bool isDefinedOutsideFunctionOrMethod() const;
286
287  // getBody - If this Decl represents a declaration for a body of code,
288  //  such as a function or method definition, this method returns the top-level
289  //  Stmt* of that body.  Otherwise this method returns null.
290  virtual Stmt* getBody() const { return 0; }
291
292  // global temp stats (until we have a per-module visitor)
293  static void addDeclKind(Kind k);
294  static bool CollectingStats(bool Enable = false);
295  static void PrintStats();
296
297  /// isTemplateParameter - Determines whether this declartion is a
298  /// template parameter.
299  bool isTemplateParameter() const;
300
301  // Implement isa/cast/dyncast/etc.
302  static bool classof(const Decl *) { return true; }
303  static DeclContext *castToDeclContext(const Decl *);
304  static Decl *castFromDeclContext(const DeclContext *);
305
306  /// Emit - Serialize this Decl to Bitcode.
307  void Emit(llvm::Serializer& S) const;
308
309  /// Create - Deserialize a Decl from Bitcode.
310  static Decl* Create(llvm::Deserializer& D, ASTContext& C);
311
312  /// Destroy - Call destructors and release memory.
313  virtual void Destroy(ASTContext& C);
314
315protected:
316  /// EmitImpl - Provides the subclass-specific serialization logic for
317  ///   serializing out a decl.
318  virtual void EmitImpl(llvm::Serializer& S) const {
319    // FIXME: This will eventually be a pure virtual function.
320    assert (false && "Not implemented.");
321  }
322};
323
324/// DeclContext - This is used only as base class of specific decl types that
325/// can act as declaration contexts. These decls are:
326///
327///   TranslationUnitDecl
328///   NamespaceDecl
329///   FunctionDecl
330///   RecordDecl/CXXRecordDecl
331///   EnumDecl
332///   ObjCMethodDecl
333///   ObjCInterfaceDecl
334///   LinkageSpecDecl
335///   BlockDecl
336class DeclContext {
337  /// DeclKind - This indicates which class this is.
338  Decl::Kind DeclKind   :  8;
339
340  /// LookupPtrKind - Describes what kind of pointer LookupPtr
341  /// actually is.
342  enum LookupPtrKind {
343    /// LookupIsMap - Indicates that LookupPtr is actually a map.
344    LookupIsMap = 7
345  };
346
347  /// LookupPtr - Pointer to a data structure used to lookup
348  /// declarations within this context. If the context contains fewer
349  /// than seven declarations, the number of declarations is provided
350  /// in the 3 lowest-order bits and the upper bits are treated as a
351  /// pointer to an array of NamedDecl pointers. If the context
352  /// contains seven or more declarations, the upper bits are treated
353  /// as a pointer to a DenseMap<DeclarationName, std::vector<NamedDecl*>>.
354  /// FIXME: We need a better data structure for this.
355  llvm::PointerIntPair<void*, 3> LookupPtr;
356
357  /// FirstDecl - The first declaration stored within this declaration
358  /// context.
359  Decl *FirstDecl;
360
361  /// LastDecl - The last declaration stored within this declaration
362  /// context. FIXME: We could probably cache this value somewhere
363  /// outside of the DeclContext, to reduce the size of DeclContext by
364  /// another pointer.
365  Decl *LastDecl;
366
367  // Used in the CastTo template to get the DeclKind
368  // from a Decl or a DeclContext. DeclContext doesn't have a getKind() method
369  // to avoid 'ambiguous access' compiler errors.
370  template<typename T> struct KindTrait {
371    static Decl::Kind getKind(const T *D) { return D->getKind(); }
372  };
373
374  // Used only by the ToDecl and FromDecl methods
375  template<typename To, typename From>
376  static To *CastTo(const From *D) {
377    Decl::Kind DK = KindTrait<From>::getKind(D);
378    switch(DK) {
379      case Decl::TranslationUnit:
380        return static_cast<TranslationUnitDecl*>(const_cast<From*>(D));
381      case Decl::Namespace:
382        return static_cast<NamespaceDecl*>(const_cast<From*>(D));
383      case Decl::Enum:
384        return static_cast<EnumDecl*>(const_cast<From*>(D));
385      case Decl::Record:
386        return static_cast<RecordDecl*>(const_cast<From*>(D));
387      case Decl::CXXRecord:
388        return static_cast<CXXRecordDecl*>(const_cast<From*>(D));
389      case Decl::ObjCMethod:
390        return static_cast<ObjCMethodDecl*>(const_cast<From*>(D));
391      case Decl::ObjCInterface:
392        return static_cast<ObjCInterfaceDecl*>(const_cast<From*>(D));
393      case Decl::ObjCCategory:
394        return static_cast<ObjCCategoryDecl*>(const_cast<From*>(D));
395      case Decl::ObjCProtocol:
396        return static_cast<ObjCProtocolDecl*>(const_cast<From*>(D));
397      case Decl::ObjCImplementation:
398        return static_cast<ObjCImplementationDecl*>(const_cast<From*>(D));
399      case Decl::ObjCCategoryImpl:
400        return static_cast<ObjCCategoryImplDecl*>(const_cast<From*>(D));
401      case Decl::LinkageSpec:
402        return static_cast<LinkageSpecDecl*>(const_cast<From*>(D));
403      case Decl::Block:
404        return static_cast<BlockDecl*>(const_cast<From*>(D));
405      default:
406        if (DK >= Decl::FunctionFirst && DK <= Decl::FunctionLast)
407          return static_cast<FunctionDecl*>(const_cast<From*>(D));
408
409        assert(false && "a decl that inherits DeclContext isn't handled");
410        return 0;
411    }
412  }
413
414  /// isLookupMap - Determine if the lookup structure is a
415  /// DenseMap. Othewise, it is an array.
416  bool isLookupMap() const { return LookupPtr.getInt() == LookupIsMap; }
417
418  static Decl *getNextDeclInScope(Decl *D) { return D->NextDeclInScope; }
419
420protected:
421   DeclContext(Decl::Kind K)
422     : DeclKind(K), LookupPtr(), FirstDecl(0), LastDecl(0) { }
423
424  void DestroyDecls(ASTContext &C);
425
426public:
427  ~DeclContext();
428
429  Decl::Kind getDeclKind() const {
430    return DeclKind;
431  }
432  const char *getDeclKindName() const;
433
434  /// getParent - Returns the containing DeclContext if this is a Decl,
435  /// else returns NULL.
436  const DeclContext *getParent() const;
437  DeclContext *getParent() {
438    return const_cast<DeclContext*>(
439                             const_cast<const DeclContext*>(this)->getParent());
440  }
441
442  /// getLexicalParent - Returns the containing lexical DeclContext. May be
443  /// different from getParent, e.g.:
444  ///
445  ///   namespace A {
446  ///      struct S;
447  ///   }
448  ///   struct A::S {}; // getParent() == namespace 'A'
449  ///                   // getLexicalParent() == translation unit
450  ///
451  const DeclContext *getLexicalParent() const;
452  DeclContext *getLexicalParent() {
453    return const_cast<DeclContext*>(
454                      const_cast<const DeclContext*>(this)->getLexicalParent());
455  }
456
457  bool isFunctionOrMethod() const {
458    switch (DeclKind) {
459      case Decl::Block:
460      case Decl::ObjCMethod:
461        return true;
462
463      default:
464       if (DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast)
465         return true;
466        return false;
467    }
468  }
469
470  bool isFileContext() const {
471    return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
472  }
473
474  bool isRecord() const {
475    return DeclKind == Decl::Record || DeclKind == Decl::CXXRecord;
476  }
477
478  bool isNamespace() const {
479    return DeclKind == Decl::Namespace;
480  }
481
482  /// isTransparentContext - Determines whether this context is a
483  /// "transparent" context, meaning that the members declared in this
484  /// context are semantically declared in the nearest enclosing
485  /// non-transparent (opaque) context but are lexically declared in
486  /// this context. For example, consider the enumerators of an
487  /// enumeration type:
488  /// @code
489  /// enum E {
490  ///   Val1
491  /// };
492  /// @endcode
493  /// Here, E is a transparent context, so its enumerator (Val1) will
494  /// appear (semantically) that it is in the same context of E.
495  /// Examples of transparent contexts include: enumerations (except for
496  /// C++0x scoped enums), C++ linkage specifications, and C++0x
497  /// inline namespaces.
498  bool isTransparentContext() const;
499
500  bool Encloses(DeclContext *DC) const {
501    for (; DC; DC = DC->getParent())
502      if (DC == this)
503        return true;
504    return false;
505  }
506
507  /// getPrimaryContext - There may be many different
508  /// declarations of the same entity (including forward declarations
509  /// of classes, multiple definitions of namespaces, etc.), each with
510  /// a different set of declarations. This routine returns the
511  /// "primary" DeclContext structure, which will contain the
512  /// information needed to perform name lookup into this context.
513  DeclContext *getPrimaryContext();
514
515  /// getLookupContext - Retrieve the innermost non-transparent
516  /// context of this context, which corresponds to the innermost
517  /// location from which name lookup can find the entities in this
518  /// context.
519  DeclContext *getLookupContext() {
520    return const_cast<DeclContext *>(
521             const_cast<const DeclContext *>(this)->getLookupContext());
522  }
523  const DeclContext *getLookupContext() const;
524
525  /// getNextContext - If this is a DeclContext that may have other
526  /// DeclContexts that are semantically connected but syntactically
527  /// different, such as C++ namespaces, this routine retrieves the
528  /// next DeclContext in the link. Iteration through the chain of
529  /// DeclContexts should begin at the primary DeclContext and
530  /// continue until this function returns NULL. For example, given:
531  /// @code
532  /// namespace N {
533  ///   int x;
534  /// }
535  /// namespace N {
536  ///   int y;
537  /// }
538  /// @endcode
539  /// The first occurrence of namespace N will be the primary
540  /// DeclContext. Its getNextContext will return the second
541  /// occurrence of namespace N.
542  DeclContext *getNextContext();
543
544  /// decl_iterator - Iterates through the declarations stored
545  /// within this context.
546  class decl_iterator {
547    /// Current - The current declaration.
548    Decl *Current;
549
550  public:
551    typedef Decl*                     value_type;
552    typedef Decl*                     reference;
553    typedef Decl*                     pointer;
554    typedef std::forward_iterator_tag iterator_category;
555    typedef std::ptrdiff_t            difference_type;
556
557    decl_iterator() : Current(0) { }
558    explicit decl_iterator(Decl *C) : Current(C) { }
559
560    reference operator*() const { return Current; }
561    pointer operator->() const { return Current; }
562
563    decl_iterator& operator++();
564
565    decl_iterator operator++(int) {
566      decl_iterator tmp(*this);
567      ++(*this);
568      return tmp;
569    }
570
571    friend bool operator==(decl_iterator x, decl_iterator y) {
572      return x.Current == y.Current;
573    }
574    friend bool operator!=(decl_iterator x, decl_iterator y) {
575      return x.Current != y.Current;
576    }
577  };
578
579  /// decls_begin/decls_end - Iterate over the declarations stored in
580  /// this context.
581  decl_iterator decls_begin() const { return decl_iterator(FirstDecl); }
582  decl_iterator decls_end()   const { return decl_iterator(); }
583
584  /// specific_decl_iterator - Iterates over a subrange of
585  /// declarations stored in a DeclContext, providing only those that
586  /// are of type SpecificDecl (or a class derived from it). This
587  /// iterator is used, for example, to provide iteration over just
588  /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
589  template<typename SpecificDecl>
590  class specific_decl_iterator {
591    /// Current - The current, underlying declaration iterator, which
592    /// will either be NULL or will point to a declaration of
593    /// type SpecificDecl.
594    DeclContext::decl_iterator Current;
595
596    /// SkipToNextDecl - Advances the current position up to the next
597    /// declaration of type SpecificDecl that also meets the criteria
598    /// required by Acceptable.
599    void SkipToNextDecl() {
600      while (*Current && !isa<SpecificDecl>(*Current))
601        ++Current;
602    }
603
604  public:
605    typedef SpecificDecl* value_type;
606    typedef SpecificDecl* reference;
607    typedef SpecificDecl* pointer;
608    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
609      difference_type;
610    typedef std::forward_iterator_tag iterator_category;
611
612    specific_decl_iterator() : Current() { }
613
614    /// specific_decl_iterator - Construct a new iterator over a
615    /// subset of the declarations the range [C,
616    /// end-of-declarations). If A is non-NULL, it is a pointer to a
617    /// member function of SpecificDecl that should return true for
618    /// all of the SpecificDecl instances that will be in the subset
619    /// of iterators. For example, if you want Objective-C instance
620    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
621    /// &ObjCMethodDecl::isInstanceMethod.
622    explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
623      SkipToNextDecl();
624    }
625
626    reference operator*() const { return cast<SpecificDecl>(*Current); }
627    pointer operator->() const { return cast<SpecificDecl>(*Current); }
628
629    specific_decl_iterator& operator++() {
630      ++Current;
631      SkipToNextDecl();
632      return *this;
633    }
634
635    specific_decl_iterator operator++(int) {
636      specific_decl_iterator tmp(*this);
637      ++(*this);
638      return tmp;
639    }
640
641    friend bool
642    operator==(const specific_decl_iterator& x, const specific_decl_iterator& y) {
643      return x.Current == y.Current;
644    }
645
646    friend bool
647    operator!=(const specific_decl_iterator& x, const specific_decl_iterator& y) {
648      return x.Current != y.Current;
649    }
650  };
651
652  /// \brief Iterates over a filtered subrange of declarations stored
653  /// in a DeclContext.
654  ///
655  /// This iterator visits only those declarations that are of type
656  /// SpecificDecl (or a class derived from it) and that meet some
657  /// additional run-time criteria. This iterator is used, for
658  /// example, to provide access to the instance methods within an
659  /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
660  /// Acceptable = ObjCMethodDecl::isInstanceMethod).
661  template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
662  class filtered_decl_iterator {
663    /// Current - The current, underlying declaration iterator, which
664    /// will either be NULL or will point to a declaration of
665    /// type SpecificDecl.
666    DeclContext::decl_iterator Current;
667
668    /// SkipToNextDecl - Advances the current position up to the next
669    /// declaration of type SpecificDecl that also meets the criteria
670    /// required by Acceptable.
671    void SkipToNextDecl() {
672      while (*Current &&
673             (!isa<SpecificDecl>(*Current) ||
674              (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
675        ++Current;
676    }
677
678  public:
679    typedef SpecificDecl* value_type;
680    typedef SpecificDecl* reference;
681    typedef SpecificDecl* pointer;
682    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
683      difference_type;
684    typedef std::forward_iterator_tag iterator_category;
685
686    filtered_decl_iterator() : Current() { }
687
688    /// specific_decl_iterator - Construct a new iterator over a
689    /// subset of the declarations the range [C,
690    /// end-of-declarations). If A is non-NULL, it is a pointer to a
691    /// member function of SpecificDecl that should return true for
692    /// all of the SpecificDecl instances that will be in the subset
693    /// of iterators. For example, if you want Objective-C instance
694    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
695    /// &ObjCMethodDecl::isInstanceMethod.
696    explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
697      SkipToNextDecl();
698    }
699
700    reference operator*() const { return cast<SpecificDecl>(*Current); }
701    pointer operator->() const { return cast<SpecificDecl>(*Current); }
702
703    filtered_decl_iterator& operator++() {
704      ++Current;
705      SkipToNextDecl();
706      return *this;
707    }
708
709    filtered_decl_iterator operator++(int) {
710      filtered_decl_iterator tmp(*this);
711      ++(*this);
712      return tmp;
713    }
714
715    friend bool
716    operator==(const filtered_decl_iterator& x, const filtered_decl_iterator& y) {
717      return x.Current == y.Current;
718    }
719
720    friend bool
721    operator!=(const filtered_decl_iterator& x, const filtered_decl_iterator& y) {
722      return x.Current != y.Current;
723    }
724  };
725
726  /// @brief Add the declaration D into this context.
727  ///
728  /// This routine should be invoked when the declaration D has first
729  /// been declared, to place D into the context where it was
730  /// (lexically) defined. Every declaration must be added to one
731  /// (and only one!) context, where it can be visited via
732  /// [decls_begin(), decls_end()). Once a declaration has been added
733  /// to its lexical context, the corresponding DeclContext owns the
734  /// declaration.
735  ///
736  /// If D is also a NamedDecl, it will be made visible within its
737  /// semantic context via makeDeclVisibleInContext.
738  void addDecl(Decl *D);
739
740  /// lookup_iterator - An iterator that provides access to the results
741  /// of looking up a name within this context.
742  typedef NamedDecl **lookup_iterator;
743
744  /// lookup_const_iterator - An iterator that provides non-mutable
745  /// access to the results of lookup up a name within this context.
746  typedef NamedDecl * const * lookup_const_iterator;
747
748  typedef std::pair<lookup_iterator, lookup_iterator> lookup_result;
749  typedef std::pair<lookup_const_iterator, lookup_const_iterator>
750    lookup_const_result;
751
752  /// lookup - Find the declarations (if any) with the given Name in
753  /// this context. Returns a range of iterators that contains all of
754  /// the declarations with this name, with object, function, member,
755  /// and enumerator names preceding any tag name. Note that this
756  /// routine will not look into parent contexts.
757  lookup_result lookup(DeclarationName Name);
758  lookup_const_result lookup(DeclarationName Name) const;
759
760  /// @brief Makes a declaration visible within this context.
761  ///
762  /// This routine makes the declaration D visible to name lookup
763  /// within this context and, if this is a transparent context,
764  /// within its parent contexts up to the first enclosing
765  /// non-transparent context. Making a declaration visible within a
766  /// context does not transfer ownership of a declaration, and a
767  /// declaration can be visible in many contexts that aren't its
768  /// lexical context.
769  ///
770  /// If D is a redeclaration of an existing declaration that is
771  /// visible from this context, as determined by
772  /// NamedDecl::declarationReplaces, the previous declaration will be
773  /// replaced with D.
774  void makeDeclVisibleInContext(NamedDecl *D);
775
776  /// udir_iterator - Iterates through the using-directives stored
777  /// within this context.
778  typedef UsingDirectiveDecl * const * udir_iterator;
779
780  typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
781
782  udir_iterator_range getUsingDirectives() const;
783
784  udir_iterator using_directives_begin() const {
785    return getUsingDirectives().first;
786  }
787
788  udir_iterator using_directives_end() const {
789    return getUsingDirectives().second;
790  }
791
792  static bool classof(const Decl *D) {
793    switch (D->getKind()) {
794#define DECL_CONTEXT(Name) case Decl::Name:
795#include "clang/AST/DeclNodes.def"
796        return true;
797      default:
798        if (D->getKind() >= Decl::FunctionFirst &&
799            D->getKind() <= Decl::FunctionLast)
800          return true;
801        return false;
802    }
803  }
804  static bool classof(const DeclContext *D) { return true; }
805#define DECL_CONTEXT(Name) \
806  static bool classof(const Name##Decl *D) { return true; }
807#include "clang/AST/DeclNodes.def"
808
809private:
810  void buildLookup(DeclContext *DCtx);
811  void makeDeclVisibleInContextImpl(NamedDecl *D);
812
813  void EmitOutRec(llvm::Serializer& S) const;
814  void ReadOutRec(llvm::Deserializer& D, ASTContext& C);
815
816  friend class Decl;
817};
818
819template<> struct DeclContext::KindTrait<DeclContext> {
820  static Decl::Kind getKind(const DeclContext *D) { return D->DeclKind; }
821};
822
823inline bool Decl::isTemplateParameter() const {
824  return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm;
825}
826
827inline bool Decl::isDefinedOutsideFunctionOrMethod() const {
828  if (getDeclContext())
829    return !getDeclContext()->getLookupContext()->isFunctionOrMethod();
830  else
831    return true;
832}
833
834inline DeclContext::decl_iterator& DeclContext::decl_iterator::operator++() {
835  Current = getNextDeclInScope(Current);
836  return *this;
837}
838
839} // end clang.
840
841namespace llvm {
842
843/// Implement a isa_impl_wrap specialization to check whether a DeclContext is
844/// a specific Decl.
845template<class ToTy>
846struct isa_impl_wrap<ToTy,
847                     const ::clang::DeclContext,const ::clang::DeclContext> {
848  static bool doit(const ::clang::DeclContext &Val) {
849    return ToTy::classof(::clang::Decl::castFromDeclContext(&Val));
850  }
851};
852template<class ToTy>
853struct isa_impl_wrap<ToTy, ::clang::DeclContext, ::clang::DeclContext>
854  : public isa_impl_wrap<ToTy,
855                      const ::clang::DeclContext,const ::clang::DeclContext> {};
856
857/// Implement cast_convert_val for Decl -> DeclContext conversions.
858template<class FromTy>
859struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
860  static ::clang::DeclContext &doit(const FromTy &Val) {
861    return *FromTy::castToDeclContext(&Val);
862  }
863};
864
865template<class FromTy>
866struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
867  static ::clang::DeclContext *doit(const FromTy *Val) {
868    return FromTy::castToDeclContext(Val);
869  }
870};
871
872template<class FromTy>
873struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
874  static const ::clang::DeclContext &doit(const FromTy &Val) {
875    return *FromTy::castToDeclContext(&Val);
876  }
877};
878
879template<class FromTy>
880struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
881  static const ::clang::DeclContext *doit(const FromTy *Val) {
882    return FromTy::castToDeclContext(Val);
883  }
884};
885
886/// Implement cast_convert_val for DeclContext -> Decl conversions.
887template<class ToTy>
888struct cast_convert_val<ToTy,
889                        const ::clang::DeclContext,const ::clang::DeclContext> {
890  static ToTy &doit(const ::clang::DeclContext &Val) {
891    return *reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(&Val));
892  }
893};
894template<class ToTy>
895struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext>
896  : public cast_convert_val<ToTy,
897                      const ::clang::DeclContext,const ::clang::DeclContext> {};
898
899template<class ToTy>
900struct cast_convert_val<ToTy,
901                     const ::clang::DeclContext*, const ::clang::DeclContext*> {
902  static ToTy *doit(const ::clang::DeclContext *Val) {
903    return reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(Val));
904  }
905};
906template<class ToTy>
907struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*>
908  : public cast_convert_val<ToTy,
909                    const ::clang::DeclContext*,const ::clang::DeclContext*> {};
910
911} // end namespace llvm
912
913#endif
914