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