DeclBase.h revision 9aeed32282fe8a775c24c01c923717ca86695685
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  bool isInAnonymousNamespace() const;
228
229  ASTContext &getASTContext() const;
230
231  void setAccess(AccessSpecifier AS) {
232    Access = AS;
233    CheckAccessDeclContext();
234  }
235
236  AccessSpecifier getAccess() const {
237    CheckAccessDeclContext();
238    return AccessSpecifier(Access);
239  }
240
241  bool hasAttrs() const { return HasAttrs; }
242  void addAttr(Attr *attr);
243  const Attr *getAttrs() const {
244    if (!HasAttrs) return 0;  // common case, no attributes.
245    return getAttrsImpl();    // Uncommon case, out of line hash lookup.
246  }
247  void swapAttrs(Decl *D);
248  void invalidateAttrs();
249
250  template<typename T> const T *getAttr() const {
251    for (const Attr *attr = getAttrs(); attr; attr = attr->getNext())
252      if (const T *V = dyn_cast<T>(attr))
253        return V;
254    return 0;
255  }
256
257  template<typename T> bool hasAttr() const {
258    return getAttr<T>() != 0;
259  }
260
261  /// setInvalidDecl - Indicates the Decl had a semantic error. This
262  /// allows for graceful error recovery.
263  void setInvalidDecl(bool Invalid = true) { InvalidDecl = Invalid; }
264  bool isInvalidDecl() const { return (bool) InvalidDecl; }
265
266  /// isImplicit - Indicates whether the declaration was implicitly
267  /// generated by the implementation. If false, this declaration
268  /// was written explicitly in the source code.
269  bool isImplicit() const { return Implicit; }
270  void setImplicit(bool I = true) { Implicit = I; }
271
272  /// \brief Whether this declaration was used, meaning that a definition
273  /// is required.
274  bool isUsed() const { return Used; }
275  void setUsed(bool U = true) { Used = U; }
276
277  unsigned getIdentifierNamespace() const {
278    return IdentifierNamespace;
279  }
280  bool isInIdentifierNamespace(unsigned NS) const {
281    return getIdentifierNamespace() & NS;
282  }
283  static unsigned getIdentifierNamespaceForKind(Kind DK);
284
285
286  /// getLexicalDeclContext - The declaration context where this Decl was
287  /// lexically declared (LexicalDC). May be different from
288  /// getDeclContext() (SemanticDC).
289  /// e.g.:
290  ///
291  ///   namespace A {
292  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
293  ///   }
294  ///   void A::f(); // SemanticDC == namespace 'A'
295  ///                // LexicalDC == global namespace
296  DeclContext *getLexicalDeclContext() {
297    if (isInSemaDC())
298      return getSemanticDC();
299    return getMultipleDC()->LexicalDC;
300  }
301  const DeclContext *getLexicalDeclContext() const {
302    return const_cast<Decl*>(this)->getLexicalDeclContext();
303  }
304
305  bool isOutOfLine() const {
306    return getLexicalDeclContext() != getDeclContext();
307  }
308
309  /// setDeclContext - Set both the semantic and lexical DeclContext
310  /// to DC.
311  void setDeclContext(DeclContext *DC);
312
313  void setLexicalDeclContext(DeclContext *DC);
314
315  // isDefinedOutsideFunctionOrMethod - This predicate returns true if this
316  // scoped decl is defined outside the current function or method.  This is
317  // roughly global variables and functions, but also handles enums (which could
318  // be defined inside or outside a function etc).
319  bool isDefinedOutsideFunctionOrMethod() const;
320
321  /// \brief Retrieves the "canonical" declaration of the given declaration.
322  virtual Decl *getCanonicalDecl() { return this; }
323  const Decl *getCanonicalDecl() const {
324    return const_cast<Decl*>(this)->getCanonicalDecl();
325  }
326
327  /// \brief Whether this particular Decl is a canonical one.
328  bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
329
330protected:
331  /// \brief Returns the next redeclaration or itself if this is the only decl.
332  ///
333  /// Decl subclasses that can be redeclared should override this method so that
334  /// Decl::redecl_iterator can iterate over them.
335  virtual Decl *getNextRedeclaration() { return this; }
336
337public:
338  /// \brief Iterates through all the redeclarations of the same decl.
339  class redecl_iterator {
340    /// Current - The current declaration.
341    Decl *Current;
342    Decl *Starter;
343
344  public:
345    typedef Decl*                     value_type;
346    typedef Decl*                     reference;
347    typedef Decl*                     pointer;
348    typedef std::forward_iterator_tag iterator_category;
349    typedef std::ptrdiff_t            difference_type;
350
351    redecl_iterator() : Current(0) { }
352    explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
353
354    reference operator*() const { return Current; }
355    pointer operator->() const { return Current; }
356
357    redecl_iterator& operator++() {
358      assert(Current && "Advancing while iterator has reached end");
359      // Get either previous decl or latest decl.
360      Decl *Next = Current->getNextRedeclaration();
361      assert(Next && "Should return next redeclaration or itself, never null!");
362      Current = (Next != Starter ? Next : 0);
363      return *this;
364    }
365
366    redecl_iterator operator++(int) {
367      redecl_iterator tmp(*this);
368      ++(*this);
369      return tmp;
370    }
371
372    friend bool operator==(redecl_iterator x, redecl_iterator y) {
373      return x.Current == y.Current;
374    }
375    friend bool operator!=(redecl_iterator x, redecl_iterator y) {
376      return x.Current != y.Current;
377    }
378  };
379
380  /// \brief Returns iterator for all the redeclarations of the same decl.
381  /// It will iterate at least once (when this decl is the only one).
382  redecl_iterator redecls_begin() const {
383    return redecl_iterator(const_cast<Decl*>(this));
384  }
385  redecl_iterator redecls_end() const { return redecl_iterator(); }
386
387  /// getBody - If this Decl represents a declaration for a body of code,
388  ///  such as a function or method definition, this method returns the
389  ///  top-level Stmt* of that body.  Otherwise this method returns null.
390  virtual Stmt* getBody() const { return 0; }
391
392  /// getCompoundBody - Returns getBody(), dyn_casted to a CompoundStmt.
393  CompoundStmt* getCompoundBody() const;
394
395  /// getBodyRBrace - Gets the right brace of the body, if a body exists.
396  /// This works whether the body is a CompoundStmt or a CXXTryStmt.
397  SourceLocation getBodyRBrace() const;
398
399  // global temp stats (until we have a per-module visitor)
400  static void addDeclKind(Kind k);
401  static bool CollectingStats(bool Enable = false);
402  static void PrintStats();
403
404  /// isTemplateParameter - Determines whether this declaration is a
405  /// template parameter.
406  bool isTemplateParameter() const;
407
408  /// isTemplateParameter - Determines whether this declaration is a
409  /// template parameter pack.
410  bool isTemplateParameterPack() const;
411
412  /// \brief Whether this declaration is a function or function template.
413  bool isFunctionOrFunctionTemplate() const;
414
415  /// \brief Changes the namespace of this declaration to reflect that it's
416  /// the object of a friend declaration.
417  ///
418  /// These declarations appear in the lexical context of the friending
419  /// class, but in the semantic context of the actual entity.  This property
420  /// applies only to a specific decl object;  other redeclarations of the
421  /// same entity may not (and probably don't) share this property.
422  void setObjectOfFriendDecl(bool PreviouslyDeclared) {
423    unsigned OldNS = IdentifierNamespace;
424    assert((OldNS == IDNS_Tag || OldNS == IDNS_Ordinary ||
425            OldNS == (IDNS_Tag | IDNS_Ordinary))
426           && "unsupported namespace for undeclared friend");
427    if (!PreviouslyDeclared) IdentifierNamespace = 0;
428
429    if (OldNS == IDNS_Tag)
430      IdentifierNamespace |= IDNS_TagFriend;
431    else
432      IdentifierNamespace |= IDNS_OrdinaryFriend;
433  }
434
435  enum FriendObjectKind {
436    FOK_None, // not a friend object
437    FOK_Declared, // a friend of a previously-declared entity
438    FOK_Undeclared // a friend of a previously-undeclared entity
439  };
440
441  /// \brief Determines whether this declaration is the object of a
442  /// friend declaration and, if so, what kind.
443  ///
444  /// There is currently no direct way to find the associated FriendDecl.
445  FriendObjectKind getFriendObjectKind() const {
446    unsigned mask
447      = (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
448    if (!mask) return FOK_None;
449    return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ?
450              FOK_Declared : FOK_Undeclared);
451  }
452
453  // Implement isa/cast/dyncast/etc.
454  static bool classof(const Decl *) { return true; }
455  static DeclContext *castToDeclContext(const Decl *);
456  static Decl *castFromDeclContext(const DeclContext *);
457
458  /// Destroy - Call destructors and release memory.
459  virtual void Destroy(ASTContext& C);
460
461  void print(llvm::raw_ostream &Out, unsigned Indentation = 0) const;
462  void print(llvm::raw_ostream &Out, const PrintingPolicy &Policy,
463             unsigned Indentation = 0) const;
464  static void printGroup(Decl** Begin, unsigned NumDecls,
465                         llvm::raw_ostream &Out, const PrintingPolicy &Policy,
466                         unsigned Indentation = 0);
467  void dump() const;
468
469private:
470  const Attr *getAttrsImpl() const;
471
472};
473
474/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
475/// doing something to a specific decl.
476class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
477  Decl *TheDecl;
478  SourceLocation Loc;
479  SourceManager &SM;
480  const char *Message;
481public:
482  PrettyStackTraceDecl(Decl *theDecl, SourceLocation L,
483                       SourceManager &sm, const char *Msg)
484  : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
485
486  virtual void print(llvm::raw_ostream &OS) const;
487};
488
489
490/// DeclContext - This is used only as base class of specific decl types that
491/// can act as declaration contexts. These decls are (only the top classes
492/// that directly derive from DeclContext are mentioned, not their subclasses):
493///
494///   TranslationUnitDecl
495///   NamespaceDecl
496///   FunctionDecl
497///   TagDecl
498///   ObjCMethodDecl
499///   ObjCContainerDecl
500///   LinkageSpecDecl
501///   BlockDecl
502///
503class DeclContext {
504  /// DeclKind - This indicates which class this is.
505  Decl::Kind DeclKind   :  8;
506
507  /// \brief Whether this declaration context also has some external
508  /// storage that contains additional declarations that are lexically
509  /// part of this context.
510  mutable bool ExternalLexicalStorage : 1;
511
512  /// \brief Whether this declaration context also has some external
513  /// storage that contains additional declarations that are visible
514  /// in this context.
515  mutable bool ExternalVisibleStorage : 1;
516
517  /// \brief Pointer to the data structure used to lookup declarations
518  /// within this context, which is a DenseMap<DeclarationName,
519  /// StoredDeclsList>.
520  mutable void* LookupPtr;
521
522  /// FirstDecl - The first declaration stored within this declaration
523  /// context.
524  mutable Decl *FirstDecl;
525
526  /// LastDecl - The last declaration stored within this declaration
527  /// context. FIXME: We could probably cache this value somewhere
528  /// outside of the DeclContext, to reduce the size of DeclContext by
529  /// another pointer.
530  mutable Decl *LastDecl;
531
532protected:
533   DeclContext(Decl::Kind K)
534     : DeclKind(K), ExternalLexicalStorage(false),
535       ExternalVisibleStorage(false), LookupPtr(0), FirstDecl(0),
536       LastDecl(0) { }
537
538  void DestroyDecls(ASTContext &C);
539
540public:
541  ~DeclContext();
542
543  Decl::Kind getDeclKind() const {
544    return DeclKind;
545  }
546  const char *getDeclKindName() const;
547
548  /// getParent - Returns the containing DeclContext.
549  DeclContext *getParent() {
550    return cast<Decl>(this)->getDeclContext();
551  }
552  const DeclContext *getParent() const {
553    return const_cast<DeclContext*>(this)->getParent();
554  }
555
556  /// getLexicalParent - Returns the containing lexical DeclContext. May be
557  /// different from getParent, e.g.:
558  ///
559  ///   namespace A {
560  ///      struct S;
561  ///   }
562  ///   struct A::S {}; // getParent() == namespace 'A'
563  ///                   // getLexicalParent() == translation unit
564  ///
565  DeclContext *getLexicalParent() {
566    return cast<Decl>(this)->getLexicalDeclContext();
567  }
568  const DeclContext *getLexicalParent() const {
569    return const_cast<DeclContext*>(this)->getLexicalParent();
570  }
571
572  DeclContext *getLookupParent();
573
574  const DeclContext *getLookupParent() const {
575    return const_cast<DeclContext*>(this)->getLookupParent();
576  }
577
578  ASTContext &getParentASTContext() const {
579    return cast<Decl>(this)->getASTContext();
580  }
581
582  bool isFunctionOrMethod() const {
583    switch (DeclKind) {
584    case Decl::Block:
585    case Decl::ObjCMethod:
586      return true;
587    default:
588      return DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast;
589    }
590  }
591
592  bool isFileContext() const {
593    return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
594  }
595
596  bool isTranslationUnit() const {
597    return DeclKind == Decl::TranslationUnit;
598  }
599
600  bool isRecord() const {
601    return DeclKind >= Decl::RecordFirst && DeclKind <= Decl::RecordLast;
602  }
603
604  bool isNamespace() const {
605    return DeclKind == Decl::Namespace;
606  }
607
608  /// \brief Determines whether this context is dependent on a
609  /// template parameter.
610  bool isDependentContext() const;
611
612  /// isTransparentContext - Determines whether this context is a
613  /// "transparent" context, meaning that the members declared in this
614  /// context are semantically declared in the nearest enclosing
615  /// non-transparent (opaque) context but are lexically declared in
616  /// this context. For example, consider the enumerators of an
617  /// enumeration type:
618  /// @code
619  /// enum E {
620  ///   Val1
621  /// };
622  /// @endcode
623  /// Here, E is a transparent context, so its enumerator (Val1) will
624  /// appear (semantically) that it is in the same context of E.
625  /// Examples of transparent contexts include: enumerations (except for
626  /// C++0x scoped enums), C++ linkage specifications, and C++0x
627  /// inline namespaces.
628  bool isTransparentContext() const;
629
630  /// \brief Determine whether this declaration context is equivalent
631  /// to the declaration context DC.
632  bool Equals(DeclContext *DC) {
633    return this->getPrimaryContext() == DC->getPrimaryContext();
634  }
635
636  /// \brief Determine whether this declaration context encloses the
637  /// declaration context DC.
638  bool Encloses(DeclContext *DC);
639
640  /// getPrimaryContext - There may be many different
641  /// declarations of the same entity (including forward declarations
642  /// of classes, multiple definitions of namespaces, etc.), each with
643  /// a different set of declarations. This routine returns the
644  /// "primary" DeclContext structure, which will contain the
645  /// information needed to perform name lookup into this context.
646  DeclContext *getPrimaryContext();
647
648  /// getLookupContext - Retrieve the innermost non-transparent
649  /// context of this context, which corresponds to the innermost
650  /// location from which name lookup can find the entities in this
651  /// context.
652  DeclContext *getLookupContext();
653  const DeclContext *getLookupContext() const {
654    return const_cast<DeclContext *>(this)->getLookupContext();
655  }
656
657  /// \brief Retrieve the nearest enclosing namespace context.
658  DeclContext *getEnclosingNamespaceContext();
659  const DeclContext *getEnclosingNamespaceContext() const {
660    return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
661  }
662
663  /// getNextContext - If this is a DeclContext that may have other
664  /// DeclContexts that are semantically connected but syntactically
665  /// different, such as C++ namespaces, this routine retrieves the
666  /// next DeclContext in the link. Iteration through the chain of
667  /// DeclContexts should begin at the primary DeclContext and
668  /// continue until this function returns NULL. For example, given:
669  /// @code
670  /// namespace N {
671  ///   int x;
672  /// }
673  /// namespace N {
674  ///   int y;
675  /// }
676  /// @endcode
677  /// The first occurrence of namespace N will be the primary
678  /// DeclContext. Its getNextContext will return the second
679  /// occurrence of namespace N.
680  DeclContext *getNextContext();
681
682  /// decl_iterator - Iterates through the declarations stored
683  /// within this context.
684  class decl_iterator {
685    /// Current - The current declaration.
686    Decl *Current;
687
688  public:
689    typedef Decl*                     value_type;
690    typedef Decl*                     reference;
691    typedef Decl*                     pointer;
692    typedef std::forward_iterator_tag iterator_category;
693    typedef std::ptrdiff_t            difference_type;
694
695    decl_iterator() : Current(0) { }
696    explicit decl_iterator(Decl *C) : Current(C) { }
697
698    reference operator*() const { return Current; }
699    pointer operator->() const { return Current; }
700
701    decl_iterator& operator++() {
702      Current = Current->getNextDeclInContext();
703      return *this;
704    }
705
706    decl_iterator operator++(int) {
707      decl_iterator tmp(*this);
708      ++(*this);
709      return tmp;
710    }
711
712    friend bool operator==(decl_iterator x, decl_iterator y) {
713      return x.Current == y.Current;
714    }
715    friend bool operator!=(decl_iterator x, decl_iterator y) {
716      return x.Current != y.Current;
717    }
718  };
719
720  /// decls_begin/decls_end - Iterate over the declarations stored in
721  /// this context.
722  decl_iterator decls_begin() const;
723  decl_iterator decls_end() const;
724  bool decls_empty() const;
725
726  /// specific_decl_iterator - Iterates over a subrange of
727  /// declarations stored in a DeclContext, providing only those that
728  /// are of type SpecificDecl (or a class derived from it). This
729  /// iterator is used, for example, to provide iteration over just
730  /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
731  template<typename SpecificDecl>
732  class specific_decl_iterator {
733    /// Current - The current, underlying declaration iterator, which
734    /// will either be NULL or will point to a declaration of
735    /// type SpecificDecl.
736    DeclContext::decl_iterator Current;
737
738    /// SkipToNextDecl - Advances the current position up to the next
739    /// declaration of type SpecificDecl that also meets the criteria
740    /// required by Acceptable.
741    void SkipToNextDecl() {
742      while (*Current && !isa<SpecificDecl>(*Current))
743        ++Current;
744    }
745
746  public:
747    typedef SpecificDecl* value_type;
748    typedef SpecificDecl* reference;
749    typedef SpecificDecl* pointer;
750    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
751      difference_type;
752    typedef std::forward_iterator_tag iterator_category;
753
754    specific_decl_iterator() : Current() { }
755
756    /// specific_decl_iterator - Construct a new iterator over a
757    /// subset of the declarations the range [C,
758    /// end-of-declarations). If A is non-NULL, it is a pointer to a
759    /// member function of SpecificDecl that should return true for
760    /// all of the SpecificDecl instances that will be in the subset
761    /// of iterators. For example, if you want Objective-C instance
762    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
763    /// &ObjCMethodDecl::isInstanceMethod.
764    explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
765      SkipToNextDecl();
766    }
767
768    reference operator*() const { return cast<SpecificDecl>(*Current); }
769    pointer operator->() const { return cast<SpecificDecl>(*Current); }
770
771    specific_decl_iterator& operator++() {
772      ++Current;
773      SkipToNextDecl();
774      return *this;
775    }
776
777    specific_decl_iterator operator++(int) {
778      specific_decl_iterator tmp(*this);
779      ++(*this);
780      return tmp;
781    }
782
783    friend bool
784    operator==(const specific_decl_iterator& x, const specific_decl_iterator& y) {
785      return x.Current == y.Current;
786    }
787
788    friend bool
789    operator!=(const specific_decl_iterator& x, const specific_decl_iterator& y) {
790      return x.Current != y.Current;
791    }
792  };
793
794  /// \brief Iterates over a filtered subrange of declarations stored
795  /// in a DeclContext.
796  ///
797  /// This iterator visits only those declarations that are of type
798  /// SpecificDecl (or a class derived from it) and that meet some
799  /// additional run-time criteria. This iterator is used, for
800  /// example, to provide access to the instance methods within an
801  /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
802  /// Acceptable = ObjCMethodDecl::isInstanceMethod).
803  template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
804  class filtered_decl_iterator {
805    /// Current - The current, underlying declaration iterator, which
806    /// will either be NULL or will point to a declaration of
807    /// type SpecificDecl.
808    DeclContext::decl_iterator Current;
809
810    /// SkipToNextDecl - Advances the current position up to the next
811    /// declaration of type SpecificDecl that also meets the criteria
812    /// required by Acceptable.
813    void SkipToNextDecl() {
814      while (*Current &&
815             (!isa<SpecificDecl>(*Current) ||
816              (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
817        ++Current;
818    }
819
820  public:
821    typedef SpecificDecl* value_type;
822    typedef SpecificDecl* reference;
823    typedef SpecificDecl* pointer;
824    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
825      difference_type;
826    typedef std::forward_iterator_tag iterator_category;
827
828    filtered_decl_iterator() : Current() { }
829
830    /// specific_decl_iterator - Construct a new iterator over a
831    /// subset of the declarations the range [C,
832    /// end-of-declarations). If A is non-NULL, it is a pointer to a
833    /// member function of SpecificDecl that should return true for
834    /// all of the SpecificDecl instances that will be in the subset
835    /// of iterators. For example, if you want Objective-C instance
836    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
837    /// &ObjCMethodDecl::isInstanceMethod.
838    explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
839      SkipToNextDecl();
840    }
841
842    reference operator*() const { return cast<SpecificDecl>(*Current); }
843    pointer operator->() const { return cast<SpecificDecl>(*Current); }
844
845    filtered_decl_iterator& operator++() {
846      ++Current;
847      SkipToNextDecl();
848      return *this;
849    }
850
851    filtered_decl_iterator operator++(int) {
852      filtered_decl_iterator tmp(*this);
853      ++(*this);
854      return tmp;
855    }
856
857    friend bool
858    operator==(const filtered_decl_iterator& x, const filtered_decl_iterator& y) {
859      return x.Current == y.Current;
860    }
861
862    friend bool
863    operator!=(const filtered_decl_iterator& x, const filtered_decl_iterator& y) {
864      return x.Current != y.Current;
865    }
866  };
867
868  /// @brief Add the declaration D into this context.
869  ///
870  /// This routine should be invoked when the declaration D has first
871  /// been declared, to place D into the context where it was
872  /// (lexically) defined. Every declaration must be added to one
873  /// (and only one!) context, where it can be visited via
874  /// [decls_begin(), decls_end()). Once a declaration has been added
875  /// to its lexical context, the corresponding DeclContext owns the
876  /// declaration.
877  ///
878  /// If D is also a NamedDecl, it will be made visible within its
879  /// semantic context via makeDeclVisibleInContext.
880  void addDecl(Decl *D);
881
882  /// @brief Add the declaration D to this context without modifying
883  /// any lookup tables.
884  ///
885  /// This is useful for some operations in dependent contexts where
886  /// the semantic context might not be dependent;  this basically
887  /// only happens with friends.
888  void addHiddenDecl(Decl *D);
889
890  /// lookup_iterator - An iterator that provides access to the results
891  /// of looking up a name within this context.
892  typedef NamedDecl **lookup_iterator;
893
894  /// lookup_const_iterator - An iterator that provides non-mutable
895  /// access to the results of lookup up a name within this context.
896  typedef NamedDecl * const * lookup_const_iterator;
897
898  typedef std::pair<lookup_iterator, lookup_iterator> lookup_result;
899  typedef std::pair<lookup_const_iterator, lookup_const_iterator>
900    lookup_const_result;
901
902  /// lookup - Find the declarations (if any) with the given Name in
903  /// this context. Returns a range of iterators that contains all of
904  /// the declarations with this name, with object, function, member,
905  /// and enumerator names preceding any tag name. Note that this
906  /// routine will not look into parent contexts.
907  lookup_result lookup(DeclarationName Name);
908  lookup_const_result lookup(DeclarationName Name) const;
909
910  /// @brief Makes a declaration visible within this context.
911  ///
912  /// This routine makes the declaration D visible to name lookup
913  /// within this context and, if this is a transparent context,
914  /// within its parent contexts up to the first enclosing
915  /// non-transparent context. Making a declaration visible within a
916  /// context does not transfer ownership of a declaration, and a
917  /// declaration can be visible in many contexts that aren't its
918  /// lexical context.
919  ///
920  /// If D is a redeclaration of an existing declaration that is
921  /// visible from this context, as determined by
922  /// NamedDecl::declarationReplaces, the previous declaration will be
923  /// replaced with D.
924  ///
925  /// @param Recoverable true if it's okay to not add this decl to
926  /// the lookup tables because it can be easily recovered by walking
927  /// the declaration chains.
928  void makeDeclVisibleInContext(NamedDecl *D, bool Recoverable = true);
929
930  /// udir_iterator - Iterates through the using-directives stored
931  /// within this context.
932  typedef UsingDirectiveDecl * const * udir_iterator;
933
934  typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
935
936  udir_iterator_range getUsingDirectives() const;
937
938  udir_iterator using_directives_begin() const {
939    return getUsingDirectives().first;
940  }
941
942  udir_iterator using_directives_end() const {
943    return getUsingDirectives().second;
944  }
945
946  // Low-level accessors
947
948  /// \brief Retrieve the internal representation of the lookup structure.
949  void* getLookupPtr() const { return LookupPtr; }
950
951  /// \brief Whether this DeclContext has external storage containing
952  /// additional declarations that are lexically in this context.
953  bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
954
955  /// \brief State whether this DeclContext has external storage for
956  /// declarations lexically in this context.
957  void setHasExternalLexicalStorage(bool ES = true) {
958    ExternalLexicalStorage = ES;
959  }
960
961  /// \brief Whether this DeclContext has external storage containing
962  /// additional declarations that are visible in this context.
963  bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
964
965  /// \brief State whether this DeclContext has external storage for
966  /// declarations visible in this context.
967  void setHasExternalVisibleStorage(bool ES = true) {
968    ExternalVisibleStorage = ES;
969  }
970
971  static bool classof(const Decl *D);
972  static bool classof(const DeclContext *D) { return true; }
973#define DECL_CONTEXT(Name) \
974  static bool classof(const Name##Decl *D) { return true; }
975#include "clang/AST/DeclNodes.def"
976
977private:
978  void LoadLexicalDeclsFromExternalStorage() const;
979  void LoadVisibleDeclsFromExternalStorage() const;
980
981  void buildLookup(DeclContext *DCtx);
982  void makeDeclVisibleInContextImpl(NamedDecl *D);
983};
984
985inline bool Decl::isTemplateParameter() const {
986  return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm;
987}
988
989inline bool Decl::isDefinedOutsideFunctionOrMethod() const {
990  if (getDeclContext())
991    return !getDeclContext()->getLookupContext()->isFunctionOrMethod();
992  return true;
993}
994
995} // end clang.
996
997namespace llvm {
998
999/// Implement a isa_impl_wrap specialization to check whether a DeclContext is
1000/// a specific Decl.
1001template<class ToTy>
1002struct isa_impl_wrap<ToTy,
1003                     const ::clang::DeclContext,const ::clang::DeclContext> {
1004  static bool doit(const ::clang::DeclContext &Val) {
1005    return ToTy::classof(::clang::Decl::castFromDeclContext(&Val));
1006  }
1007};
1008template<class ToTy>
1009struct isa_impl_wrap<ToTy, ::clang::DeclContext, ::clang::DeclContext>
1010  : public isa_impl_wrap<ToTy,
1011                      const ::clang::DeclContext,const ::clang::DeclContext> {};
1012
1013/// Implement cast_convert_val for Decl -> DeclContext conversions.
1014template<class FromTy>
1015struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1016  static ::clang::DeclContext &doit(const FromTy &Val) {
1017    return *FromTy::castToDeclContext(&Val);
1018  }
1019};
1020
1021template<class FromTy>
1022struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1023  static ::clang::DeclContext *doit(const FromTy *Val) {
1024    return FromTy::castToDeclContext(Val);
1025  }
1026};
1027
1028template<class FromTy>
1029struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1030  static const ::clang::DeclContext &doit(const FromTy &Val) {
1031    return *FromTy::castToDeclContext(&Val);
1032  }
1033};
1034
1035template<class FromTy>
1036struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1037  static const ::clang::DeclContext *doit(const FromTy *Val) {
1038    return FromTy::castToDeclContext(Val);
1039  }
1040};
1041
1042/// Implement cast_convert_val for DeclContext -> Decl conversions.
1043template<class ToTy>
1044struct cast_convert_val<ToTy,
1045                        const ::clang::DeclContext,const ::clang::DeclContext> {
1046  static ToTy &doit(const ::clang::DeclContext &Val) {
1047    return *reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(&Val));
1048  }
1049};
1050template<class ToTy>
1051struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext>
1052  : public cast_convert_val<ToTy,
1053                      const ::clang::DeclContext,const ::clang::DeclContext> {};
1054
1055template<class ToTy>
1056struct cast_convert_val<ToTy,
1057                     const ::clang::DeclContext*, const ::clang::DeclContext*> {
1058  static ToTy *doit(const ::clang::DeclContext *Val) {
1059    return reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(Val));
1060  }
1061};
1062template<class ToTy>
1063struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*>
1064  : public cast_convert_val<ToTy,
1065                    const ::clang::DeclContext*,const ::clang::DeclContext*> {};
1066
1067} // end namespace llvm
1068
1069#endif
1070