DeclBase.h revision efe38bdea21953f89c1504cfd1c63bee5f15b1b6
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 "clang/Basic/SourceLocation.h"
22#include "llvm/ADT/PointerIntPair.h"
23
24namespace clang {
25class DeclContext;
26class TranslationUnitDecl;
27class NamespaceDecl;
28class NamedDecl;
29class FunctionDecl;
30class CXXRecordDecl;
31class EnumDecl;
32class ObjCMethodDecl;
33class ObjCInterfaceDecl;
34class ObjCCategoryDecl;
35class ObjCProtocolDecl;
36class ObjCImplementationDecl;
37class ObjCCategoryImplDecl;
38class LinkageSpecDecl;
39class BlockDecl;
40class DeclarationName;
41
42/// Decl - This represents one declaration (or definition), e.g. a variable,
43/// typedef, function, struct, etc.
44///
45class Decl {
46public:
47  enum Kind {
48    // This lists the concrete classes of Decl in order of the inheritance
49    // hierarchy.  This allows us to do efficient classof tests based on the
50    // enums below.   The commented out names are abstract class names.
51    // [DeclContext] indicates that the class also inherits from DeclContext.
52
53    // Decl
54         TranslationUnit,  // [DeclContext]
55    //   NamedDecl
56           OverloadedFunction,
57           Field,
58             ObjCIvar,
59             ObjCAtDefsField,
60           Namespace,  // [DeclContext]
61    //     TypeDecl
62             Typedef,
63    //       TagDecl // [DeclContext]
64               Enum,
65               Record,
66                 CXXRecord,
67 	     TemplateTypeParm,
68    //     ValueDecl
69             EnumConstant,
70             Function,  // [DeclContext]
71               CXXMethod,
72                 CXXConstructor,
73                 CXXDestructor,
74                 CXXConversion,
75             Var,
76               ImplicitParam,
77               CXXClassVar,
78               ParmVar,
79                 OriginalParmVar,
80  	       NonTypeTemplateParm,
81           ObjCMethod,  // [DeclContext]
82           ObjCContainer, // [DeclContext]
83             ObjCCategory,
84             ObjCProtocol,
85             ObjCInterface,
86             ObjCCategoryImpl,  // [DeclContext]
87             ObjCProperty,
88             ObjCCompatibleAlias,
89         LinkageSpec, // [DeclContext]
90         ObjCPropertyImpl,
91         ObjCImplementation, // [DeclContext]
92         ObjCForwardProtocol,
93         ObjCClass,
94         FileScopeAsm,
95         Block, // [DeclContext]
96
97    // For each non-leaf class, we now define a mapping to the first/last member
98    // of the class, to allow efficient classof.
99    NamedFirst    = OverloadedFunction, NamedLast   = ObjCCompatibleAlias,
100    ObjCContainerFirst = ObjCContainer, ObjCContainerLast = ObjCInterface,
101    FieldFirst         = Field        , FieldLast     = ObjCAtDefsField,
102    TypeFirst          = Typedef      , TypeLast      = TemplateTypeParm,
103    TagFirst           = Enum         , TagLast       = CXXRecord,
104    RecordFirst        = Record       , RecordLast    = CXXRecord,
105    ValueFirst         = EnumConstant , ValueLast     = NonTypeTemplateParm,
106    FunctionFirst      = Function     , FunctionLast  = CXXConversion,
107    VarFirst           = Var          , VarLast       = NonTypeTemplateParm
108  };
109
110  /// IdentifierNamespace - According to C99 6.2.3, there are four namespaces,
111  /// labels, tags, members and ordinary identifiers. These are meant
112  /// as bitmasks, so that searches in C++ can look into the "tag" namespace
113  /// during ordinary lookup.
114  enum IdentifierNamespace {
115    IDNS_Label = 0x1,
116    IDNS_Tag = 0x2,
117    IDNS_Member = 0x4,
118    IDNS_Ordinary = 0x8
119  };
120
121  /// ObjCDeclQualifier - Qualifier used on types in method declarations
122  /// for remote messaging. They are meant for the arguments though and
123  /// applied to the Decls (ObjCMethodDecl and ParmVarDecl).
124  enum ObjCDeclQualifier {
125    OBJC_TQ_None = 0x0,
126    OBJC_TQ_In = 0x1,
127    OBJC_TQ_Inout = 0x2,
128    OBJC_TQ_Out = 0x4,
129    OBJC_TQ_Bycopy = 0x8,
130    OBJC_TQ_Byref = 0x10,
131    OBJC_TQ_Oneway = 0x20
132  };
133
134private:
135  /// Loc - The location that this decl.
136  SourceLocation Loc;
137
138  /// NextDeclarator - If this decl was part of a multi-declarator declaration,
139  /// such as "int X, Y, *Z;" this indicates Decl for the next declarator.
140  Decl *NextDeclarator;
141
142  /// NextDeclInScope - The next declaration within the same lexical
143  /// DeclContext. These pointers form the linked list that is
144  /// traversed via DeclContext's decls_begin()/decls_end().
145  /// FIXME: If NextDeclarator is non-NULL, will it always be the same
146  /// as NextDeclInScope? If so, we can use a
147  /// PointerIntPair<Decl*, 1> to make Decl smaller.
148  Decl *NextDeclInScope;
149
150  friend class DeclContext;
151
152  /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
153  /// For declarations that don't contain C++ scope specifiers, it contains
154  /// the DeclContext where the Decl was declared.
155  /// For declarations with C++ scope specifiers, it contains a MultipleDC*
156  /// with the context where it semantically belongs (SemanticDC) and the
157  /// context where it was lexically declared (LexicalDC).
158  /// e.g.:
159  ///
160  ///   namespace A {
161  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
162  ///   }
163  ///   void A::f(); // SemanticDC == namespace 'A'
164  ///                // LexicalDC == global namespace
165  uintptr_t DeclCtx;
166
167  struct MultipleDC {
168    DeclContext *SemanticDC;
169    DeclContext *LexicalDC;
170  };
171
172  inline bool isInSemaDC() const { return (DeclCtx & 0x1) == 0; }
173  inline bool isOutOfSemaDC() const { return (DeclCtx & 0x1) != 0; }
174  inline MultipleDC *getMultipleDC() const {
175    return reinterpret_cast<MultipleDC*>(DeclCtx & ~0x1);
176  }
177
178  /// DeclKind - This indicates which class this is.
179  Kind DeclKind   :  8;
180
181  /// InvalidDecl - This indicates a semantic error occurred.
182  unsigned int InvalidDecl :  1;
183
184  /// HasAttrs - This indicates whether the decl has attributes or not.
185  unsigned int HasAttrs : 1;
186
187  /// Implicit - Whether this declaration was implicitly generated by
188  /// the implementation rather than explicitly written by the user.
189  bool Implicit : 1;
190
191protected:
192  /// Access - Used by C++ decls for the access specifier.
193  // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
194  unsigned Access : 2;
195  friend class CXXClassMemberWrapper;
196
197  Decl(Kind DK, DeclContext *DC, SourceLocation L)
198    : Loc(L), NextDeclarator(0), NextDeclInScope(0),
199      DeclCtx(reinterpret_cast<uintptr_t>(DC)), DeclKind(DK), InvalidDecl(0),
200      HasAttrs(false), Implicit(false) {
201    if (Decl::CollectingStats()) addDeclKind(DK);
202  }
203
204  virtual ~Decl();
205
206  /// setDeclContext - Set both the semantic and lexical DeclContext
207  /// to DC.
208  void setDeclContext(DeclContext *DC);
209
210public:
211  SourceLocation getLocation() const { return Loc; }
212  void setLocation(SourceLocation L) { Loc = L; }
213
214  Kind getKind() const { return DeclKind; }
215  const char *getDeclKindName() const;
216
217  const DeclContext *getDeclContext() const {
218    if (isInSemaDC())
219      return reinterpret_cast<DeclContext*>(DeclCtx);
220    return getMultipleDC()->SemanticDC;
221  }
222  DeclContext *getDeclContext() {
223    return const_cast<DeclContext*>(
224                         const_cast<const Decl*>(this)->getDeclContext());
225  }
226
227  void setAccess(AccessSpecifier AS) { Access = AS; }
228  AccessSpecifier getAccess() const { return AccessSpecifier(Access); }
229
230  void addAttr(Attr *attr);
231  const Attr *getAttrs() const;
232  void swapAttrs(Decl *D);
233  void invalidateAttrs();
234
235  template<typename T> const T *getAttr() const {
236    for (const Attr *attr = getAttrs(); attr; attr = attr->getNext())
237      if (const T *V = dyn_cast<T>(attr))
238        return V;
239
240    return 0;
241  }
242
243  /// setInvalidDecl - Indicates the Decl had a semantic error. This
244  /// allows for graceful error recovery.
245  void setInvalidDecl() { InvalidDecl = 1; }
246  bool isInvalidDecl() const { return (bool) InvalidDecl; }
247
248  /// isImplicit - Indicates whether the declaration was implicitly
249  /// generated by the implementation. If false, this declaration
250  /// was written explicitly in the source code.
251  bool isImplicit() const { return Implicit; }
252  void setImplicit(bool I = true) { Implicit = I; }
253
254  IdentifierNamespace getIdentifierNamespace() const {
255    switch (DeclKind) {
256    default:
257      if (DeclKind >= FunctionFirst && DeclKind <= FunctionLast)
258        return IDNS_Ordinary;
259      assert(0 && "Unknown decl kind!");
260    case OverloadedFunction:
261    case Typedef:
262    case EnumConstant:
263    case Var:
264    case CXXClassVar:
265    case ImplicitParam:
266    case ParmVar:
267    case OriginalParmVar:
268    case NonTypeTemplateParm:
269    case ObjCMethod:
270    case ObjCContainer:
271    case ObjCCategory:
272    case ObjCProtocol:
273    case ObjCInterface:
274    case ObjCCategoryImpl:
275    case ObjCProperty:
276    case ObjCCompatibleAlias:
277      return IDNS_Ordinary;
278
279    case Field:
280    case ObjCAtDefsField:
281    case ObjCIvar:
282      return IDNS_Member;
283
284    case Record:
285    case CXXRecord:
286    case Enum:
287    case TemplateTypeParm:
288      return IDNS_Tag;
289
290    case Namespace:
291      return IdentifierNamespace(IDNS_Tag | IDNS_Ordinary);
292    }
293  }
294
295  bool isInIdentifierNamespace(unsigned NS) const {
296    return getIdentifierNamespace() & NS;
297  }
298
299  /// getLexicalDeclContext - The declaration context where this Decl was
300  /// lexically declared (LexicalDC). May be different from
301  /// getDeclContext() (SemanticDC).
302  /// e.g.:
303  ///
304  ///   namespace A {
305  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
306  ///   }
307  ///   void A::f(); // SemanticDC == namespace 'A'
308  ///                // LexicalDC == global namespace
309  const DeclContext *getLexicalDeclContext() const {
310    if (isInSemaDC())
311      return reinterpret_cast<DeclContext*>(DeclCtx);
312    return getMultipleDC()->LexicalDC;
313  }
314  DeclContext *getLexicalDeclContext() {
315    return const_cast<DeclContext*>(
316                  const_cast<const Decl*>(this)->getLexicalDeclContext());
317  }
318
319  void setLexicalDeclContext(DeclContext *DC);
320
321  /// getNextDeclarator - If this decl was part of a multi-declarator
322  /// declaration, such as "int X, Y, *Z;" this returns the decl for the next
323  /// declarator.  Otherwise it returns null.
324  Decl *getNextDeclarator() { return NextDeclarator; }
325  const Decl *getNextDeclarator() const { return NextDeclarator; }
326  void setNextDeclarator(Decl *N) { NextDeclarator = N; }
327
328  // isDefinedOutsideFunctionOrMethod - This predicate returns true if this
329  // scoped decl is defined outside the current function or method.  This is
330  // roughly global variables and functions, but also handles enums (which could
331  // be defined inside or outside a function etc).
332  bool isDefinedOutsideFunctionOrMethod() const;
333
334  // getBody - If this Decl represents a declaration for a body of code,
335  //  such as a function or method definition, this method returns the top-level
336  //  Stmt* of that body.  Otherwise this method returns null.
337  virtual Stmt* getBody() const { return 0; }
338
339  // global temp stats (until we have a per-module visitor)
340  static void addDeclKind(Kind k);
341  static bool CollectingStats(bool Enable = false);
342  static void PrintStats();
343
344  /// isTemplateParameter - Determines whether this declartion is a
345  /// template parameter.
346  bool isTemplateParameter() const;
347
348  // Implement isa/cast/dyncast/etc.
349  static bool classof(const Decl *) { return true; }
350  static DeclContext *castToDeclContext(const Decl *);
351  static Decl *castFromDeclContext(const DeclContext *);
352
353  /// Emit - Serialize this Decl to Bitcode.
354  void Emit(llvm::Serializer& S) const;
355
356  /// Create - Deserialize a Decl from Bitcode.
357  static Decl* Create(llvm::Deserializer& D, ASTContext& C);
358
359  /// Destroy - Call destructors and release memory.
360  virtual void Destroy(ASTContext& C);
361
362protected:
363  /// EmitImpl - Provides the subclass-specific serialization logic for
364  ///   serializing out a decl.
365  virtual void EmitImpl(llvm::Serializer& S) const {
366    // FIXME: This will eventually be a pure virtual function.
367    assert (false && "Not implemented.");
368  }
369};
370
371/// DeclContext - This is used only as base class of specific decl types that
372/// can act as declaration contexts. These decls are:
373///
374///   TranslationUnitDecl
375///   NamespaceDecl
376///   FunctionDecl
377///   RecordDecl/CXXRecordDecl
378///   EnumDecl
379///   ObjCMethodDecl
380///   ObjCInterfaceDecl
381///   LinkageSpecDecl
382///   BlockDecl
383class DeclContext {
384  /// DeclKind - This indicates which class this is.
385  Decl::Kind DeclKind   :  8;
386
387  /// LookupPtrKind - Describes what kind of pointer LookupPtr
388  /// actually is.
389  enum LookupPtrKind {
390    /// LookupIsMap - Indicates that LookupPtr is actually a map.
391    LookupIsMap = 7
392  };
393
394  /// LookupPtr - Pointer to a data structure used to lookup
395  /// declarations within this context. If the context contains fewer
396  /// than seven declarations, the number of declarations is provided
397  /// in the 3 lowest-order bits and the upper bits are treated as a
398  /// pointer to an array of NamedDecl pointers. If the context
399  /// contains seven or more declarations, the upper bits are treated
400  /// as a pointer to a DenseMap<DeclarationName, std::vector<NamedDecl*>>.
401  /// FIXME: We need a better data structure for this.
402  llvm::PointerIntPair<void*, 3> LookupPtr;
403
404  /// FirstDecl - The first declaration stored within this declaration
405  /// context.
406  Decl *FirstDecl;
407
408  /// LastDecl - The last declaration stored within this declaration
409  /// context. FIXME: We could probably cache this value somewhere
410  /// outside of the DeclContext, to reduce the size of DeclContext by
411  /// another pointer.
412  Decl *LastDecl;
413
414  // Used in the CastTo template to get the DeclKind
415  // from a Decl or a DeclContext. DeclContext doesn't have a getKind() method
416  // to avoid 'ambiguous access' compiler errors.
417  template<typename T> struct KindTrait {
418    static Decl::Kind getKind(const T *D) { return D->getKind(); }
419  };
420
421  // Used only by the ToDecl and FromDecl methods
422  template<typename To, typename From>
423  static To *CastTo(const From *D) {
424    Decl::Kind DK = KindTrait<From>::getKind(D);
425    switch(DK) {
426      case Decl::TranslationUnit:
427        return static_cast<TranslationUnitDecl*>(const_cast<From*>(D));
428      case Decl::Namespace:
429        return static_cast<NamespaceDecl*>(const_cast<From*>(D));
430      case Decl::Enum:
431        return static_cast<EnumDecl*>(const_cast<From*>(D));
432      case Decl::Record:
433        return static_cast<RecordDecl*>(const_cast<From*>(D));
434      case Decl::CXXRecord:
435        return static_cast<CXXRecordDecl*>(const_cast<From*>(D));
436      case Decl::ObjCMethod:
437        return static_cast<ObjCMethodDecl*>(const_cast<From*>(D));
438      case Decl::ObjCInterface:
439        return static_cast<ObjCInterfaceDecl*>(const_cast<From*>(D));
440      case Decl::ObjCCategory:
441        return static_cast<ObjCCategoryDecl*>(const_cast<From*>(D));
442      case Decl::ObjCProtocol:
443        return static_cast<ObjCProtocolDecl*>(const_cast<From*>(D));
444      case Decl::ObjCImplementation:
445        return static_cast<ObjCImplementationDecl*>(const_cast<From*>(D));
446      case Decl::ObjCCategoryImpl:
447        return static_cast<ObjCCategoryImplDecl*>(const_cast<From*>(D));
448      case Decl::LinkageSpec:
449        return static_cast<LinkageSpecDecl*>(const_cast<From*>(D));
450      case Decl::Block:
451        return static_cast<BlockDecl*>(const_cast<From*>(D));
452      default:
453        if (DK >= Decl::FunctionFirst && DK <= Decl::FunctionLast)
454          return static_cast<FunctionDecl*>(const_cast<From*>(D));
455
456        assert(false && "a decl that inherits DeclContext isn't handled");
457        return 0;
458    }
459  }
460
461  /// isLookupMap - Determine if the lookup structure is a
462  /// DenseMap. Othewise, it is an array.
463  bool isLookupMap() const { return LookupPtr.getInt() == LookupIsMap; }
464
465  static Decl *getNextDeclInScope(Decl *D) { return D->NextDeclInScope; }
466
467protected:
468   DeclContext(Decl::Kind K)
469     : DeclKind(K), LookupPtr(), FirstDecl(0), LastDecl(0) { }
470
471  void DestroyDecls(ASTContext &C);
472
473public:
474  ~DeclContext();
475
476  Decl::Kind getDeclKind() const {
477    return DeclKind;
478  }
479  const char *getDeclKindName() const;
480
481  /// getParent - Returns the containing DeclContext if this is a Decl,
482  /// else returns NULL.
483  const DeclContext *getParent() const;
484  DeclContext *getParent() {
485    return const_cast<DeclContext*>(
486                             const_cast<const DeclContext*>(this)->getParent());
487  }
488
489  /// getLexicalParent - Returns the containing lexical DeclContext. May be
490  /// different from getParent, e.g.:
491  ///
492  ///   namespace A {
493  ///      struct S;
494  ///   }
495  ///   struct A::S {}; // getParent() == namespace 'A'
496  ///                   // getLexicalParent() == translation unit
497  ///
498  const DeclContext *getLexicalParent() const;
499  DeclContext *getLexicalParent() {
500    return const_cast<DeclContext*>(
501                      const_cast<const DeclContext*>(this)->getLexicalParent());
502  }
503
504  bool isFunctionOrMethod() const {
505    switch (DeclKind) {
506      case Decl::Block:
507      case Decl::ObjCMethod:
508        return true;
509
510      default:
511       if (DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast)
512         return true;
513        return false;
514    }
515  }
516
517  bool isFileContext() const {
518    return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
519  }
520
521  bool isRecord() const {
522    return DeclKind == Decl::Record || DeclKind == Decl::CXXRecord;
523  }
524
525  bool isNamespace() const {
526    return DeclKind == Decl::Namespace;
527  }
528
529  /// isTransparentContext - Determines whether this context is a
530  /// "transparent" context, meaning that the members declared in this
531  /// context are semantically declared in the nearest enclosing
532  /// non-transparent (opaque) context but are lexically declared in
533  /// this context. For example, consider the enumerators of an
534  /// enumeration type:
535  /// @code
536  /// enum E {
537  ///   Val1
538  /// };
539  /// @endcode
540  /// Here, E is a transparent context, so its enumerator (Val1) will
541  /// appear (semantically) that it is in the same context of E.
542  /// Examples of transparent contexts include: enumerations (except for
543  /// C++0x scoped enums), C++ linkage specifications, and C++0x
544  /// inline namespaces.
545  bool isTransparentContext() const;
546
547  bool Encloses(DeclContext *DC) const {
548    for (; DC; DC = DC->getParent())
549      if (DC == this)
550        return true;
551    return false;
552  }
553
554  /// getPrimaryContext - There may be many different
555  /// declarations of the same entity (including forward declarations
556  /// of classes, multiple definitions of namespaces, etc.), each with
557  /// a different set of declarations. This routine returns the
558  /// "primary" DeclContext structure, which will contain the
559  /// information needed to perform name lookup into this context.
560  DeclContext *getPrimaryContext();
561
562  /// getLookupContext - Retrieve the innermost non-transparent
563  /// context of this context, which corresponds to the innermost
564  /// location from which name lookup can find the entities in this
565  /// context.
566  DeclContext *getLookupContext() {
567    return const_cast<DeclContext *>(
568             const_cast<const DeclContext *>(this)->getLookupContext());
569  }
570  const DeclContext *getLookupContext() const;
571
572  /// getNextContext - If this is a DeclContext that may have other
573  /// DeclContexts that are semantically connected but syntactically
574  /// different, such as C++ namespaces, this routine retrieves the
575  /// next DeclContext in the link. Iteration through the chain of
576  /// DeclContexts should begin at the primary DeclContext and
577  /// continue until this function returns NULL. For example, given:
578  /// @code
579  /// namespace N {
580  ///   int x;
581  /// }
582  /// namespace N {
583  ///   int y;
584  /// }
585  /// @endcode
586  /// The first occurrence of namespace N will be the primary
587  /// DeclContext. Its getNextContext will return the second
588  /// occurrence of namespace N.
589  DeclContext *getNextContext();
590
591  /// decl_iterator - Iterates through the declarations stored
592  /// within this context.
593  class decl_iterator {
594    /// Current - The current declaration.
595    Decl *Current;
596
597  public:
598    typedef Decl*                     value_type;
599    typedef Decl*                     reference;
600    typedef Decl*                     pointer;
601    typedef std::forward_iterator_tag iterator_category;
602    typedef std::ptrdiff_t            difference_type;
603
604    decl_iterator() : Current(0) { }
605    explicit decl_iterator(Decl *C) : Current(C) { }
606
607    reference operator*() const { return Current; }
608    pointer operator->() const { return Current; }
609
610    decl_iterator& operator++();
611
612    decl_iterator operator++(int) {
613      decl_iterator tmp(*this);
614      ++(*this);
615      return tmp;
616    }
617
618    friend bool operator==(decl_iterator x, decl_iterator y) {
619      return x.Current == y.Current;
620    }
621    friend bool operator!=(decl_iterator x, decl_iterator y) {
622      return x.Current != y.Current;
623    }
624  };
625
626  /// decls_begin/decls_end - Iterate over the declarations stored in
627  /// this context.
628  decl_iterator decls_begin() const { return decl_iterator(FirstDecl); }
629  decl_iterator decls_end()   const { return decl_iterator(); }
630
631  /// specific_decl_iterator - Iterates over a subrange of
632  /// declarations stored in a DeclContext, providing only those that
633  /// are of type SpecificDecl (or a class derived from it) and,
634  /// optionally, that meet some additional run-time criteria. This
635  /// iterator is used, for example, to provide iteration over just
636  /// the fields within a RecordDecl (with SpecificDecl = FieldDecl)
637  /// or the instance methods within an Objective-C interface (with
638  /// SpecificDecl = ObjCMethodDecl and using
639  /// ObjCMethodDecl::isInstanceMethod as the run-time criteria).
640  template<typename SpecificDecl>
641  class specific_decl_iterator {
642    /// Current - The current, underlying declaration iterator, which
643    /// will either be the same as End or will point to a declaration of
644    /// type SpecificDecl.
645    DeclContext::decl_iterator Current;
646
647    /// End - One past the last declaration within the DeclContext.
648    DeclContext::decl_iterator End;
649
650    /// Acceptable - If non-NULL, points to a member function that
651    /// will determine if a particular declaration of type
652    /// SpecificDecl should be visited by the iteration.
653    bool (SpecificDecl::*Acceptable)() const;
654
655    /// SkipToNextDecl - Advances the current position up to the next
656    /// declaration of type SpecificDecl that also meets the criteria
657    /// required by Acceptable.
658    void SkipToNextDecl() {
659      while (Current != End &&
660             (!isa<SpecificDecl>(*Current) ||
661              (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
662        ++Current;
663    }
664
665  public:
666    typedef SpecificDecl* value_type;
667    typedef SpecificDecl* reference;
668    typedef SpecificDecl* pointer;
669    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
670      difference_type;
671    typedef std::forward_iterator_tag iterator_category;
672
673    specific_decl_iterator() : Current(), End(), Acceptable(0) { }
674
675    /// specific_decl_iterator - Construct a new iterator over a
676    /// subset of the declarations in [C, E). If A is non-NULL, it is
677    /// a pointer to a member function of SpecificDecl that should
678    /// return true for all of the SpecificDecl instances that will be
679    /// in the subset of iterators. For example, if you want
680    /// Objective-C instance methods, SpecificDecl will be
681    /// ObjCMethodDecl and A will be &ObjCMethodDecl::isInstanceMethod.
682    specific_decl_iterator(DeclContext::decl_iterator C,
683                           DeclContext::decl_iterator E,
684                           bool (SpecificDecl::*A)() const = 0)
685      : Current(C), End(E), Acceptable(A) {
686      SkipToNextDecl();
687    }
688
689    reference operator*() const { return cast<SpecificDecl>(*Current); }
690    pointer operator->() const { return cast<SpecificDecl>(*Current); }
691
692    specific_decl_iterator& operator++() {
693      ++Current;
694      SkipToNextDecl();
695      return *this;
696    }
697
698    specific_decl_iterator operator++(int) {
699      specific_decl_iterator tmp(*this);
700      ++(*this);
701      return tmp;
702    }
703
704    friend bool
705    operator==(const specific_decl_iterator& x, const specific_decl_iterator& y) {
706      return x.Current == y.Current;
707    }
708
709    friend bool
710    operator!=(const specific_decl_iterator& x, const specific_decl_iterator& y) {
711      return x.Current != y.Current;
712    }
713  };
714
715  /// @brief Add the declaration D into this context.
716  ///
717  /// This routine should be invoked when the declaration D has first
718  /// been declared, to place D into the context where it was
719  /// (lexically) defined. Every declaration must be added to one
720  /// (and only one!) context, where it can be visited via
721  /// [decls_begin(), decls_end()). Once a declaration has been added
722  /// to its lexical context, the corresponding DeclContext owns the
723  /// declaration.
724  ///
725  /// If D is also a NamedDecl, it will be made visible within its
726  /// semantic context via makeDeclVisibleInContext.
727  void addDecl(Decl *D);
728
729  /// lookup_iterator - An iterator that provides access to the results
730  /// of looking up a name within this context.
731  typedef NamedDecl **lookup_iterator;
732
733  /// lookup_const_iterator - An iterator that provides non-mutable
734  /// access to the results of lookup up a name within this context.
735  typedef NamedDecl * const * lookup_const_iterator;
736
737  typedef std::pair<lookup_iterator, lookup_iterator> lookup_result;
738  typedef std::pair<lookup_const_iterator, lookup_const_iterator>
739    lookup_const_result;
740
741  /// lookup - Find the declarations (if any) with the given Name in
742  /// this context. Returns a range of iterators that contains all of
743  /// the declarations with this name, with object, function, member,
744  /// and enumerator names preceding any tag name. Note that this
745  /// routine will not look into parent contexts.
746  lookup_result lookup(DeclarationName Name);
747  lookup_const_result lookup(DeclarationName Name) const;
748
749  /// @brief Makes a declaration visible within this context.
750  ///
751  /// This routine makes the declaration D visible to name lookup
752  /// within this context and, if this is a transparent context,
753  /// within its parent contexts up to the first enclosing
754  /// non-transparent context. Making a declaration visible within a
755  /// context does not transfer ownership of a declaration, and a
756  /// declaration can be visible in many contexts that aren't its
757  /// lexical context.
758  ///
759  /// If D is a redeclaration of an existing declaration that is
760  /// visible from this context, as determined by
761  /// NamedDecl::declarationReplaces, the previous declaration will be
762  /// replaced with D.
763  void makeDeclVisibleInContext(NamedDecl *D);
764
765  static bool classof(const Decl *D) {
766    switch (D->getKind()) {
767      case Decl::TranslationUnit:
768      case Decl::Namespace:
769      case Decl::Enum:
770      case Decl::Record:
771      case Decl::CXXRecord:
772      case Decl::ObjCMethod:
773      case Decl::ObjCInterface:
774      case Decl::ObjCCategory:
775      case Decl::ObjCProtocol:
776      case Decl::ObjCImplementation:
777      case Decl::ObjCCategoryImpl:
778      case Decl::LinkageSpec:
779      case Decl::Block:
780        return true;
781      default:
782        if (D->getKind() >= Decl::FunctionFirst &&
783            D->getKind() <= Decl::FunctionLast)
784          return true;
785        return false;
786    }
787  }
788  static bool classof(const DeclContext *D) { return true; }
789  static bool classof(const TranslationUnitDecl *D) { return true; }
790  static bool classof(const NamespaceDecl *D) { return true; }
791  static bool classof(const FunctionDecl *D) { return true; }
792  static bool classof(const RecordDecl *D) { return true; }
793  static bool classof(const CXXRecordDecl *D) { return true; }
794  static bool classof(const EnumDecl *D) { return true; }
795  static bool classof(const ObjCMethodDecl *D) { return true; }
796  static bool classof(const ObjCInterfaceDecl *D) { return true; }
797  static bool classof(const ObjCCategoryDecl *D) { return true; }
798  static bool classof(const ObjCProtocolDecl *D) { return true; }
799  static bool classof(const ObjCImplementationDecl *D) { return true; }
800  static bool classof(const ObjCCategoryImplDecl *D) { return true; }
801  static bool classof(const LinkageSpecDecl *D) { return true; }
802  static bool classof(const BlockDecl *D) { return true; }
803
804private:
805  void buildLookup(DeclContext *DCtx);
806  void makeDeclVisibleInContextImpl(NamedDecl *D);
807
808  void EmitOutRec(llvm::Serializer& S) const;
809  void ReadOutRec(llvm::Deserializer& D, ASTContext& C);
810
811  friend class Decl;
812};
813
814template<> struct DeclContext::KindTrait<DeclContext> {
815  static Decl::Kind getKind(const DeclContext *D) { return D->DeclKind; }
816};
817
818inline bool Decl::isTemplateParameter() const {
819  return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm;
820}
821
822inline bool Decl::isDefinedOutsideFunctionOrMethod() const {
823  if (getDeclContext())
824    return !getDeclContext()->getLookupContext()->isFunctionOrMethod();
825  else
826    return true;
827}
828
829inline DeclContext::decl_iterator& DeclContext::decl_iterator::operator++() {
830  Current = getNextDeclInScope(Current);
831  return *this;
832}
833
834} // end clang.
835
836namespace llvm {
837
838/// Implement a isa_impl_wrap specialization to check whether a DeclContext is
839/// a specific Decl.
840template<class ToTy>
841struct isa_impl_wrap<ToTy,
842                     const ::clang::DeclContext,const ::clang::DeclContext> {
843  static bool doit(const ::clang::DeclContext &Val) {
844    return ToTy::classof(::clang::Decl::castFromDeclContext(&Val));
845  }
846};
847template<class ToTy>
848struct isa_impl_wrap<ToTy, ::clang::DeclContext, ::clang::DeclContext>
849  : public isa_impl_wrap<ToTy,
850                      const ::clang::DeclContext,const ::clang::DeclContext> {};
851
852/// Implement cast_convert_val for Decl -> DeclContext conversions.
853template<class FromTy>
854struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
855  static ::clang::DeclContext &doit(const FromTy &Val) {
856    return *FromTy::castToDeclContext(&Val);
857  }
858};
859
860template<class FromTy>
861struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
862  static ::clang::DeclContext *doit(const FromTy *Val) {
863    return FromTy::castToDeclContext(Val);
864  }
865};
866
867template<class FromTy>
868struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
869  static const ::clang::DeclContext &doit(const FromTy &Val) {
870    return *FromTy::castToDeclContext(&Val);
871  }
872};
873
874template<class FromTy>
875struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
876  static const ::clang::DeclContext *doit(const FromTy *Val) {
877    return FromTy::castToDeclContext(Val);
878  }
879};
880
881/// Implement cast_convert_val for DeclContext -> Decl conversions.
882template<class ToTy>
883struct cast_convert_val<ToTy,
884                        const ::clang::DeclContext,const ::clang::DeclContext> {
885  static ToTy &doit(const ::clang::DeclContext &Val) {
886    return *reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(&Val));
887  }
888};
889template<class ToTy>
890struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext>
891  : public cast_convert_val<ToTy,
892                      const ::clang::DeclContext,const ::clang::DeclContext> {};
893
894template<class ToTy>
895struct cast_convert_val<ToTy,
896                     const ::clang::DeclContext*, const ::clang::DeclContext*> {
897  static ToTy *doit(const ::clang::DeclContext *Val) {
898    return reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(Val));
899  }
900};
901template<class ToTy>
902struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*>
903  : public cast_convert_val<ToTy,
904                    const ::clang::DeclContext*,const ::clang::DeclContext*> {};
905
906} // end namespace llvm
907
908#endif
909