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