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