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