DeclBase.h revision 2a3009a432bdcec59e6383d7b2b17494d6f91649
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      return IdentifierNamespace(IDNS_Tag | IDNS_Ordinary);
241    }
242  }
243
244  bool isInIdentifierNamespace(unsigned NS) const {
245    return getIdentifierNamespace() & NS;
246  }
247
248  /// getLexicalDeclContext - The declaration context where this Decl was
249  /// lexically declared (LexicalDC). May be different from
250  /// getDeclContext() (SemanticDC).
251  /// e.g.:
252  ///
253  ///   namespace A {
254  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
255  ///   }
256  ///   void A::f(); // SemanticDC == namespace 'A'
257  ///                // LexicalDC == global namespace
258  const DeclContext *getLexicalDeclContext() const {
259    if (isInSemaDC())
260      return reinterpret_cast<DeclContext*>(DeclCtx);
261    return getMultipleDC()->LexicalDC;
262  }
263  DeclContext *getLexicalDeclContext() {
264    return const_cast<DeclContext*>(
265                  const_cast<const Decl*>(this)->getLexicalDeclContext());
266  }
267
268  void setLexicalDeclContext(DeclContext *DC);
269
270  /// getNextDeclarator - If this decl was part of a multi-declarator
271  /// declaration, such as "int X, Y, *Z;" this returns the decl for the next
272  /// declarator.  Otherwise it returns null.
273  Decl *getNextDeclarator() { return NextDeclarator; }
274  const Decl *getNextDeclarator() const { return NextDeclarator; }
275  void setNextDeclarator(Decl *N) { NextDeclarator = N; }
276
277  // isDefinedOutsideFunctionOrMethod - This predicate returns true if this
278  // scoped decl is defined outside the current function or method.  This is
279  // roughly global variables and functions, but also handles enums (which could
280  // be defined inside or outside a function etc).
281  bool isDefinedOutsideFunctionOrMethod() const;
282
283  // getBody - If this Decl represents a declaration for a body of code,
284  //  such as a function or method definition, this method returns the top-level
285  //  Stmt* of that body.  Otherwise this method returns null.
286  virtual Stmt* getBody() const { return 0; }
287
288  // global temp stats (until we have a per-module visitor)
289  static void addDeclKind(Kind k);
290  static bool CollectingStats(bool Enable = false);
291  static void PrintStats();
292
293  /// isTemplateParameter - Determines whether this declartion is a
294  /// template parameter.
295  bool isTemplateParameter() const;
296
297  // Implement isa/cast/dyncast/etc.
298  static bool classof(const Decl *) { return true; }
299  static DeclContext *castToDeclContext(const Decl *);
300  static Decl *castFromDeclContext(const DeclContext *);
301
302  /// Emit - Serialize this Decl to Bitcode.
303  void Emit(llvm::Serializer& S) const;
304
305  /// Create - Deserialize a Decl from Bitcode.
306  static Decl* Create(llvm::Deserializer& D, ASTContext& C);
307
308  /// Destroy - Call destructors and release memory.
309  virtual void Destroy(ASTContext& C);
310
311protected:
312  /// EmitImpl - Provides the subclass-specific serialization logic for
313  ///   serializing out a decl.
314  virtual void EmitImpl(llvm::Serializer& S) const {
315    // FIXME: This will eventually be a pure virtual function.
316    assert (false && "Not implemented.");
317  }
318};
319
320/// DeclContext - This is used only as base class of specific decl types that
321/// can act as declaration contexts. These decls are:
322///
323///   TranslationUnitDecl
324///   NamespaceDecl
325///   FunctionDecl
326///   RecordDecl/CXXRecordDecl
327///   EnumDecl
328///   ObjCMethodDecl
329///   ObjCInterfaceDecl
330///   LinkageSpecDecl
331///   BlockDecl
332class DeclContext {
333  /// DeclKind - This indicates which class this is.
334  Decl::Kind DeclKind   :  8;
335
336  /// LookupPtrKind - Describes what kind of pointer LookupPtr
337  /// actually is.
338  enum LookupPtrKind {
339    /// LookupIsMap - Indicates that LookupPtr is actually a map.
340    LookupIsMap = 7
341  };
342
343  /// LookupPtr - Pointer to a data structure used to lookup
344  /// declarations within this context. If the context contains fewer
345  /// than seven declarations, the number of declarations is provided
346  /// in the 3 lowest-order bits and the upper bits are treated as a
347  /// pointer to an array of NamedDecl pointers. If the context
348  /// contains seven or more declarations, the upper bits are treated
349  /// as a pointer to a DenseMap<DeclarationName, std::vector<NamedDecl*>>.
350  /// FIXME: We need a better data structure for this.
351  llvm::PointerIntPair<void*, 3> LookupPtr;
352
353  /// FirstDecl - The first declaration stored within this declaration
354  /// context.
355  Decl *FirstDecl;
356
357  /// LastDecl - The last declaration stored within this declaration
358  /// context. FIXME: We could probably cache this value somewhere
359  /// outside of the DeclContext, to reduce the size of DeclContext by
360  /// another pointer.
361  Decl *LastDecl;
362
363  // Used in the CastTo template to get the DeclKind
364  // from a Decl or a DeclContext. DeclContext doesn't have a getKind() method
365  // to avoid 'ambiguous access' compiler errors.
366  template<typename T> struct KindTrait {
367    static Decl::Kind getKind(const T *D) { return D->getKind(); }
368  };
369
370  // Used only by the ToDecl and FromDecl methods
371  template<typename To, typename From>
372  static To *CastTo(const From *D) {
373    Decl::Kind DK = KindTrait<From>::getKind(D);
374    switch(DK) {
375      case Decl::TranslationUnit:
376        return static_cast<TranslationUnitDecl*>(const_cast<From*>(D));
377      case Decl::Namespace:
378        return static_cast<NamespaceDecl*>(const_cast<From*>(D));
379      case Decl::Enum:
380        return static_cast<EnumDecl*>(const_cast<From*>(D));
381      case Decl::Record:
382        return static_cast<RecordDecl*>(const_cast<From*>(D));
383      case Decl::CXXRecord:
384        return static_cast<CXXRecordDecl*>(const_cast<From*>(D));
385      case Decl::ObjCMethod:
386        return static_cast<ObjCMethodDecl*>(const_cast<From*>(D));
387      case Decl::ObjCInterface:
388        return static_cast<ObjCInterfaceDecl*>(const_cast<From*>(D));
389      case Decl::ObjCCategory:
390        return static_cast<ObjCCategoryDecl*>(const_cast<From*>(D));
391      case Decl::ObjCProtocol:
392        return static_cast<ObjCProtocolDecl*>(const_cast<From*>(D));
393      case Decl::ObjCImplementation:
394        return static_cast<ObjCImplementationDecl*>(const_cast<From*>(D));
395      case Decl::ObjCCategoryImpl:
396        return static_cast<ObjCCategoryImplDecl*>(const_cast<From*>(D));
397      case Decl::LinkageSpec:
398        return static_cast<LinkageSpecDecl*>(const_cast<From*>(D));
399      case Decl::Block:
400        return static_cast<BlockDecl*>(const_cast<From*>(D));
401      default:
402        if (DK >= Decl::FunctionFirst && DK <= Decl::FunctionLast)
403          return static_cast<FunctionDecl*>(const_cast<From*>(D));
404
405        assert(false && "a decl that inherits DeclContext isn't handled");
406        return 0;
407    }
408  }
409
410  /// isLookupMap - Determine if the lookup structure is a
411  /// DenseMap. Othewise, it is an array.
412  bool isLookupMap() const { return LookupPtr.getInt() == LookupIsMap; }
413
414  static Decl *getNextDeclInScope(Decl *D) { return D->NextDeclInScope; }
415
416protected:
417   DeclContext(Decl::Kind K)
418     : DeclKind(K), LookupPtr(), FirstDecl(0), LastDecl(0) { }
419
420  void DestroyDecls(ASTContext &C);
421
422public:
423  ~DeclContext();
424
425  Decl::Kind getDeclKind() const {
426    return DeclKind;
427  }
428  const char *getDeclKindName() const;
429
430  /// getParent - Returns the containing DeclContext if this is a Decl,
431  /// else returns NULL.
432  const DeclContext *getParent() const;
433  DeclContext *getParent() {
434    return const_cast<DeclContext*>(
435                             const_cast<const DeclContext*>(this)->getParent());
436  }
437
438  /// getLexicalParent - Returns the containing lexical DeclContext. May be
439  /// different from getParent, e.g.:
440  ///
441  ///   namespace A {
442  ///      struct S;
443  ///   }
444  ///   struct A::S {}; // getParent() == namespace 'A'
445  ///                   // getLexicalParent() == translation unit
446  ///
447  const DeclContext *getLexicalParent() const;
448  DeclContext *getLexicalParent() {
449    return const_cast<DeclContext*>(
450                      const_cast<const DeclContext*>(this)->getLexicalParent());
451  }
452
453  bool isFunctionOrMethod() const {
454    switch (DeclKind) {
455      case Decl::Block:
456      case Decl::ObjCMethod:
457        return true;
458
459      default:
460       if (DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast)
461         return true;
462        return false;
463    }
464  }
465
466  bool isFileContext() const {
467    return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
468  }
469
470  bool isRecord() const {
471    return DeclKind == Decl::Record || DeclKind == Decl::CXXRecord;
472  }
473
474  bool isNamespace() const {
475    return DeclKind == Decl::Namespace;
476  }
477
478  /// isTransparentContext - Determines whether this context is a
479  /// "transparent" context, meaning that the members declared in this
480  /// context are semantically declared in the nearest enclosing
481  /// non-transparent (opaque) context but are lexically declared in
482  /// this context. For example, consider the enumerators of an
483  /// enumeration type:
484  /// @code
485  /// enum E {
486  ///   Val1
487  /// };
488  /// @endcode
489  /// Here, E is a transparent context, so its enumerator (Val1) will
490  /// appear (semantically) that it is in the same context of E.
491  /// Examples of transparent contexts include: enumerations (except for
492  /// C++0x scoped enums), C++ linkage specifications, and C++0x
493  /// inline namespaces.
494  bool isTransparentContext() const;
495
496  bool Encloses(DeclContext *DC) const {
497    for (; DC; DC = DC->getParent())
498      if (DC == this)
499        return true;
500    return false;
501  }
502
503  /// getPrimaryContext - There may be many different
504  /// declarations of the same entity (including forward declarations
505  /// of classes, multiple definitions of namespaces, etc.), each with
506  /// a different set of declarations. This routine returns the
507  /// "primary" DeclContext structure, which will contain the
508  /// information needed to perform name lookup into this context.
509  DeclContext *getPrimaryContext();
510
511  /// getLookupContext - Retrieve the innermost non-transparent
512  /// context of this context, which corresponds to the innermost
513  /// location from which name lookup can find the entities in this
514  /// context.
515  DeclContext *getLookupContext() {
516    return const_cast<DeclContext *>(
517             const_cast<const DeclContext *>(this)->getLookupContext());
518  }
519  const DeclContext *getLookupContext() const;
520
521  /// getNextContext - If this is a DeclContext that may have other
522  /// DeclContexts that are semantically connected but syntactically
523  /// different, such as C++ namespaces, this routine retrieves the
524  /// next DeclContext in the link. Iteration through the chain of
525  /// DeclContexts should begin at the primary DeclContext and
526  /// continue until this function returns NULL. For example, given:
527  /// @code
528  /// namespace N {
529  ///   int x;
530  /// }
531  /// namespace N {
532  ///   int y;
533  /// }
534  /// @endcode
535  /// The first occurrence of namespace N will be the primary
536  /// DeclContext. Its getNextContext will return the second
537  /// occurrence of namespace N.
538  DeclContext *getNextContext();
539
540  /// decl_iterator - Iterates through the declarations stored
541  /// within this context.
542  class decl_iterator {
543    /// Current - The current declaration.
544    Decl *Current;
545
546  public:
547    typedef Decl*                     value_type;
548    typedef Decl*                     reference;
549    typedef Decl*                     pointer;
550    typedef std::forward_iterator_tag iterator_category;
551    typedef std::ptrdiff_t            difference_type;
552
553    decl_iterator() : Current(0) { }
554    explicit decl_iterator(Decl *C) : Current(C) { }
555
556    reference operator*() const { return Current; }
557    pointer operator->() const { return Current; }
558
559    decl_iterator& operator++();
560
561    decl_iterator operator++(int) {
562      decl_iterator tmp(*this);
563      ++(*this);
564      return tmp;
565    }
566
567    friend bool operator==(decl_iterator x, decl_iterator y) {
568      return x.Current == y.Current;
569    }
570    friend bool operator!=(decl_iterator x, decl_iterator y) {
571      return x.Current != y.Current;
572    }
573  };
574
575  /// decls_begin/decls_end - Iterate over the declarations stored in
576  /// this context.
577  decl_iterator decls_begin() const { return decl_iterator(FirstDecl); }
578  decl_iterator decls_end()   const { return decl_iterator(); }
579
580  /// specific_decl_iterator - Iterates over a subrange of
581  /// declarations stored in a DeclContext, providing only those that
582  /// are of type SpecificDecl (or a class derived from it). This
583  /// iterator is used, for example, to provide iteration over just
584  /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
585  template<typename SpecificDecl>
586  class specific_decl_iterator {
587    /// Current - The current, underlying declaration iterator, which
588    /// will either be NULL or will point to a declaration of
589    /// type SpecificDecl.
590    DeclContext::decl_iterator Current;
591
592    /// SkipToNextDecl - Advances the current position up to the next
593    /// declaration of type SpecificDecl that also meets the criteria
594    /// required by Acceptable.
595    void SkipToNextDecl() {
596      while (*Current && !isa<SpecificDecl>(*Current))
597        ++Current;
598    }
599
600  public:
601    typedef SpecificDecl* value_type;
602    typedef SpecificDecl* reference;
603    typedef SpecificDecl* pointer;
604    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
605      difference_type;
606    typedef std::forward_iterator_tag iterator_category;
607
608    specific_decl_iterator() : Current() { }
609
610    /// specific_decl_iterator - Construct a new iterator over a
611    /// subset of the declarations the range [C,
612    /// end-of-declarations). If A is non-NULL, it is a pointer to a
613    /// member function of SpecificDecl that should return true for
614    /// all of the SpecificDecl instances that will be in the subset
615    /// of iterators. For example, if you want Objective-C instance
616    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
617    /// &ObjCMethodDecl::isInstanceMethod.
618    explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
619      SkipToNextDecl();
620    }
621
622    reference operator*() const { return cast<SpecificDecl>(*Current); }
623    pointer operator->() const { return cast<SpecificDecl>(*Current); }
624
625    specific_decl_iterator& operator++() {
626      ++Current;
627      SkipToNextDecl();
628      return *this;
629    }
630
631    specific_decl_iterator operator++(int) {
632      specific_decl_iterator tmp(*this);
633      ++(*this);
634      return tmp;
635    }
636
637    friend bool
638    operator==(const specific_decl_iterator& x, const specific_decl_iterator& y) {
639      return x.Current == y.Current;
640    }
641
642    friend bool
643    operator!=(const specific_decl_iterator& x, const specific_decl_iterator& y) {
644      return x.Current != y.Current;
645    }
646  };
647
648  /// \brief Iterates over a filtered subrange of declarations stored
649  /// in a DeclContext.
650  ///
651  /// This iterator visits only those declarations that are of type
652  /// SpecificDecl (or a class derived from it) and that meet some
653  /// additional run-time criteria. This iterator is used, for
654  /// example, to provide access to the instance methods within an
655  /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
656  /// Acceptable = ObjCMethodDecl::isInstanceMethod).
657  template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
658  class filtered_decl_iterator {
659    /// Current - The current, underlying declaration iterator, which
660    /// will either be NULL or will point to a declaration of
661    /// type SpecificDecl.
662    DeclContext::decl_iterator Current;
663
664    /// SkipToNextDecl - Advances the current position up to the next
665    /// declaration of type SpecificDecl that also meets the criteria
666    /// required by Acceptable.
667    void SkipToNextDecl() {
668      while (*Current &&
669             (!isa<SpecificDecl>(*Current) ||
670              (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
671        ++Current;
672    }
673
674  public:
675    typedef SpecificDecl* value_type;
676    typedef SpecificDecl* reference;
677    typedef SpecificDecl* pointer;
678    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
679      difference_type;
680    typedef std::forward_iterator_tag iterator_category;
681
682    filtered_decl_iterator() : Current() { }
683
684    /// specific_decl_iterator - Construct a new iterator over a
685    /// subset of the declarations the range [C,
686    /// end-of-declarations). If A is non-NULL, it is a pointer to a
687    /// member function of SpecificDecl that should return true for
688    /// all of the SpecificDecl instances that will be in the subset
689    /// of iterators. For example, if you want Objective-C instance
690    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
691    /// &ObjCMethodDecl::isInstanceMethod.
692    explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
693      SkipToNextDecl();
694    }
695
696    reference operator*() const { return cast<SpecificDecl>(*Current); }
697    pointer operator->() const { return cast<SpecificDecl>(*Current); }
698
699    filtered_decl_iterator& operator++() {
700      ++Current;
701      SkipToNextDecl();
702      return *this;
703    }
704
705    filtered_decl_iterator operator++(int) {
706      filtered_decl_iterator tmp(*this);
707      ++(*this);
708      return tmp;
709    }
710
711    friend bool
712    operator==(const filtered_decl_iterator& x, const filtered_decl_iterator& y) {
713      return x.Current == y.Current;
714    }
715
716    friend bool
717    operator!=(const filtered_decl_iterator& x, const filtered_decl_iterator& y) {
718      return x.Current != y.Current;
719    }
720  };
721
722  /// @brief Add the declaration D into this context.
723  ///
724  /// This routine should be invoked when the declaration D has first
725  /// been declared, to place D into the context where it was
726  /// (lexically) defined. Every declaration must be added to one
727  /// (and only one!) context, where it can be visited via
728  /// [decls_begin(), decls_end()). Once a declaration has been added
729  /// to its lexical context, the corresponding DeclContext owns the
730  /// declaration.
731  ///
732  /// If D is also a NamedDecl, it will be made visible within its
733  /// semantic context via makeDeclVisibleInContext.
734  void addDecl(Decl *D);
735
736  /// lookup_iterator - An iterator that provides access to the results
737  /// of looking up a name within this context.
738  typedef NamedDecl **lookup_iterator;
739
740  /// lookup_const_iterator - An iterator that provides non-mutable
741  /// access to the results of lookup up a name within this context.
742  typedef NamedDecl * const * lookup_const_iterator;
743
744  typedef std::pair<lookup_iterator, lookup_iterator> lookup_result;
745  typedef std::pair<lookup_const_iterator, lookup_const_iterator>
746    lookup_const_result;
747
748  /// lookup - Find the declarations (if any) with the given Name in
749  /// this context. Returns a range of iterators that contains all of
750  /// the declarations with this name, with object, function, member,
751  /// and enumerator names preceding any tag name. Note that this
752  /// routine will not look into parent contexts.
753  lookup_result lookup(DeclarationName Name);
754  lookup_const_result lookup(DeclarationName Name) const;
755
756  /// @brief Makes a declaration visible within this context.
757  ///
758  /// This routine makes the declaration D visible to name lookup
759  /// within this context and, if this is a transparent context,
760  /// within its parent contexts up to the first enclosing
761  /// non-transparent context. Making a declaration visible within a
762  /// context does not transfer ownership of a declaration, and a
763  /// declaration can be visible in many contexts that aren't its
764  /// lexical context.
765  ///
766  /// If D is a redeclaration of an existing declaration that is
767  /// visible from this context, as determined by
768  /// NamedDecl::declarationReplaces, the previous declaration will be
769  /// replaced with D.
770  void makeDeclVisibleInContext(NamedDecl *D);
771
772  /// udir_iterator - Iterates through the using-directives stored
773  /// within this context.
774  typedef UsingDirectiveDecl * const * udir_iterator;
775
776  typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
777
778  udir_iterator_range getUsingDirectives() const;
779
780  udir_iterator using_directives_begin() const {
781    return getUsingDirectives().first;
782  }
783
784  udir_iterator using_directives_end() const {
785    return getUsingDirectives().second;
786  }
787
788  static bool classof(const Decl *D) {
789    switch (D->getKind()) {
790#define DECL_CONTEXT(Name) case Decl::Name:
791#include "clang/AST/DeclNodes.def"
792        return true;
793      default:
794        if (D->getKind() >= Decl::FunctionFirst &&
795            D->getKind() <= Decl::FunctionLast)
796          return true;
797        return false;
798    }
799  }
800  static bool classof(const DeclContext *D) { return true; }
801#define DECL_CONTEXT(Name) \
802  static bool classof(const Name##Decl *D) { return true; }
803#include "clang/AST/DeclNodes.def"
804
805private:
806  void buildLookup(DeclContext *DCtx);
807  void makeDeclVisibleInContextImpl(NamedDecl *D);
808
809  void EmitOutRec(llvm::Serializer& S) const;
810  void ReadOutRec(llvm::Deserializer& D, ASTContext& C);
811
812  friend class Decl;
813};
814
815template<> struct DeclContext::KindTrait<DeclContext> {
816  static Decl::Kind getKind(const DeclContext *D) { return D->DeclKind; }
817};
818
819inline bool Decl::isTemplateParameter() const {
820  return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm;
821}
822
823inline bool Decl::isDefinedOutsideFunctionOrMethod() const {
824  if (getDeclContext())
825    return !getDeclContext()->getLookupContext()->isFunctionOrMethod();
826  else
827    return true;
828}
829
830inline DeclContext::decl_iterator& DeclContext::decl_iterator::operator++() {
831  Current = getNextDeclInScope(Current);
832  return *this;
833}
834
835} // end clang.
836
837namespace llvm {
838
839/// Implement a isa_impl_wrap specialization to check whether a DeclContext is
840/// a specific Decl.
841template<class ToTy>
842struct isa_impl_wrap<ToTy,
843                     const ::clang::DeclContext,const ::clang::DeclContext> {
844  static bool doit(const ::clang::DeclContext &Val) {
845    return ToTy::classof(::clang::Decl::castFromDeclContext(&Val));
846  }
847};
848template<class ToTy>
849struct isa_impl_wrap<ToTy, ::clang::DeclContext, ::clang::DeclContext>
850  : public isa_impl_wrap<ToTy,
851                      const ::clang::DeclContext,const ::clang::DeclContext> {};
852
853/// Implement cast_convert_val for Decl -> DeclContext conversions.
854template<class FromTy>
855struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
856  static ::clang::DeclContext &doit(const FromTy &Val) {
857    return *FromTy::castToDeclContext(&Val);
858  }
859};
860
861template<class FromTy>
862struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
863  static ::clang::DeclContext *doit(const FromTy *Val) {
864    return FromTy::castToDeclContext(Val);
865  }
866};
867
868template<class FromTy>
869struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
870  static const ::clang::DeclContext &doit(const FromTy &Val) {
871    return *FromTy::castToDeclContext(&Val);
872  }
873};
874
875template<class FromTy>
876struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
877  static const ::clang::DeclContext *doit(const FromTy *Val) {
878    return FromTy::castToDeclContext(Val);
879  }
880};
881
882/// Implement cast_convert_val for DeclContext -> Decl conversions.
883template<class ToTy>
884struct cast_convert_val<ToTy,
885                        const ::clang::DeclContext,const ::clang::DeclContext> {
886  static ToTy &doit(const ::clang::DeclContext &Val) {
887    return *reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(&Val));
888  }
889};
890template<class ToTy>
891struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext>
892  : public cast_convert_val<ToTy,
893                      const ::clang::DeclContext,const ::clang::DeclContext> {};
894
895template<class ToTy>
896struct cast_convert_val<ToTy,
897                     const ::clang::DeclContext*, const ::clang::DeclContext*> {
898  static ToTy *doit(const ::clang::DeclContext *Val) {
899    return reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(Val));
900  }
901};
902template<class ToTy>
903struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*>
904  : public cast_convert_val<ToTy,
905                    const ::clang::DeclContext*,const ::clang::DeclContext*> {};
906
907} // end namespace llvm
908
909#endif
910