DeclBase.h revision ab88d97734f1260402a0c6a8f6b77bed7ed4e295
1//===-- DeclBase.h - Base Classes for representing declarations -*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the Decl and DeclContext interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECLBASE_H
15#define LLVM_CLANG_AST_DECLBASE_H
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/Type.h"
19// FIXME: Layering violation
20#include "clang/Parse/AccessSpecifier.h"
21#include "llvm/Support/PrettyStackTrace.h"
22#include "llvm/ADT/PointerUnion.h"
23
24namespace clang {
25class DeclContext;
26class TranslationUnitDecl;
27class NamespaceDecl;
28class UsingDirectiveDecl;
29class NamedDecl;
30class FunctionDecl;
31class CXXRecordDecl;
32class EnumDecl;
33class ObjCMethodDecl;
34class ObjCContainerDecl;
35class ObjCInterfaceDecl;
36class ObjCCategoryDecl;
37class ObjCProtocolDecl;
38class ObjCImplementationDecl;
39class ObjCCategoryImplDecl;
40class ObjCImplDecl;
41class LinkageSpecDecl;
42class BlockDecl;
43class DeclarationName;
44class CompoundStmt;
45}
46
47namespace llvm {
48// DeclContext* is only 4-byte aligned on 32-bit systems.
49template<>
50  class PointerLikeTypeTraits<clang::DeclContext*> {
51  typedef clang::DeclContext* PT;
52public:
53  static inline void *getAsVoidPointer(PT P) { return P; }
54  static inline PT getFromVoidPointer(void *P) {
55    return static_cast<PT>(P);
56  }
57  enum { NumLowBitsAvailable = 2 };
58};
59}
60
61namespace clang {
62
63/// Decl - This represents one declaration (or definition), e.g. a variable,
64/// typedef, function, struct, etc.
65///
66class Decl {
67public:
68  /// \brief Lists the kind of concrete classes of Decl.
69  enum Kind {
70#define DECL(Derived, Base) Derived,
71#define DECL_RANGE(CommonBase, Start, End) \
72    CommonBase##First = Start, CommonBase##Last = End,
73#define LAST_DECL_RANGE(CommonBase, Start, End) \
74    CommonBase##First = Start, CommonBase##Last = End
75#include "clang/AST/DeclNodes.def"
76  };
77
78  /// IdentifierNamespace - According to C99 6.2.3, there are four
79  /// namespaces, labels, tags, members and ordinary
80  /// identifiers. These are meant as bitmasks, so that searches in
81  /// C++ can look into the "tag" namespace during ordinary lookup. We
82  /// use additional namespaces for Objective-C entities.  We also
83  /// put C++ friend declarations (of previously-undeclared entities) in
84  /// shadow namespaces.
85  enum IdentifierNamespace {
86    IDNS_Label = 0x1,
87    IDNS_Tag = 0x2,
88    IDNS_Member = 0x4,
89    IDNS_Ordinary = 0x8,
90    IDNS_ObjCProtocol = 0x10,
91    IDNS_ObjCImplementation = 0x20,
92    IDNS_ObjCCategoryImpl = 0x40,
93    IDNS_OrdinaryFriend = 0x80,
94    IDNS_TagFriend = 0x100
95  };
96
97  /// ObjCDeclQualifier - Qualifier used on types in method declarations
98  /// for remote messaging. They are meant for the arguments though and
99  /// applied to the Decls (ObjCMethodDecl and ParmVarDecl).
100  enum ObjCDeclQualifier {
101    OBJC_TQ_None = 0x0,
102    OBJC_TQ_In = 0x1,
103    OBJC_TQ_Inout = 0x2,
104    OBJC_TQ_Out = 0x4,
105    OBJC_TQ_Bycopy = 0x8,
106    OBJC_TQ_Byref = 0x10,
107    OBJC_TQ_Oneway = 0x20
108  };
109
110private:
111  /// NextDeclInContext - The next declaration within the same lexical
112  /// DeclContext. These pointers form the linked list that is
113  /// traversed via DeclContext's decls_begin()/decls_end().
114  Decl *NextDeclInContext;
115
116  friend class DeclContext;
117
118  struct MultipleDC {
119    DeclContext *SemanticDC;
120    DeclContext *LexicalDC;
121  };
122
123
124  /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
125  /// For declarations that don't contain C++ scope specifiers, it contains
126  /// the DeclContext where the Decl was declared.
127  /// For declarations with C++ scope specifiers, it contains a MultipleDC*
128  /// with the context where it semantically belongs (SemanticDC) and the
129  /// context where it was lexically declared (LexicalDC).
130  /// e.g.:
131  ///
132  ///   namespace A {
133  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
134  ///   }
135  ///   void A::f(); // SemanticDC == namespace 'A'
136  ///                // LexicalDC == global namespace
137  llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
138
139  inline bool isInSemaDC() const    { return DeclCtx.is<DeclContext*>(); }
140  inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
141  inline MultipleDC *getMultipleDC() const {
142    return DeclCtx.get<MultipleDC*>();
143  }
144  inline DeclContext *getSemanticDC() const {
145    return DeclCtx.get<DeclContext*>();
146  }
147
148  /// Loc - The location that this decl.
149  SourceLocation Loc;
150
151  /// DeclKind - This indicates which class this is.
152  Kind DeclKind   :  8;
153
154  /// InvalidDecl - This indicates a semantic error occurred.
155  unsigned int InvalidDecl :  1;
156
157  /// HasAttrs - This indicates whether the decl has attributes or not.
158  unsigned int HasAttrs : 1;
159
160  /// Implicit - Whether this declaration was implicitly generated by
161  /// the implementation rather than explicitly written by the user.
162  bool Implicit : 1;
163
164  /// \brief Whether this declaration was "used", meaning that a definition is
165  /// required.
166  bool Used : 1;
167
168protected:
169  /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
170  unsigned IdentifierNamespace : 16;
171
172private:
173#ifndef NDEBUG
174  void CheckAccessDeclContext() const;
175#else
176  void CheckAccessDeclContext() const { }
177#endif
178
179protected:
180  /// Access - Used by C++ decls for the access specifier.
181  // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
182  unsigned Access : 2;
183  friend class CXXClassMemberWrapper;
184
185  Decl(Kind DK, DeclContext *DC, SourceLocation L)
186    : NextDeclInContext(0), DeclCtx(DC),
187      Loc(L), DeclKind(DK), InvalidDecl(0),
188      HasAttrs(false), Implicit(false), Used(false),
189      IdentifierNamespace(getIdentifierNamespaceForKind(DK)), Access(AS_none) {
190    if (Decl::CollectingStats()) addDeclKind(DK);
191  }
192
193  virtual ~Decl();
194
195public:
196
197  /// \brief Source range that this declaration covers.
198  virtual SourceRange getSourceRange() const {
199    return SourceRange(getLocation(), getLocation());
200  }
201  SourceLocation getLocStart() const { return getSourceRange().getBegin(); }
202  SourceLocation getLocEnd() const { return getSourceRange().getEnd(); }
203
204  SourceLocation getLocation() const { return Loc; }
205  void setLocation(SourceLocation L) { Loc = L; }
206
207  Kind getKind() const { return DeclKind; }
208  const char *getDeclKindName() const;
209
210  Decl *getNextDeclInContext() { return NextDeclInContext; }
211  const Decl *getNextDeclInContext() const { return NextDeclInContext; }
212
213  DeclContext *getDeclContext() {
214    if (isInSemaDC())
215      return getSemanticDC();
216    return getMultipleDC()->SemanticDC;
217  }
218  const DeclContext *getDeclContext() const {
219    return const_cast<Decl*>(this)->getDeclContext();
220  }
221
222  TranslationUnitDecl *getTranslationUnitDecl();
223  const TranslationUnitDecl *getTranslationUnitDecl() const {
224    return const_cast<Decl*>(this)->getTranslationUnitDecl();
225  }
226
227  ASTContext &getASTContext() const;
228
229  void setAccess(AccessSpecifier AS) {
230    Access = AS;
231    CheckAccessDeclContext();
232  }
233
234  AccessSpecifier getAccess() const {
235    CheckAccessDeclContext();
236    return AccessSpecifier(Access);
237  }
238
239  bool hasAttrs() const { return HasAttrs; }
240  void addAttr(Attr *attr);
241  const Attr *getAttrs() const {
242    if (!HasAttrs) return 0;  // common case, no attributes.
243    return getAttrsImpl();    // Uncommon case, out of line hash lookup.
244  }
245  void swapAttrs(Decl *D);
246  void invalidateAttrs();
247
248  template<typename T> const T *getAttr() const {
249    for (const Attr *attr = getAttrs(); attr; attr = attr->getNext())
250      if (const T *V = dyn_cast<T>(attr))
251        return V;
252    return 0;
253  }
254
255  template<typename T> bool hasAttr() const {
256    return getAttr<T>() != 0;
257  }
258
259  /// setInvalidDecl - Indicates the Decl had a semantic error. This
260  /// allows for graceful error recovery.
261  void setInvalidDecl(bool Invalid = true) { InvalidDecl = Invalid; }
262  bool isInvalidDecl() const { return (bool) InvalidDecl; }
263
264  /// isImplicit - Indicates whether the declaration was implicitly
265  /// generated by the implementation. If false, this declaration
266  /// was written explicitly in the source code.
267  bool isImplicit() const { return Implicit; }
268  void setImplicit(bool I = true) { Implicit = I; }
269
270  /// \brief Whether this declaration was used, meaning that a definition
271  /// is required.
272  bool isUsed() const { return Used; }
273  void setUsed(bool U = true) { Used = U; }
274
275  unsigned getIdentifierNamespace() const {
276    return IdentifierNamespace;
277  }
278  bool isInIdentifierNamespace(unsigned NS) const {
279    return getIdentifierNamespace() & NS;
280  }
281  static unsigned getIdentifierNamespaceForKind(Kind DK);
282
283
284  /// getLexicalDeclContext - The declaration context where this Decl was
285  /// lexically declared (LexicalDC). May be different from
286  /// getDeclContext() (SemanticDC).
287  /// e.g.:
288  ///
289  ///   namespace A {
290  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
291  ///   }
292  ///   void A::f(); // SemanticDC == namespace 'A'
293  ///                // LexicalDC == global namespace
294  DeclContext *getLexicalDeclContext() {
295    if (isInSemaDC())
296      return getSemanticDC();
297    return getMultipleDC()->LexicalDC;
298  }
299  const DeclContext *getLexicalDeclContext() const {
300    return const_cast<Decl*>(this)->getLexicalDeclContext();
301  }
302
303  bool isOutOfLine() const {
304    return getLexicalDeclContext() != getDeclContext();
305  }
306
307  /// setDeclContext - Set both the semantic and lexical DeclContext
308  /// to DC.
309  void setDeclContext(DeclContext *DC);
310
311  void setLexicalDeclContext(DeclContext *DC);
312
313  // isDefinedOutsideFunctionOrMethod - This predicate returns true if this
314  // scoped decl is defined outside the current function or method.  This is
315  // roughly global variables and functions, but also handles enums (which could
316  // be defined inside or outside a function etc).
317  bool isDefinedOutsideFunctionOrMethod() const;
318
319  /// \brief Retrieves the "canonical" declaration of the given declaration.
320  virtual Decl *getCanonicalDecl() { return this; }
321  const Decl *getCanonicalDecl() const {
322    return const_cast<Decl*>(this)->getCanonicalDecl();
323  }
324
325  /// \brief Whether this particular Decl is a canonical one.
326  bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
327
328protected:
329  /// \brief Returns the next redeclaration or itself if this is the only decl.
330  ///
331  /// Decl subclasses that can be redeclared should override this method so that
332  /// Decl::redecl_iterator can iterate over them.
333  virtual Decl *getNextRedeclaration() { return this; }
334
335public:
336  /// \brief Iterates through all the redeclarations of the same decl.
337  class redecl_iterator {
338    /// Current - The current declaration.
339    Decl *Current;
340    Decl *Starter;
341
342  public:
343    typedef Decl*                     value_type;
344    typedef Decl*                     reference;
345    typedef Decl*                     pointer;
346    typedef std::forward_iterator_tag iterator_category;
347    typedef std::ptrdiff_t            difference_type;
348
349    redecl_iterator() : Current(0) { }
350    explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
351
352    reference operator*() const { return Current; }
353    pointer operator->() const { return Current; }
354
355    redecl_iterator& operator++() {
356      assert(Current && "Advancing while iterator has reached end");
357      // Get either previous decl or latest decl.
358      Decl *Next = Current->getNextRedeclaration();
359      assert(Next && "Should return next redeclaration or itself, never null!");
360      Current = (Next != Starter ? Next : 0);
361      return *this;
362    }
363
364    redecl_iterator operator++(int) {
365      redecl_iterator tmp(*this);
366      ++(*this);
367      return tmp;
368    }
369
370    friend bool operator==(redecl_iterator x, redecl_iterator y) {
371      return x.Current == y.Current;
372    }
373    friend bool operator!=(redecl_iterator x, redecl_iterator y) {
374      return x.Current != y.Current;
375    }
376  };
377
378  /// \brief Returns iterator for all the redeclarations of the same decl.
379  /// It will iterate at least once (when this decl is the only one).
380  redecl_iterator redecls_begin() const {
381    return redecl_iterator(const_cast<Decl*>(this));
382  }
383  redecl_iterator redecls_end() const { return redecl_iterator(); }
384
385  /// getBody - If this Decl represents a declaration for a body of code,
386  ///  such as a function or method definition, this method returns the
387  ///  top-level Stmt* of that body.  Otherwise this method returns null.
388  virtual Stmt* getBody() const { return 0; }
389
390  /// getCompoundBody - Returns getBody(), dyn_casted to a CompoundStmt.
391  CompoundStmt* getCompoundBody() const;
392
393  /// getBodyRBrace - Gets the right brace of the body, if a body exists.
394  /// This works whether the body is a CompoundStmt or a CXXTryStmt.
395  SourceLocation getBodyRBrace() const;
396
397  // global temp stats (until we have a per-module visitor)
398  static void addDeclKind(Kind k);
399  static bool CollectingStats(bool Enable = false);
400  static void PrintStats();
401
402  /// isTemplateParameter - Determines whether this declaration is a
403  /// template parameter.
404  bool isTemplateParameter() const;
405
406  /// isTemplateParameter - Determines whether this declaration is a
407  /// template parameter pack.
408  bool isTemplateParameterPack() const;
409
410  /// \brief Whether this declaration is a function or function template.
411  bool isFunctionOrFunctionTemplate() const;
412
413  /// \brief Changes the namespace of this declaration to reflect that it's
414  /// the object of a friend declaration.
415  ///
416  /// These declarations appear in the lexical context of the friending
417  /// class, but in the semantic context of the actual entity.  This property
418  /// applies only to a specific decl object;  other redeclarations of the
419  /// same entity may not (and probably don't) share this property.
420  void setObjectOfFriendDecl(bool PreviouslyDeclared) {
421    unsigned OldNS = IdentifierNamespace;
422    assert((OldNS == IDNS_Tag || OldNS == IDNS_Ordinary)
423           && "unsupported namespace for undeclared friend");
424    if (!PreviouslyDeclared) IdentifierNamespace = 0;
425
426    if (OldNS == IDNS_Tag)
427      IdentifierNamespace |= IDNS_TagFriend;
428    else
429      IdentifierNamespace |= IDNS_OrdinaryFriend;
430  }
431
432  enum FriendObjectKind {
433    FOK_None, // not a friend object
434    FOK_Declared, // a friend of a previously-declared entity
435    FOK_Undeclared // a friend of a previously-undeclared entity
436  };
437
438  /// \brief Determines whether this declaration is the object of a
439  /// friend declaration and, if so, what kind.
440  ///
441  /// There is currently no direct way to find the associated FriendDecl.
442  FriendObjectKind getFriendObjectKind() const {
443    unsigned mask
444      = (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
445    if (!mask) return FOK_None;
446    return (mask & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared : FOK_Undeclared);
447  }
448
449  // Implement isa/cast/dyncast/etc.
450  static bool classof(const Decl *) { return true; }
451  static DeclContext *castToDeclContext(const Decl *);
452  static Decl *castFromDeclContext(const DeclContext *);
453
454  /// Destroy - Call destructors and release memory.
455  virtual void Destroy(ASTContext& C);
456
457  void print(llvm::raw_ostream &Out, unsigned Indentation = 0);
458  void print(llvm::raw_ostream &Out, const PrintingPolicy &Policy,
459             unsigned Indentation = 0);
460  static void printGroup(Decl** Begin, unsigned NumDecls,
461                         llvm::raw_ostream &Out, const PrintingPolicy &Policy,
462                         unsigned Indentation = 0);
463  void dump();
464
465private:
466  const Attr *getAttrsImpl() const;
467
468};
469
470/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
471/// doing something to a specific decl.
472class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
473  Decl *TheDecl;
474  SourceLocation Loc;
475  SourceManager &SM;
476  const char *Message;
477public:
478  PrettyStackTraceDecl(Decl *theDecl, SourceLocation L,
479                       SourceManager &sm, const char *Msg)
480  : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
481
482  virtual void print(llvm::raw_ostream &OS) const;
483};
484
485
486/// DeclContext - This is used only as base class of specific decl types that
487/// can act as declaration contexts. These decls are (only the top classes
488/// that directly derive from DeclContext are mentioned, not their subclasses):
489///
490///   TranslationUnitDecl
491///   NamespaceDecl
492///   FunctionDecl
493///   TagDecl
494///   ObjCMethodDecl
495///   ObjCContainerDecl
496///   LinkageSpecDecl
497///   BlockDecl
498///
499class DeclContext {
500  /// DeclKind - This indicates which class this is.
501  Decl::Kind DeclKind   :  8;
502
503  /// \brief Whether this declaration context also has some external
504  /// storage that contains additional declarations that are lexically
505  /// part of this context.
506  mutable bool ExternalLexicalStorage : 1;
507
508  /// \brief Whether this declaration context also has some external
509  /// storage that contains additional declarations that are visible
510  /// in this context.
511  mutable bool ExternalVisibleStorage : 1;
512
513  /// \brief Pointer to the data structure used to lookup declarations
514  /// within this context, which is a DenseMap<DeclarationName,
515  /// StoredDeclsList>.
516  mutable void* LookupPtr;
517
518  /// FirstDecl - The first declaration stored within this declaration
519  /// context.
520  mutable Decl *FirstDecl;
521
522  /// LastDecl - The last declaration stored within this declaration
523  /// context. FIXME: We could probably cache this value somewhere
524  /// outside of the DeclContext, to reduce the size of DeclContext by
525  /// another pointer.
526  mutable Decl *LastDecl;
527
528protected:
529   DeclContext(Decl::Kind K)
530     : DeclKind(K), ExternalLexicalStorage(false),
531       ExternalVisibleStorage(false), LookupPtr(0), FirstDecl(0),
532       LastDecl(0) { }
533
534  void DestroyDecls(ASTContext &C);
535
536public:
537  ~DeclContext();
538
539  Decl::Kind getDeclKind() const {
540    return DeclKind;
541  }
542  const char *getDeclKindName() const;
543
544  /// getParent - Returns the containing DeclContext.
545  DeclContext *getParent() {
546    return cast<Decl>(this)->getDeclContext();
547  }
548  const DeclContext *getParent() const {
549    return const_cast<DeclContext*>(this)->getParent();
550  }
551
552  /// getLexicalParent - Returns the containing lexical DeclContext. May be
553  /// different from getParent, e.g.:
554  ///
555  ///   namespace A {
556  ///      struct S;
557  ///   }
558  ///   struct A::S {}; // getParent() == namespace 'A'
559  ///                   // getLexicalParent() == translation unit
560  ///
561  DeclContext *getLexicalParent() {
562    return cast<Decl>(this)->getLexicalDeclContext();
563  }
564  const DeclContext *getLexicalParent() const {
565    return const_cast<DeclContext*>(this)->getLexicalParent();
566  }
567
568  ASTContext &getParentASTContext() const {
569    return cast<Decl>(this)->getASTContext();
570  }
571
572  bool isFunctionOrMethod() const {
573    switch (DeclKind) {
574    case Decl::Block:
575    case Decl::ObjCMethod:
576      return true;
577    default:
578      return DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast;
579    }
580  }
581
582  bool isFileContext() const {
583    return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
584  }
585
586  bool isTranslationUnit() const {
587    return DeclKind == Decl::TranslationUnit;
588  }
589
590  bool isRecord() const {
591    return DeclKind >= Decl::RecordFirst && DeclKind <= Decl::RecordLast;
592  }
593
594  bool isNamespace() const {
595    return DeclKind == Decl::Namespace;
596  }
597
598  /// \brief Determines whether this context is dependent on a
599  /// template parameter.
600  bool isDependentContext() const;
601
602  /// isTransparentContext - Determines whether this context is a
603  /// "transparent" context, meaning that the members declared in this
604  /// context are semantically declared in the nearest enclosing
605  /// non-transparent (opaque) context but are lexically declared in
606  /// this context. For example, consider the enumerators of an
607  /// enumeration type:
608  /// @code
609  /// enum E {
610  ///   Val1
611  /// };
612  /// @endcode
613  /// Here, E is a transparent context, so its enumerator (Val1) will
614  /// appear (semantically) that it is in the same context of E.
615  /// Examples of transparent contexts include: enumerations (except for
616  /// C++0x scoped enums), C++ linkage specifications, and C++0x
617  /// inline namespaces.
618  bool isTransparentContext() const;
619
620  /// \brief Determine whether this declaration context encloses the
621  /// declaration context DC.
622  bool Encloses(DeclContext *DC);
623
624  /// getPrimaryContext - There may be many different
625  /// declarations of the same entity (including forward declarations
626  /// of classes, multiple definitions of namespaces, etc.), each with
627  /// a different set of declarations. This routine returns the
628  /// "primary" DeclContext structure, which will contain the
629  /// information needed to perform name lookup into this context.
630  DeclContext *getPrimaryContext();
631
632  /// getLookupContext - Retrieve the innermost non-transparent
633  /// context of this context, which corresponds to the innermost
634  /// location from which name lookup can find the entities in this
635  /// context.
636  DeclContext *getLookupContext();
637  const DeclContext *getLookupContext() const {
638    return const_cast<DeclContext *>(this)->getLookupContext();
639  }
640
641  /// \brief Retrieve the nearest enclosing namespace context.
642  DeclContext *getEnclosingNamespaceContext();
643  const DeclContext *getEnclosingNamespaceContext() const {
644    return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
645  }
646
647  /// getNextContext - If this is a DeclContext that may have other
648  /// DeclContexts that are semantically connected but syntactically
649  /// different, such as C++ namespaces, this routine retrieves the
650  /// next DeclContext in the link. Iteration through the chain of
651  /// DeclContexts should begin at the primary DeclContext and
652  /// continue until this function returns NULL. For example, given:
653  /// @code
654  /// namespace N {
655  ///   int x;
656  /// }
657  /// namespace N {
658  ///   int y;
659  /// }
660  /// @endcode
661  /// The first occurrence of namespace N will be the primary
662  /// DeclContext. Its getNextContext will return the second
663  /// occurrence of namespace N.
664  DeclContext *getNextContext();
665
666  /// decl_iterator - Iterates through the declarations stored
667  /// within this context.
668  class decl_iterator {
669    /// Current - The current declaration.
670    Decl *Current;
671
672  public:
673    typedef Decl*                     value_type;
674    typedef Decl*                     reference;
675    typedef Decl*                     pointer;
676    typedef std::forward_iterator_tag iterator_category;
677    typedef std::ptrdiff_t            difference_type;
678
679    decl_iterator() : Current(0) { }
680    explicit decl_iterator(Decl *C) : Current(C) { }
681
682    reference operator*() const { return Current; }
683    pointer operator->() const { return Current; }
684
685    decl_iterator& operator++() {
686      Current = Current->getNextDeclInContext();
687      return *this;
688    }
689
690    decl_iterator operator++(int) {
691      decl_iterator tmp(*this);
692      ++(*this);
693      return tmp;
694    }
695
696    friend bool operator==(decl_iterator x, decl_iterator y) {
697      return x.Current == y.Current;
698    }
699    friend bool operator!=(decl_iterator x, decl_iterator y) {
700      return x.Current != y.Current;
701    }
702  };
703
704  /// decls_begin/decls_end - Iterate over the declarations stored in
705  /// this context.
706  decl_iterator decls_begin() const;
707  decl_iterator decls_end() const;
708  bool decls_empty() const;
709
710  /// specific_decl_iterator - Iterates over a subrange of
711  /// declarations stored in a DeclContext, providing only those that
712  /// are of type SpecificDecl (or a class derived from it). This
713  /// iterator is used, for example, to provide iteration over just
714  /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
715  template<typename SpecificDecl>
716  class specific_decl_iterator {
717    /// Current - The current, underlying declaration iterator, which
718    /// will either be NULL or will point to a declaration of
719    /// type SpecificDecl.
720    DeclContext::decl_iterator Current;
721
722    /// SkipToNextDecl - Advances the current position up to the next
723    /// declaration of type SpecificDecl that also meets the criteria
724    /// required by Acceptable.
725    void SkipToNextDecl() {
726      while (*Current && !isa<SpecificDecl>(*Current))
727        ++Current;
728    }
729
730  public:
731    typedef SpecificDecl* value_type;
732    typedef SpecificDecl* reference;
733    typedef SpecificDecl* pointer;
734    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
735      difference_type;
736    typedef std::forward_iterator_tag iterator_category;
737
738    specific_decl_iterator() : Current() { }
739
740    /// specific_decl_iterator - Construct a new iterator over a
741    /// subset of the declarations the range [C,
742    /// end-of-declarations). If A is non-NULL, it is a pointer to a
743    /// member function of SpecificDecl that should return true for
744    /// all of the SpecificDecl instances that will be in the subset
745    /// of iterators. For example, if you want Objective-C instance
746    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
747    /// &ObjCMethodDecl::isInstanceMethod.
748    explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
749      SkipToNextDecl();
750    }
751
752    reference operator*() const { return cast<SpecificDecl>(*Current); }
753    pointer operator->() const { return cast<SpecificDecl>(*Current); }
754
755    specific_decl_iterator& operator++() {
756      ++Current;
757      SkipToNextDecl();
758      return *this;
759    }
760
761    specific_decl_iterator operator++(int) {
762      specific_decl_iterator tmp(*this);
763      ++(*this);
764      return tmp;
765    }
766
767    friend bool
768    operator==(const specific_decl_iterator& x, const specific_decl_iterator& y) {
769      return x.Current == y.Current;
770    }
771
772    friend bool
773    operator!=(const specific_decl_iterator& x, const specific_decl_iterator& y) {
774      return x.Current != y.Current;
775    }
776  };
777
778  /// \brief Iterates over a filtered subrange of declarations stored
779  /// in a DeclContext.
780  ///
781  /// This iterator visits only those declarations that are of type
782  /// SpecificDecl (or a class derived from it) and that meet some
783  /// additional run-time criteria. This iterator is used, for
784  /// example, to provide access to the instance methods within an
785  /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
786  /// Acceptable = ObjCMethodDecl::isInstanceMethod).
787  template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
788  class filtered_decl_iterator {
789    /// Current - The current, underlying declaration iterator, which
790    /// will either be NULL or will point to a declaration of
791    /// type SpecificDecl.
792    DeclContext::decl_iterator Current;
793
794    /// SkipToNextDecl - Advances the current position up to the next
795    /// declaration of type SpecificDecl that also meets the criteria
796    /// required by Acceptable.
797    void SkipToNextDecl() {
798      while (*Current &&
799             (!isa<SpecificDecl>(*Current) ||
800              (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
801        ++Current;
802    }
803
804  public:
805    typedef SpecificDecl* value_type;
806    typedef SpecificDecl* reference;
807    typedef SpecificDecl* pointer;
808    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
809      difference_type;
810    typedef std::forward_iterator_tag iterator_category;
811
812    filtered_decl_iterator() : Current() { }
813
814    /// specific_decl_iterator - Construct a new iterator over a
815    /// subset of the declarations the range [C,
816    /// end-of-declarations). If A is non-NULL, it is a pointer to a
817    /// member function of SpecificDecl that should return true for
818    /// all of the SpecificDecl instances that will be in the subset
819    /// of iterators. For example, if you want Objective-C instance
820    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
821    /// &ObjCMethodDecl::isInstanceMethod.
822    explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
823      SkipToNextDecl();
824    }
825
826    reference operator*() const { return cast<SpecificDecl>(*Current); }
827    pointer operator->() const { return cast<SpecificDecl>(*Current); }
828
829    filtered_decl_iterator& operator++() {
830      ++Current;
831      SkipToNextDecl();
832      return *this;
833    }
834
835    filtered_decl_iterator operator++(int) {
836      filtered_decl_iterator tmp(*this);
837      ++(*this);
838      return tmp;
839    }
840
841    friend bool
842    operator==(const filtered_decl_iterator& x, const filtered_decl_iterator& y) {
843      return x.Current == y.Current;
844    }
845
846    friend bool
847    operator!=(const filtered_decl_iterator& x, const filtered_decl_iterator& y) {
848      return x.Current != y.Current;
849    }
850  };
851
852  /// @brief Add the declaration D into this context.
853  ///
854  /// This routine should be invoked when the declaration D has first
855  /// been declared, to place D into the context where it was
856  /// (lexically) defined. Every declaration must be added to one
857  /// (and only one!) context, where it can be visited via
858  /// [decls_begin(), decls_end()). Once a declaration has been added
859  /// to its lexical context, the corresponding DeclContext owns the
860  /// declaration.
861  ///
862  /// If D is also a NamedDecl, it will be made visible within its
863  /// semantic context via makeDeclVisibleInContext.
864  void addDecl(Decl *D);
865
866  /// @brief Add the declaration D to this context without modifying
867  /// any lookup tables.
868  ///
869  /// This is useful for some operations in dependent contexts where
870  /// the semantic context might not be dependent;  this basically
871  /// only happens with friends.
872  void addHiddenDecl(Decl *D);
873
874  /// lookup_iterator - An iterator that provides access to the results
875  /// of looking up a name within this context.
876  typedef NamedDecl **lookup_iterator;
877
878  /// lookup_const_iterator - An iterator that provides non-mutable
879  /// access to the results of lookup up a name within this context.
880  typedef NamedDecl * const * lookup_const_iterator;
881
882  typedef std::pair<lookup_iterator, lookup_iterator> lookup_result;
883  typedef std::pair<lookup_const_iterator, lookup_const_iterator>
884    lookup_const_result;
885
886  /// lookup - Find the declarations (if any) with the given Name in
887  /// this context. Returns a range of iterators that contains all of
888  /// the declarations with this name, with object, function, member,
889  /// and enumerator names preceding any tag name. Note that this
890  /// routine will not look into parent contexts.
891  lookup_result lookup(DeclarationName Name);
892  lookup_const_result lookup(DeclarationName Name) const;
893
894  /// @brief Makes a declaration visible within this context.
895  ///
896  /// This routine makes the declaration D visible to name lookup
897  /// within this context and, if this is a transparent context,
898  /// within its parent contexts up to the first enclosing
899  /// non-transparent context. Making a declaration visible within a
900  /// context does not transfer ownership of a declaration, and a
901  /// declaration can be visible in many contexts that aren't its
902  /// lexical context.
903  ///
904  /// If D is a redeclaration of an existing declaration that is
905  /// visible from this context, as determined by
906  /// NamedDecl::declarationReplaces, the previous declaration will be
907  /// replaced with D.
908  ///
909  /// @param Recoverable true if it's okay to not add this decl to
910  /// the lookup tables because it can be easily recovered by walking
911  /// the declaration chains.
912  void makeDeclVisibleInContext(NamedDecl *D, bool Recoverable = true);
913
914  /// udir_iterator - Iterates through the using-directives stored
915  /// within this context.
916  typedef UsingDirectiveDecl * const * udir_iterator;
917
918  typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
919
920  udir_iterator_range getUsingDirectives() const;
921
922  udir_iterator using_directives_begin() const {
923    return getUsingDirectives().first;
924  }
925
926  udir_iterator using_directives_end() const {
927    return getUsingDirectives().second;
928  }
929
930  // Low-level accessors
931
932  /// \brief Retrieve the internal representation of the lookup structure.
933  void* getLookupPtr() const { return LookupPtr; }
934
935  /// \brief Whether this DeclContext has external storage containing
936  /// additional declarations that are lexically in this context.
937  bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
938
939  /// \brief State whether this DeclContext has external storage for
940  /// declarations lexically in this context.
941  void setHasExternalLexicalStorage(bool ES = true) {
942    ExternalLexicalStorage = ES;
943  }
944
945  /// \brief Whether this DeclContext has external storage containing
946  /// additional declarations that are visible in this context.
947  bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
948
949  /// \brief State whether this DeclContext has external storage for
950  /// declarations visible in this context.
951  void setHasExternalVisibleStorage(bool ES = true) {
952    ExternalVisibleStorage = ES;
953  }
954
955  static bool classof(const Decl *D);
956  static bool classof(const DeclContext *D) { return true; }
957#define DECL_CONTEXT(Name) \
958  static bool classof(const Name##Decl *D) { return true; }
959#include "clang/AST/DeclNodes.def"
960
961private:
962  void LoadLexicalDeclsFromExternalStorage() const;
963  void LoadVisibleDeclsFromExternalStorage() const;
964
965  void buildLookup(DeclContext *DCtx);
966  void makeDeclVisibleInContextImpl(NamedDecl *D);
967};
968
969inline bool Decl::isTemplateParameter() const {
970  return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm;
971}
972
973inline bool Decl::isDefinedOutsideFunctionOrMethod() const {
974  if (getDeclContext())
975    return !getDeclContext()->getLookupContext()->isFunctionOrMethod();
976  return true;
977}
978
979} // end clang.
980
981namespace llvm {
982
983/// Implement a isa_impl_wrap specialization to check whether a DeclContext is
984/// a specific Decl.
985template<class ToTy>
986struct isa_impl_wrap<ToTy,
987                     const ::clang::DeclContext,const ::clang::DeclContext> {
988  static bool doit(const ::clang::DeclContext &Val) {
989    return ToTy::classof(::clang::Decl::castFromDeclContext(&Val));
990  }
991};
992template<class ToTy>
993struct isa_impl_wrap<ToTy, ::clang::DeclContext, ::clang::DeclContext>
994  : public isa_impl_wrap<ToTy,
995                      const ::clang::DeclContext,const ::clang::DeclContext> {};
996
997/// Implement cast_convert_val for Decl -> DeclContext conversions.
998template<class FromTy>
999struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1000  static ::clang::DeclContext &doit(const FromTy &Val) {
1001    return *FromTy::castToDeclContext(&Val);
1002  }
1003};
1004
1005template<class FromTy>
1006struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1007  static ::clang::DeclContext *doit(const FromTy *Val) {
1008    return FromTy::castToDeclContext(Val);
1009  }
1010};
1011
1012template<class FromTy>
1013struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1014  static const ::clang::DeclContext &doit(const FromTy &Val) {
1015    return *FromTy::castToDeclContext(&Val);
1016  }
1017};
1018
1019template<class FromTy>
1020struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1021  static const ::clang::DeclContext *doit(const FromTy *Val) {
1022    return FromTy::castToDeclContext(Val);
1023  }
1024};
1025
1026/// Implement cast_convert_val for DeclContext -> Decl conversions.
1027template<class ToTy>
1028struct cast_convert_val<ToTy,
1029                        const ::clang::DeclContext,const ::clang::DeclContext> {
1030  static ToTy &doit(const ::clang::DeclContext &Val) {
1031    return *reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(&Val));
1032  }
1033};
1034template<class ToTy>
1035struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext>
1036  : public cast_convert_val<ToTy,
1037                      const ::clang::DeclContext,const ::clang::DeclContext> {};
1038
1039template<class ToTy>
1040struct cast_convert_val<ToTy,
1041                     const ::clang::DeclContext*, const ::clang::DeclContext*> {
1042  static ToTy *doit(const ::clang::DeclContext *Val) {
1043    return reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(Val));
1044  }
1045};
1046template<class ToTy>
1047struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*>
1048  : public cast_convert_val<ToTy,
1049                    const ::clang::DeclContext*,const ::clang::DeclContext*> {};
1050
1051} // end namespace llvm
1052
1053#endif
1054