DeclBase.h revision cfa88f893915ceb8ae4ce2f17c46c24a4d67502f
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/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/Specifiers.h"
20#include "llvm/ADT/PointerUnion.h"
21#include "llvm/Support/Compiler.h"
22#include "llvm/Support/PrettyStackTrace.h"
23
24namespace clang {
25class ASTMutationListener;
26class BlockDecl;
27class CXXRecordDecl;
28class CompoundStmt;
29class DeclContext;
30class DeclarationName;
31class DependentDiagnostic;
32class EnumDecl;
33class FunctionDecl;
34class LinkageSpecDecl;
35class Module;
36class NamedDecl;
37class NamespaceDecl;
38class ObjCCategoryDecl;
39class ObjCCategoryImplDecl;
40class ObjCContainerDecl;
41class ObjCImplDecl;
42class ObjCImplementationDecl;
43class ObjCInterfaceDecl;
44class ObjCMethodDecl;
45class ObjCProtocolDecl;
46struct PrintingPolicy;
47class Stmt;
48class StoredDeclsMap;
49class TranslationUnitDecl;
50class UsingDirectiveDecl;
51}
52
53namespace llvm {
54// DeclContext* is only 4-byte aligned on 32-bit systems.
55template<>
56  class PointerLikeTypeTraits<clang::DeclContext*> {
57  typedef clang::DeclContext* PT;
58public:
59  static inline void *getAsVoidPointer(PT P) { return P; }
60  static inline PT getFromVoidPointer(void *P) {
61    return static_cast<PT>(P);
62  }
63  enum { NumLowBitsAvailable = 2 };
64};
65}
66
67namespace clang {
68
69  /// \brief Captures the result of checking the availability of a
70  /// declaration.
71  enum AvailabilityResult {
72    AR_Available = 0,
73    AR_NotYetIntroduced,
74    AR_Deprecated,
75    AR_Unavailable
76  };
77
78/// Decl - This represents one declaration (or definition), e.g. a variable,
79/// typedef, function, struct, etc.
80///
81class Decl {
82public:
83  /// \brief Lists the kind of concrete classes of Decl.
84  enum Kind {
85#define DECL(DERIVED, BASE) DERIVED,
86#define ABSTRACT_DECL(DECL)
87#define DECL_RANGE(BASE, START, END) \
88        first##BASE = START, last##BASE = END,
89#define LAST_DECL_RANGE(BASE, START, END) \
90        first##BASE = START, last##BASE = END
91#include "clang/AST/DeclNodes.inc"
92  };
93
94  /// \brief A placeholder type used to construct an empty shell of a
95  /// decl-derived type that will be filled in later (e.g., by some
96  /// deserialization method).
97  struct EmptyShell { };
98
99  /// IdentifierNamespace - The different namespaces in which
100  /// declarations may appear.  According to C99 6.2.3, there are
101  /// four namespaces, labels, tags, members and ordinary
102  /// identifiers.  C++ describes lookup completely differently:
103  /// certain lookups merely "ignore" certain kinds of declarations,
104  /// usually based on whether the declaration is of a type, etc.
105  ///
106  /// These are meant as bitmasks, so that searches in
107  /// C++ can look into the "tag" namespace during ordinary lookup.
108  ///
109  /// Decl currently provides 15 bits of IDNS bits.
110  enum IdentifierNamespace {
111    /// Labels, declared with 'x:' and referenced with 'goto x'.
112    IDNS_Label               = 0x0001,
113
114    /// Tags, declared with 'struct foo;' and referenced with
115    /// 'struct foo'.  All tags are also types.  This is what
116    /// elaborated-type-specifiers look for in C.
117    IDNS_Tag                 = 0x0002,
118
119    /// Types, declared with 'struct foo', typedefs, etc.
120    /// This is what elaborated-type-specifiers look for in C++,
121    /// but note that it's ill-formed to find a non-tag.
122    IDNS_Type                = 0x0004,
123
124    /// Members, declared with object declarations within tag
125    /// definitions.  In C, these can only be found by "qualified"
126    /// lookup in member expressions.  In C++, they're found by
127    /// normal lookup.
128    IDNS_Member              = 0x0008,
129
130    /// Namespaces, declared with 'namespace foo {}'.
131    /// Lookup for nested-name-specifiers find these.
132    IDNS_Namespace           = 0x0010,
133
134    /// Ordinary names.  In C, everything that's not a label, tag,
135    /// or member ends up here.
136    IDNS_Ordinary            = 0x0020,
137
138    /// Objective C @protocol.
139    IDNS_ObjCProtocol        = 0x0040,
140
141    /// This declaration is a friend function.  A friend function
142    /// declaration is always in this namespace but may also be in
143    /// IDNS_Ordinary if it was previously declared.
144    IDNS_OrdinaryFriend      = 0x0080,
145
146    /// This declaration is a friend class.  A friend class
147    /// declaration is always in this namespace but may also be in
148    /// IDNS_Tag|IDNS_Type if it was previously declared.
149    IDNS_TagFriend           = 0x0100,
150
151    /// This declaration is a using declaration.  A using declaration
152    /// *introduces* a number of other declarations into the current
153    /// scope, and those declarations use the IDNS of their targets,
154    /// but the actual using declarations go in this namespace.
155    IDNS_Using               = 0x0200,
156
157    /// This declaration is a C++ operator declared in a non-class
158    /// context.  All such operators are also in IDNS_Ordinary.
159    /// C++ lexical operator lookup looks for these.
160    IDNS_NonMemberOperator   = 0x0400
161  };
162
163  /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
164  /// parameter types in method declarations.  Other than remembering
165  /// them and mangling them into the method's signature string, these
166  /// are ignored by the compiler; they are consumed by certain
167  /// remote-messaging frameworks.
168  ///
169  /// in, inout, and out are mutually exclusive and apply only to
170  /// method parameters.  bycopy and byref are mutually exclusive and
171  /// apply only to method parameters (?).  oneway applies only to
172  /// results.  All of these expect their corresponding parameter to
173  /// have a particular type.  None of this is currently enforced by
174  /// clang.
175  ///
176  /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
177  enum ObjCDeclQualifier {
178    OBJC_TQ_None = 0x0,
179    OBJC_TQ_In = 0x1,
180    OBJC_TQ_Inout = 0x2,
181    OBJC_TQ_Out = 0x4,
182    OBJC_TQ_Bycopy = 0x8,
183    OBJC_TQ_Byref = 0x10,
184    OBJC_TQ_Oneway = 0x20
185  };
186
187protected:
188  // Enumeration values used in the bits stored in NextInContextAndBits.
189  enum {
190    /// \brief Whether this declaration is a top-level declaration (function,
191    /// global variable, etc.) that is lexically inside an objc container
192    /// definition.
193    TopLevelDeclInObjCContainerFlag = 0x01,
194
195    /// \brief Whether this declaration is private to the module in which it was
196    /// defined.
197    ModulePrivateFlag = 0x02
198  };
199
200  /// \brief The next declaration within the same lexical
201  /// DeclContext. These pointers form the linked list that is
202  /// traversed via DeclContext's decls_begin()/decls_end().
203  ///
204  /// The extra two bits are used for the TopLevelDeclInObjCContainer and
205  /// ModulePrivate bits.
206  llvm::PointerIntPair<Decl *, 2, unsigned> NextInContextAndBits;
207
208private:
209  friend class DeclContext;
210
211  struct MultipleDC {
212    DeclContext *SemanticDC;
213    DeclContext *LexicalDC;
214  };
215
216
217  /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
218  /// For declarations that don't contain C++ scope specifiers, it contains
219  /// the DeclContext where the Decl was declared.
220  /// For declarations with C++ scope specifiers, it contains a MultipleDC*
221  /// with the context where it semantically belongs (SemanticDC) and the
222  /// context where it was lexically declared (LexicalDC).
223  /// e.g.:
224  ///
225  ///   namespace A {
226  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
227  ///   }
228  ///   void A::f(); // SemanticDC == namespace 'A'
229  ///                // LexicalDC == global namespace
230  llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
231
232  inline bool isInSemaDC() const    { return DeclCtx.is<DeclContext*>(); }
233  inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
234  inline MultipleDC *getMultipleDC() const {
235    return DeclCtx.get<MultipleDC*>();
236  }
237  inline DeclContext *getSemanticDC() const {
238    return DeclCtx.get<DeclContext*>();
239  }
240
241  /// Loc - The location of this decl.
242  SourceLocation Loc;
243
244  /// DeclKind - This indicates which class this is.
245  unsigned DeclKind : 8;
246
247  /// InvalidDecl - This indicates a semantic error occurred.
248  unsigned InvalidDecl :  1;
249
250  /// HasAttrs - This indicates whether the decl has attributes or not.
251  unsigned HasAttrs : 1;
252
253  /// Implicit - Whether this declaration was implicitly generated by
254  /// the implementation rather than explicitly written by the user.
255  unsigned Implicit : 1;
256
257  /// \brief Whether this declaration was "used", meaning that a definition is
258  /// required.
259  unsigned Used : 1;
260
261  /// \brief Whether this declaration was "referenced".
262  /// The difference with 'Used' is whether the reference appears in a
263  /// evaluated context or not, e.g. functions used in uninstantiated templates
264  /// are regarded as "referenced" but not "used".
265  unsigned Referenced : 1;
266
267  /// \brief Whether statistic collection is enabled.
268  static bool StatisticsEnabled;
269
270protected:
271  /// Access - Used by C++ decls for the access specifier.
272  // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
273  unsigned Access : 2;
274  friend class CXXClassMemberWrapper;
275
276  /// \brief Whether this declaration was loaded from an AST file.
277  unsigned FromASTFile : 1;
278
279  /// \brief Whether this declaration is hidden from normal name lookup, e.g.,
280  /// because it is was loaded from an AST file is either module-private or
281  /// because its submodule has not been made visible.
282  unsigned Hidden : 1;
283
284  /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
285  unsigned IdentifierNamespace : 12;
286
287  /// \brief Whether the \c CachedLinkage field is active.
288  ///
289  /// This field is only valid for NamedDecls subclasses.
290  mutable unsigned HasCachedLinkage : 1;
291
292  /// \brief If \c HasCachedLinkage, the linkage of this declaration.
293  ///
294  /// This field is only valid for NamedDecls subclasses.
295  mutable unsigned CachedLinkage : 2;
296
297  friend class ASTDeclWriter;
298  friend class ASTDeclReader;
299  friend class ASTReader;
300
301private:
302  void CheckAccessDeclContext() const;
303
304protected:
305
306  Decl(Kind DK, DeclContext *DC, SourceLocation L)
307    : NextInContextAndBits(), DeclCtx(DC),
308      Loc(L), DeclKind(DK), InvalidDecl(0),
309      HasAttrs(false), Implicit(false), Used(false), Referenced(false),
310      Access(AS_none), FromASTFile(0), Hidden(0),
311      IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
312      HasCachedLinkage(0)
313  {
314    if (StatisticsEnabled) add(DK);
315  }
316
317  Decl(Kind DK, EmptyShell Empty)
318    : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0),
319      HasAttrs(false), Implicit(false), Used(false), Referenced(false),
320      Access(AS_none), FromASTFile(0), Hidden(0),
321      IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
322      HasCachedLinkage(0)
323  {
324    if (StatisticsEnabled) add(DK);
325  }
326
327  virtual ~Decl();
328
329  /// \brief Allocate memory for a deserialized declaration.
330  ///
331  /// This routine must be used to allocate memory for any declaration that is
332  /// deserialized from a module file.
333  ///
334  /// \param Context The context in which we will allocate memory.
335  /// \param ID The global ID of the deserialized declaration.
336  /// \param Size The size of the allocated object.
337  static void *AllocateDeserializedDecl(const ASTContext &Context,
338                                        unsigned ID,
339                                        unsigned Size);
340
341public:
342
343  /// \brief Source range that this declaration covers.
344  virtual SourceRange getSourceRange() const LLVM_READONLY {
345    return SourceRange(getLocation(), getLocation());
346  }
347  SourceLocation getLocStart() const LLVM_READONLY {
348    return getSourceRange().getBegin();
349  }
350  SourceLocation getLocEnd() const LLVM_READONLY {
351    return getSourceRange().getEnd();
352  }
353
354  SourceLocation getLocation() const { return Loc; }
355  void setLocation(SourceLocation L) { Loc = L; }
356
357  Kind getKind() const { return static_cast<Kind>(DeclKind); }
358  const char *getDeclKindName() const;
359
360  Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
361  const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
362
363  DeclContext *getDeclContext() {
364    if (isInSemaDC())
365      return getSemanticDC();
366    return getMultipleDC()->SemanticDC;
367  }
368  const DeclContext *getDeclContext() const {
369    return const_cast<Decl*>(this)->getDeclContext();
370  }
371
372  /// Finds the innermost non-closure context of this declaration.
373  /// That is, walk out the DeclContext chain, skipping any blocks.
374  DeclContext *getNonClosureContext();
375  const DeclContext *getNonClosureContext() const {
376    return const_cast<Decl*>(this)->getNonClosureContext();
377  }
378
379  TranslationUnitDecl *getTranslationUnitDecl();
380  const TranslationUnitDecl *getTranslationUnitDecl() const {
381    return const_cast<Decl*>(this)->getTranslationUnitDecl();
382  }
383
384  bool isInAnonymousNamespace() const;
385
386  ASTContext &getASTContext() const LLVM_READONLY;
387
388  void setAccess(AccessSpecifier AS) {
389    Access = AS;
390#ifndef NDEBUG
391    CheckAccessDeclContext();
392#endif
393  }
394
395  AccessSpecifier getAccess() const {
396#ifndef NDEBUG
397    CheckAccessDeclContext();
398#endif
399    return AccessSpecifier(Access);
400  }
401
402  bool hasAttrs() const { return HasAttrs; }
403  void setAttrs(const AttrVec& Attrs) {
404    return setAttrsImpl(Attrs, getASTContext());
405  }
406  AttrVec &getAttrs() {
407    return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
408  }
409  const AttrVec &getAttrs() const;
410  void swapAttrs(Decl *D);
411  void dropAttrs();
412
413  void addAttr(Attr *A) {
414    if (hasAttrs())
415      getAttrs().push_back(A);
416    else
417      setAttrs(AttrVec(1, A));
418  }
419
420  typedef AttrVec::const_iterator attr_iterator;
421
422  // FIXME: Do not rely on iterators having comparable singular values.
423  //        Note that this should error out if they do not.
424  attr_iterator attr_begin() const {
425    return hasAttrs() ? getAttrs().begin() : 0;
426  }
427  attr_iterator attr_end() const {
428    return hasAttrs() ? getAttrs().end() : 0;
429  }
430
431  template <typename T>
432  void dropAttr() {
433    if (!HasAttrs) return;
434
435    AttrVec &Vec = getAttrs();
436    Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
437
438    if (Vec.empty())
439      HasAttrs = false;
440  }
441
442  template <typename T>
443  specific_attr_iterator<T> specific_attr_begin() const {
444    return specific_attr_iterator<T>(attr_begin());
445  }
446  template <typename T>
447  specific_attr_iterator<T> specific_attr_end() const {
448    return specific_attr_iterator<T>(attr_end());
449  }
450
451  template<typename T> T *getAttr() const {
452    return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : 0;
453  }
454  template<typename T> bool hasAttr() const {
455    return hasAttrs() && hasSpecificAttr<T>(getAttrs());
456  }
457
458  /// getMaxAlignment - return the maximum alignment specified by attributes
459  /// on this decl, 0 if there are none.
460  unsigned getMaxAlignment() const;
461
462  /// setInvalidDecl - Indicates the Decl had a semantic error. This
463  /// allows for graceful error recovery.
464  void setInvalidDecl(bool Invalid = true);
465  bool isInvalidDecl() const { return (bool) InvalidDecl; }
466
467  /// isImplicit - Indicates whether the declaration was implicitly
468  /// generated by the implementation. If false, this declaration
469  /// was written explicitly in the source code.
470  bool isImplicit() const { return Implicit; }
471  void setImplicit(bool I = true) { Implicit = I; }
472
473  /// \brief Whether this declaration was used, meaning that a definition
474  /// is required.
475  ///
476  /// \param CheckUsedAttr When true, also consider the "used" attribute
477  /// (in addition to the "used" bit set by \c setUsed()) when determining
478  /// whether the function is used.
479  bool isUsed(bool CheckUsedAttr = true) const;
480
481  void setUsed(bool U = true) { Used = U; }
482
483  /// \brief Whether this declaration was referenced.
484  bool isReferenced() const;
485
486  void setReferenced(bool R = true) { Referenced = R; }
487
488  /// \brief Whether this declaration is a top-level declaration (function,
489  /// global variable, etc.) that is lexically inside an objc container
490  /// definition.
491  bool isTopLevelDeclInObjCContainer() const {
492    return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag;
493  }
494
495  void setTopLevelDeclInObjCContainer(bool V = true) {
496    unsigned Bits = NextInContextAndBits.getInt();
497    if (V)
498      Bits |= TopLevelDeclInObjCContainerFlag;
499    else
500      Bits &= ~TopLevelDeclInObjCContainerFlag;
501    NextInContextAndBits.setInt(Bits);
502  }
503
504protected:
505  /// \brief Whether this declaration was marked as being private to the
506  /// module in which it was defined.
507  bool isModulePrivate() const {
508    return NextInContextAndBits.getInt() & ModulePrivateFlag;
509  }
510
511  /// \brief Specify whether this declaration was marked as being private
512  /// to the module in which it was defined.
513  void setModulePrivate(bool MP = true) {
514    unsigned Bits = NextInContextAndBits.getInt();
515    if (MP)
516      Bits |= ModulePrivateFlag;
517    else
518      Bits &= ~ModulePrivateFlag;
519    NextInContextAndBits.setInt(Bits);
520  }
521
522  /// \brief Set the owning module ID.
523  void setOwningModuleID(unsigned ID) {
524    assert(isFromASTFile() && "Only works on a deserialized declaration");
525    *((unsigned*)this - 2) = ID;
526  }
527
528public:
529
530  /// \brief Determine the availability of the given declaration.
531  ///
532  /// This routine will determine the most restrictive availability of
533  /// the given declaration (e.g., preferring 'unavailable' to
534  /// 'deprecated').
535  ///
536  /// \param Message If non-NULL and the result is not \c
537  /// AR_Available, will be set to a (possibly empty) message
538  /// describing why the declaration has not been introduced, is
539  /// deprecated, or is unavailable.
540  AvailabilityResult getAvailability(std::string *Message = 0) const;
541
542  /// \brief Determine whether this declaration is marked 'deprecated'.
543  ///
544  /// \param Message If non-NULL and the declaration is deprecated,
545  /// this will be set to the message describing why the declaration
546  /// was deprecated (which may be empty).
547  bool isDeprecated(std::string *Message = 0) const {
548    return getAvailability(Message) == AR_Deprecated;
549  }
550
551  /// \brief Determine whether this declaration is marked 'unavailable'.
552  ///
553  /// \param Message If non-NULL and the declaration is unavailable,
554  /// this will be set to the message describing why the declaration
555  /// was made unavailable (which may be empty).
556  bool isUnavailable(std::string *Message = 0) const {
557    return getAvailability(Message) == AR_Unavailable;
558  }
559
560  /// \brief Determine whether this is a weak-imported symbol.
561  ///
562  /// Weak-imported symbols are typically marked with the
563  /// 'weak_import' attribute, but may also be marked with an
564  /// 'availability' attribute where we're targing a platform prior to
565  /// the introduction of this feature.
566  bool isWeakImported() const;
567
568  /// \brief Determines whether this symbol can be weak-imported,
569  /// e.g., whether it would be well-formed to add the weak_import
570  /// attribute.
571  ///
572  /// \param IsDefinition Set to \c true to indicate that this
573  /// declaration cannot be weak-imported because it has a definition.
574  bool canBeWeakImported(bool &IsDefinition) const;
575
576  /// \brief Determine whether this declaration came from an AST file (such as
577  /// a precompiled header or module) rather than having been parsed.
578  bool isFromASTFile() const { return FromASTFile; }
579
580  /// \brief Retrieve the global declaration ID associated with this
581  /// declaration, which specifies where in the
582  unsigned getGlobalID() const {
583    if (isFromASTFile())
584      return *((const unsigned*)this - 1);
585    return 0;
586  }
587
588  /// \brief Retrieve the global ID of the module that owns this particular
589  /// declaration.
590  unsigned getOwningModuleID() const {
591    if (isFromASTFile())
592      return *((const unsigned*)this - 2);
593
594    return 0;
595  }
596
597private:
598  Module *getOwningModuleSlow() const;
599
600public:
601  Module *getOwningModule() const {
602    if (!isFromASTFile())
603      return 0;
604
605    return getOwningModuleSlow();
606  }
607
608  unsigned getIdentifierNamespace() const {
609    return IdentifierNamespace;
610  }
611  bool isInIdentifierNamespace(unsigned NS) const {
612    return getIdentifierNamespace() & NS;
613  }
614  static unsigned getIdentifierNamespaceForKind(Kind DK);
615
616  bool hasTagIdentifierNamespace() const {
617    return isTagIdentifierNamespace(getIdentifierNamespace());
618  }
619  static bool isTagIdentifierNamespace(unsigned NS) {
620    // TagDecls have Tag and Type set and may also have TagFriend.
621    return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
622  }
623
624  /// getLexicalDeclContext - The declaration context where this Decl was
625  /// lexically declared (LexicalDC). May be different from
626  /// getDeclContext() (SemanticDC).
627  /// e.g.:
628  ///
629  ///   namespace A {
630  ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
631  ///   }
632  ///   void A::f(); // SemanticDC == namespace 'A'
633  ///                // LexicalDC == global namespace
634  DeclContext *getLexicalDeclContext() {
635    if (isInSemaDC())
636      return getSemanticDC();
637    return getMultipleDC()->LexicalDC;
638  }
639  const DeclContext *getLexicalDeclContext() const {
640    return const_cast<Decl*>(this)->getLexicalDeclContext();
641  }
642
643  virtual bool isOutOfLine() const {
644    return getLexicalDeclContext() != getDeclContext();
645  }
646
647  /// setDeclContext - Set both the semantic and lexical DeclContext
648  /// to DC.
649  void setDeclContext(DeclContext *DC);
650
651  void setLexicalDeclContext(DeclContext *DC);
652
653  /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
654  /// scoped decl is defined outside the current function or method.  This is
655  /// roughly global variables and functions, but also handles enums (which
656  /// could be defined inside or outside a function etc).
657  bool isDefinedOutsideFunctionOrMethod() const {
658    return getParentFunctionOrMethod() == 0;
659  }
660
661  /// \brief If this decl is defined inside a function/method/block it returns
662  /// the corresponding DeclContext, otherwise it returns null.
663  const DeclContext *getParentFunctionOrMethod() const;
664  DeclContext *getParentFunctionOrMethod() {
665    return const_cast<DeclContext*>(
666                    const_cast<const Decl*>(this)->getParentFunctionOrMethod());
667  }
668
669  /// \brief Retrieves the "canonical" declaration of the given declaration.
670  virtual Decl *getCanonicalDecl() { return this; }
671  const Decl *getCanonicalDecl() const {
672    return const_cast<Decl*>(this)->getCanonicalDecl();
673  }
674
675  /// \brief Whether this particular Decl is a canonical one.
676  bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
677
678protected:
679  /// \brief Returns the next redeclaration or itself if this is the only decl.
680  ///
681  /// Decl subclasses that can be redeclared should override this method so that
682  /// Decl::redecl_iterator can iterate over them.
683  virtual Decl *getNextRedeclaration() { return this; }
684
685  /// \brief Implementation of getPreviousDecl(), to be overridden by any
686  /// subclass that has a redeclaration chain.
687  virtual Decl *getPreviousDeclImpl() { return 0; }
688
689  /// \brief Implementation of getMostRecentDecl(), to be overridden by any
690  /// subclass that has a redeclaration chain.
691  virtual Decl *getMostRecentDeclImpl() { return this; }
692
693public:
694  /// \brief Iterates through all the redeclarations of the same decl.
695  class redecl_iterator {
696    /// Current - The current declaration.
697    Decl *Current;
698    Decl *Starter;
699
700  public:
701    typedef Decl *value_type;
702    typedef const value_type &reference;
703    typedef const value_type *pointer;
704    typedef std::forward_iterator_tag iterator_category;
705    typedef std::ptrdiff_t difference_type;
706
707    redecl_iterator() : Current(0) { }
708    explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
709
710    reference operator*() const { return Current; }
711    value_type operator->() const { return Current; }
712
713    redecl_iterator& operator++() {
714      assert(Current && "Advancing while iterator has reached end");
715      // Get either previous decl or latest decl.
716      Decl *Next = Current->getNextRedeclaration();
717      assert(Next && "Should return next redeclaration or itself, never null!");
718      Current = (Next != Starter ? Next : 0);
719      return *this;
720    }
721
722    redecl_iterator operator++(int) {
723      redecl_iterator tmp(*this);
724      ++(*this);
725      return tmp;
726    }
727
728    friend bool operator==(redecl_iterator x, redecl_iterator y) {
729      return x.Current == y.Current;
730    }
731    friend bool operator!=(redecl_iterator x, redecl_iterator y) {
732      return x.Current != y.Current;
733    }
734  };
735
736  /// \brief Returns iterator for all the redeclarations of the same decl.
737  /// It will iterate at least once (when this decl is the only one).
738  redecl_iterator redecls_begin() const {
739    return redecl_iterator(const_cast<Decl*>(this));
740  }
741  redecl_iterator redecls_end() const { return redecl_iterator(); }
742
743  /// \brief Retrieve the previous declaration that declares the same entity
744  /// as this declaration, or NULL if there is no previous declaration.
745  Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
746
747  /// \brief Retrieve the most recent declaration that declares the same entity
748  /// as this declaration, or NULL if there is no previous declaration.
749  const Decl *getPreviousDecl() const {
750    return const_cast<Decl *>(this)->getPreviousDeclImpl();
751  }
752
753  /// \brief Retrieve the most recent declaration that declares the same entity
754  /// as this declaration (which may be this declaration).
755  Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
756
757  /// \brief Retrieve the most recent declaration that declares the same entity
758  /// as this declaration (which may be this declaration).
759  const Decl *getMostRecentDecl() const {
760    return const_cast<Decl *>(this)->getMostRecentDeclImpl();
761  }
762
763  /// getBody - If this Decl represents a declaration for a body of code,
764  ///  such as a function or method definition, this method returns the
765  ///  top-level Stmt* of that body.  Otherwise this method returns null.
766  virtual Stmt* getBody() const { return 0; }
767
768  /// \brief Returns true if this Decl represents a declaration for a body of
769  /// code, such as a function or method definition.
770  virtual bool hasBody() const { return getBody() != 0; }
771
772  /// getBodyRBrace - Gets the right brace of the body, if a body exists.
773  /// This works whether the body is a CompoundStmt or a CXXTryStmt.
774  SourceLocation getBodyRBrace() const;
775
776  // global temp stats (until we have a per-module visitor)
777  static void add(Kind k);
778  static void EnableStatistics();
779  static void PrintStats();
780
781  /// isTemplateParameter - Determines whether this declaration is a
782  /// template parameter.
783  bool isTemplateParameter() const;
784
785  /// isTemplateParameter - Determines whether this declaration is a
786  /// template parameter pack.
787  bool isTemplateParameterPack() const;
788
789  /// \brief Whether this declaration is a parameter pack.
790  bool isParameterPack() const;
791
792  /// \brief returns true if this declaration is a template
793  bool isTemplateDecl() const;
794
795  /// \brief Whether this declaration is a function or function template.
796  bool isFunctionOrFunctionTemplate() const;
797
798  /// \brief Changes the namespace of this declaration to reflect that it's
799  /// the object of a friend declaration.
800  ///
801  /// These declarations appear in the lexical context of the friending
802  /// class, but in the semantic context of the actual entity.  This property
803  /// applies only to a specific decl object;  other redeclarations of the
804  /// same entity may not (and probably don't) share this property.
805  void setObjectOfFriendDecl(bool PreviouslyDeclared) {
806    unsigned OldNS = IdentifierNamespace;
807    assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
808                     IDNS_TagFriend | IDNS_OrdinaryFriend)) &&
809           "namespace includes neither ordinary nor tag");
810    assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
811                       IDNS_TagFriend | IDNS_OrdinaryFriend)) &&
812           "namespace includes other than ordinary or tag");
813
814    IdentifierNamespace = 0;
815    if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
816      IdentifierNamespace |= IDNS_TagFriend;
817      if (PreviouslyDeclared) IdentifierNamespace |= IDNS_Tag | IDNS_Type;
818    }
819
820    if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend)) {
821      IdentifierNamespace |= IDNS_OrdinaryFriend;
822      if (PreviouslyDeclared) IdentifierNamespace |= IDNS_Ordinary;
823    }
824  }
825
826  enum FriendObjectKind {
827    FOK_None, // not a friend object
828    FOK_Declared, // a friend of a previously-declared entity
829    FOK_Undeclared // a friend of a previously-undeclared entity
830  };
831
832  /// \brief Determines whether this declaration is the object of a
833  /// friend declaration and, if so, what kind.
834  ///
835  /// There is currently no direct way to find the associated FriendDecl.
836  FriendObjectKind getFriendObjectKind() const {
837    unsigned mask
838      = (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
839    if (!mask) return FOK_None;
840    return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ?
841              FOK_Declared : FOK_Undeclared);
842  }
843
844  /// Specifies that this declaration is a C++ overloaded non-member.
845  void setNonMemberOperator() {
846    assert(getKind() == Function || getKind() == FunctionTemplate);
847    assert((IdentifierNamespace & IDNS_Ordinary) &&
848           "visible non-member operators should be in ordinary namespace");
849    IdentifierNamespace |= IDNS_NonMemberOperator;
850  }
851
852  static bool classofKind(Kind K) { return true; }
853  static DeclContext *castToDeclContext(const Decl *);
854  static Decl *castFromDeclContext(const DeclContext *);
855
856  void print(raw_ostream &Out, unsigned Indentation = 0,
857             bool PrintInstantiation = false) const;
858  void print(raw_ostream &Out, const PrintingPolicy &Policy,
859             unsigned Indentation = 0, bool PrintInstantiation = false) const;
860  static void printGroup(Decl** Begin, unsigned NumDecls,
861                         raw_ostream &Out, const PrintingPolicy &Policy,
862                         unsigned Indentation = 0);
863  // Debuggers don't usually respect default arguments.
864  LLVM_ATTRIBUTE_USED void dump() const;
865  void dump(raw_ostream &Out) const;
866  // Debuggers don't usually respect default arguments.
867  LLVM_ATTRIBUTE_USED void dumpXML() const;
868  void dumpXML(raw_ostream &OS) const;
869
870private:
871  void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
872  void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
873                           ASTContext &Ctx);
874
875protected:
876  ASTMutationListener *getASTMutationListener() const;
877};
878
879/// \brief Determine whether two declarations declare the same entity.
880inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
881  if (!D1 || !D2)
882    return false;
883
884  if (D1 == D2)
885    return true;
886
887  return D1->getCanonicalDecl() == D2->getCanonicalDecl();
888}
889
890/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
891/// doing something to a specific decl.
892class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
893  const Decl *TheDecl;
894  SourceLocation Loc;
895  SourceManager &SM;
896  const char *Message;
897public:
898  PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
899                       SourceManager &sm, const char *Msg)
900  : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
901
902  virtual void print(raw_ostream &OS) const;
903};
904
905typedef llvm::MutableArrayRef<NamedDecl*> DeclContextLookupResult;
906
907typedef ArrayRef<NamedDecl *> DeclContextLookupConstResult;
908
909/// DeclContext - This is used only as base class of specific decl types that
910/// can act as declaration contexts. These decls are (only the top classes
911/// that directly derive from DeclContext are mentioned, not their subclasses):
912///
913///   TranslationUnitDecl
914///   NamespaceDecl
915///   FunctionDecl
916///   TagDecl
917///   ObjCMethodDecl
918///   ObjCContainerDecl
919///   LinkageSpecDecl
920///   BlockDecl
921///
922class DeclContext {
923  /// DeclKind - This indicates which class this is.
924  unsigned DeclKind : 8;
925
926  /// \brief Whether this declaration context also has some external
927  /// storage that contains additional declarations that are lexically
928  /// part of this context.
929  mutable unsigned ExternalLexicalStorage : 1;
930
931  /// \brief Whether this declaration context also has some external
932  /// storage that contains additional declarations that are visible
933  /// in this context.
934  mutable unsigned ExternalVisibleStorage : 1;
935
936  /// \brief Pointer to the data structure used to lookup declarations
937  /// within this context (or a DependentStoredDeclsMap if this is a
938  /// dependent context), and a bool indicating whether we have lazily
939  /// omitted any declarations from the map. We maintain the invariant
940  /// that, if the map contains an entry for a DeclarationName, then it
941  /// contains all relevant entries for that name.
942  mutable llvm::PointerIntPair<StoredDeclsMap*, 1, bool> LookupPtr;
943
944protected:
945  /// FirstDecl - The first declaration stored within this declaration
946  /// context.
947  mutable Decl *FirstDecl;
948
949  /// LastDecl - The last declaration stored within this declaration
950  /// context. FIXME: We could probably cache this value somewhere
951  /// outside of the DeclContext, to reduce the size of DeclContext by
952  /// another pointer.
953  mutable Decl *LastDecl;
954
955  friend class ExternalASTSource;
956  friend class ASTWriter;
957
958  /// \brief Build up a chain of declarations.
959  ///
960  /// \returns the first/last pair of declarations.
961  static std::pair<Decl *, Decl *>
962  BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
963
964   DeclContext(Decl::Kind K)
965     : DeclKind(K), ExternalLexicalStorage(false),
966       ExternalVisibleStorage(false), LookupPtr(0, false), FirstDecl(0),
967       LastDecl(0) { }
968
969public:
970  ~DeclContext();
971
972  Decl::Kind getDeclKind() const {
973    return static_cast<Decl::Kind>(DeclKind);
974  }
975  const char *getDeclKindName() const;
976
977  /// getParent - Returns the containing DeclContext.
978  DeclContext *getParent() {
979    return cast<Decl>(this)->getDeclContext();
980  }
981  const DeclContext *getParent() const {
982    return const_cast<DeclContext*>(this)->getParent();
983  }
984
985  /// getLexicalParent - Returns the containing lexical DeclContext. May be
986  /// different from getParent, e.g.:
987  ///
988  ///   namespace A {
989  ///      struct S;
990  ///   }
991  ///   struct A::S {}; // getParent() == namespace 'A'
992  ///                   // getLexicalParent() == translation unit
993  ///
994  DeclContext *getLexicalParent() {
995    return cast<Decl>(this)->getLexicalDeclContext();
996  }
997  const DeclContext *getLexicalParent() const {
998    return const_cast<DeclContext*>(this)->getLexicalParent();
999  }
1000
1001  DeclContext *getLookupParent();
1002
1003  const DeclContext *getLookupParent() const {
1004    return const_cast<DeclContext*>(this)->getLookupParent();
1005  }
1006
1007  ASTContext &getParentASTContext() const {
1008    return cast<Decl>(this)->getASTContext();
1009  }
1010
1011  bool isClosure() const {
1012    return DeclKind == Decl::Block;
1013  }
1014
1015  bool isObjCContainer() const {
1016    switch (DeclKind) {
1017        case Decl::ObjCCategory:
1018        case Decl::ObjCCategoryImpl:
1019        case Decl::ObjCImplementation:
1020        case Decl::ObjCInterface:
1021        case Decl::ObjCProtocol:
1022            return true;
1023    }
1024    return false;
1025  }
1026
1027  bool isFunctionOrMethod() const {
1028    switch (DeclKind) {
1029    case Decl::Block:
1030    case Decl::ObjCMethod:
1031      return true;
1032    default:
1033      return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1034    }
1035  }
1036
1037  bool isFileContext() const {
1038    return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1039  }
1040
1041  bool isTranslationUnit() const {
1042    return DeclKind == Decl::TranslationUnit;
1043  }
1044
1045  bool isRecord() const {
1046    return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1047  }
1048
1049  bool isNamespace() const {
1050    return DeclKind == Decl::Namespace;
1051  }
1052
1053  bool isInlineNamespace() const;
1054
1055  /// \brief Determines whether this context is dependent on a
1056  /// template parameter.
1057  bool isDependentContext() const;
1058
1059  /// isTransparentContext - Determines whether this context is a
1060  /// "transparent" context, meaning that the members declared in this
1061  /// context are semantically declared in the nearest enclosing
1062  /// non-transparent (opaque) context but are lexically declared in
1063  /// this context. For example, consider the enumerators of an
1064  /// enumeration type:
1065  /// @code
1066  /// enum E {
1067  ///   Val1
1068  /// };
1069  /// @endcode
1070  /// Here, E is a transparent context, so its enumerator (Val1) will
1071  /// appear (semantically) that it is in the same context of E.
1072  /// Examples of transparent contexts include: enumerations (except for
1073  /// C++0x scoped enums), and C++ linkage specifications.
1074  bool isTransparentContext() const;
1075
1076  /// \brief Determines whether this context is, or is nested within,
1077  /// a C++ extern "C" linkage spec.
1078  bool isExternCContext() const;
1079
1080  /// \brief Determine whether this declaration context is equivalent
1081  /// to the declaration context DC.
1082  bool Equals(const DeclContext *DC) const {
1083    return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1084  }
1085
1086  /// \brief Determine whether this declaration context encloses the
1087  /// declaration context DC.
1088  bool Encloses(const DeclContext *DC) const;
1089
1090  /// \brief Find the nearest non-closure ancestor of this context,
1091  /// i.e. the innermost semantic parent of this context which is not
1092  /// a closure.  A context may be its own non-closure ancestor.
1093  DeclContext *getNonClosureAncestor();
1094  const DeclContext *getNonClosureAncestor() const {
1095    return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1096  }
1097
1098  /// getPrimaryContext - There may be many different
1099  /// declarations of the same entity (including forward declarations
1100  /// of classes, multiple definitions of namespaces, etc.), each with
1101  /// a different set of declarations. This routine returns the
1102  /// "primary" DeclContext structure, which will contain the
1103  /// information needed to perform name lookup into this context.
1104  DeclContext *getPrimaryContext();
1105  const DeclContext *getPrimaryContext() const {
1106    return const_cast<DeclContext*>(this)->getPrimaryContext();
1107  }
1108
1109  /// getRedeclContext - Retrieve the context in which an entity conflicts with
1110  /// other entities of the same name, or where it is a redeclaration if the
1111  /// two entities are compatible. This skips through transparent contexts.
1112  DeclContext *getRedeclContext();
1113  const DeclContext *getRedeclContext() const {
1114    return const_cast<DeclContext *>(this)->getRedeclContext();
1115  }
1116
1117  /// \brief Retrieve the nearest enclosing namespace context.
1118  DeclContext *getEnclosingNamespaceContext();
1119  const DeclContext *getEnclosingNamespaceContext() const {
1120    return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1121  }
1122
1123  /// \brief Test if this context is part of the enclosing namespace set of
1124  /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1125  /// isn't a namespace, this is equivalent to Equals().
1126  ///
1127  /// The enclosing namespace set of a namespace is the namespace and, if it is
1128  /// inline, its enclosing namespace, recursively.
1129  bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1130
1131  /// \brief Collects all of the declaration contexts that are semantically
1132  /// connected to this declaration context.
1133  ///
1134  /// For declaration contexts that have multiple semantically connected but
1135  /// syntactically distinct contexts, such as C++ namespaces, this routine
1136  /// retrieves the complete set of such declaration contexts in source order.
1137  /// For example, given:
1138  ///
1139  /// \code
1140  /// namespace N {
1141  ///   int x;
1142  /// }
1143  /// namespace N {
1144  ///   int y;
1145  /// }
1146  /// \endcode
1147  ///
1148  /// The \c Contexts parameter will contain both definitions of N.
1149  ///
1150  /// \param Contexts Will be cleared and set to the set of declaration
1151  /// contexts that are semanticaly connected to this declaration context,
1152  /// in source order, including this context (which may be the only result,
1153  /// for non-namespace contexts).
1154  void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1155
1156  /// decl_iterator - Iterates through the declarations stored
1157  /// within this context.
1158  class decl_iterator {
1159    /// Current - The current declaration.
1160    Decl *Current;
1161
1162  public:
1163    typedef Decl *value_type;
1164    typedef const value_type &reference;
1165    typedef const value_type *pointer;
1166    typedef std::forward_iterator_tag iterator_category;
1167    typedef std::ptrdiff_t            difference_type;
1168
1169    decl_iterator() : Current(0) { }
1170    explicit decl_iterator(Decl *C) : Current(C) { }
1171
1172    reference operator*() const { return Current; }
1173    // This doesn't meet the iterator requirements, but it's convenient
1174    value_type operator->() const { return Current; }
1175
1176    decl_iterator& operator++() {
1177      Current = Current->getNextDeclInContext();
1178      return *this;
1179    }
1180
1181    decl_iterator operator++(int) {
1182      decl_iterator tmp(*this);
1183      ++(*this);
1184      return tmp;
1185    }
1186
1187    friend bool operator==(decl_iterator x, decl_iterator y) {
1188      return x.Current == y.Current;
1189    }
1190    friend bool operator!=(decl_iterator x, decl_iterator y) {
1191      return x.Current != y.Current;
1192    }
1193  };
1194
1195  /// decls_begin/decls_end - Iterate over the declarations stored in
1196  /// this context.
1197  decl_iterator decls_begin() const;
1198  decl_iterator decls_end() const { return decl_iterator(); }
1199  bool decls_empty() const;
1200
1201  /// noload_decls_begin/end - Iterate over the declarations stored in this
1202  /// context that are currently loaded; don't attempt to retrieve anything
1203  /// from an external source.
1204  decl_iterator noload_decls_begin() const;
1205  decl_iterator noload_decls_end() const { return decl_iterator(); }
1206
1207  /// specific_decl_iterator - Iterates over a subrange of
1208  /// declarations stored in a DeclContext, providing only those that
1209  /// are of type SpecificDecl (or a class derived from it). This
1210  /// iterator is used, for example, to provide iteration over just
1211  /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1212  template<typename SpecificDecl>
1213  class specific_decl_iterator {
1214    /// Current - The current, underlying declaration iterator, which
1215    /// will either be NULL or will point to a declaration of
1216    /// type SpecificDecl.
1217    DeclContext::decl_iterator Current;
1218
1219    /// SkipToNextDecl - Advances the current position up to the next
1220    /// declaration of type SpecificDecl that also meets the criteria
1221    /// required by Acceptable.
1222    void SkipToNextDecl() {
1223      while (*Current && !isa<SpecificDecl>(*Current))
1224        ++Current;
1225    }
1226
1227  public:
1228    typedef SpecificDecl *value_type;
1229    // TODO: Add reference and pointer typedefs (with some appropriate proxy
1230    // type) if we ever have a need for them.
1231    typedef void reference;
1232    typedef void pointer;
1233    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1234      difference_type;
1235    typedef std::forward_iterator_tag iterator_category;
1236
1237    specific_decl_iterator() : Current() { }
1238
1239    /// specific_decl_iterator - Construct a new iterator over a
1240    /// subset of the declarations the range [C,
1241    /// end-of-declarations). If A is non-NULL, it is a pointer to a
1242    /// member function of SpecificDecl that should return true for
1243    /// all of the SpecificDecl instances that will be in the subset
1244    /// of iterators. For example, if you want Objective-C instance
1245    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1246    /// &ObjCMethodDecl::isInstanceMethod.
1247    explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1248      SkipToNextDecl();
1249    }
1250
1251    value_type operator*() const { return cast<SpecificDecl>(*Current); }
1252    // This doesn't meet the iterator requirements, but it's convenient
1253    value_type operator->() const { return **this; }
1254
1255    specific_decl_iterator& operator++() {
1256      ++Current;
1257      SkipToNextDecl();
1258      return *this;
1259    }
1260
1261    specific_decl_iterator operator++(int) {
1262      specific_decl_iterator tmp(*this);
1263      ++(*this);
1264      return tmp;
1265    }
1266
1267    friend bool operator==(const specific_decl_iterator& x,
1268                           const specific_decl_iterator& y) {
1269      return x.Current == y.Current;
1270    }
1271
1272    friend bool operator!=(const specific_decl_iterator& x,
1273                           const specific_decl_iterator& y) {
1274      return x.Current != y.Current;
1275    }
1276  };
1277
1278  /// \brief Iterates over a filtered subrange of declarations stored
1279  /// in a DeclContext.
1280  ///
1281  /// This iterator visits only those declarations that are of type
1282  /// SpecificDecl (or a class derived from it) and that meet some
1283  /// additional run-time criteria. This iterator is used, for
1284  /// example, to provide access to the instance methods within an
1285  /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1286  /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1287  template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1288  class filtered_decl_iterator {
1289    /// Current - The current, underlying declaration iterator, which
1290    /// will either be NULL or will point to a declaration of
1291    /// type SpecificDecl.
1292    DeclContext::decl_iterator Current;
1293
1294    /// SkipToNextDecl - Advances the current position up to the next
1295    /// declaration of type SpecificDecl that also meets the criteria
1296    /// required by Acceptable.
1297    void SkipToNextDecl() {
1298      while (*Current &&
1299             (!isa<SpecificDecl>(*Current) ||
1300              (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1301        ++Current;
1302    }
1303
1304  public:
1305    typedef SpecificDecl *value_type;
1306    // TODO: Add reference and pointer typedefs (with some appropriate proxy
1307    // type) if we ever have a need for them.
1308    typedef void reference;
1309    typedef void pointer;
1310    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1311      difference_type;
1312    typedef std::forward_iterator_tag iterator_category;
1313
1314    filtered_decl_iterator() : Current() { }
1315
1316    /// filtered_decl_iterator - Construct a new iterator over a
1317    /// subset of the declarations the range [C,
1318    /// end-of-declarations). If A is non-NULL, it is a pointer to a
1319    /// member function of SpecificDecl that should return true for
1320    /// all of the SpecificDecl instances that will be in the subset
1321    /// of iterators. For example, if you want Objective-C instance
1322    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1323    /// &ObjCMethodDecl::isInstanceMethod.
1324    explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1325      SkipToNextDecl();
1326    }
1327
1328    value_type operator*() const { return cast<SpecificDecl>(*Current); }
1329    value_type operator->() const { return cast<SpecificDecl>(*Current); }
1330
1331    filtered_decl_iterator& operator++() {
1332      ++Current;
1333      SkipToNextDecl();
1334      return *this;
1335    }
1336
1337    filtered_decl_iterator operator++(int) {
1338      filtered_decl_iterator tmp(*this);
1339      ++(*this);
1340      return tmp;
1341    }
1342
1343    friend bool operator==(const filtered_decl_iterator& x,
1344                           const filtered_decl_iterator& y) {
1345      return x.Current == y.Current;
1346    }
1347
1348    friend bool operator!=(const filtered_decl_iterator& x,
1349                           const filtered_decl_iterator& y) {
1350      return x.Current != y.Current;
1351    }
1352  };
1353
1354  /// @brief Add the declaration D into this context.
1355  ///
1356  /// This routine should be invoked when the declaration D has first
1357  /// been declared, to place D into the context where it was
1358  /// (lexically) defined. Every declaration must be added to one
1359  /// (and only one!) context, where it can be visited via
1360  /// [decls_begin(), decls_end()). Once a declaration has been added
1361  /// to its lexical context, the corresponding DeclContext owns the
1362  /// declaration.
1363  ///
1364  /// If D is also a NamedDecl, it will be made visible within its
1365  /// semantic context via makeDeclVisibleInContext.
1366  void addDecl(Decl *D);
1367
1368  /// @brief Add the declaration D into this context, but suppress
1369  /// searches for external declarations with the same name.
1370  ///
1371  /// Although analogous in function to addDecl, this removes an
1372  /// important check.  This is only useful if the Decl is being
1373  /// added in response to an external search; in all other cases,
1374  /// addDecl() is the right function to use.
1375  /// See the ASTImporter for use cases.
1376  void addDeclInternal(Decl *D);
1377
1378  /// @brief Add the declaration D to this context without modifying
1379  /// any lookup tables.
1380  ///
1381  /// This is useful for some operations in dependent contexts where
1382  /// the semantic context might not be dependent;  this basically
1383  /// only happens with friends.
1384  void addHiddenDecl(Decl *D);
1385
1386  /// @brief Removes a declaration from this context.
1387  void removeDecl(Decl *D);
1388
1389  /// lookup_iterator - An iterator that provides access to the results
1390  /// of looking up a name within this context.
1391  typedef NamedDecl **lookup_iterator;
1392
1393  /// lookup_const_iterator - An iterator that provides non-mutable
1394  /// access to the results of lookup up a name within this context.
1395  typedef NamedDecl * const * lookup_const_iterator;
1396
1397  typedef DeclContextLookupResult lookup_result;
1398  typedef DeclContextLookupConstResult lookup_const_result;
1399
1400  /// lookup - Find the declarations (if any) with the given Name in
1401  /// this context. Returns a range of iterators that contains all of
1402  /// the declarations with this name, with object, function, member,
1403  /// and enumerator names preceding any tag name. Note that this
1404  /// routine will not look into parent contexts.
1405  lookup_result lookup(DeclarationName Name);
1406  lookup_const_result lookup(DeclarationName Name) const {
1407    return const_cast<DeclContext*>(this)->lookup(Name);
1408  }
1409
1410  /// \brief A simplistic name lookup mechanism that performs name lookup
1411  /// into this declaration context without consulting the external source.
1412  ///
1413  /// This function should almost never be used, because it subverts the
1414  /// usual relationship between a DeclContext and the external source.
1415  /// See the ASTImporter for the (few, but important) use cases.
1416  void localUncachedLookup(DeclarationName Name,
1417                           SmallVectorImpl<NamedDecl *> &Results);
1418
1419  /// @brief Makes a declaration visible within this context.
1420  ///
1421  /// This routine makes the declaration D visible to name lookup
1422  /// within this context and, if this is a transparent context,
1423  /// within its parent contexts up to the first enclosing
1424  /// non-transparent context. Making a declaration visible within a
1425  /// context does not transfer ownership of a declaration, and a
1426  /// declaration can be visible in many contexts that aren't its
1427  /// lexical context.
1428  ///
1429  /// If D is a redeclaration of an existing declaration that is
1430  /// visible from this context, as determined by
1431  /// NamedDecl::declarationReplaces, the previous declaration will be
1432  /// replaced with D.
1433  void makeDeclVisibleInContext(NamedDecl *D);
1434
1435  /// all_lookups_iterator - An iterator that provides a view over the results
1436  /// of looking up every possible name.
1437  class all_lookups_iterator;
1438
1439  all_lookups_iterator lookups_begin() const;
1440
1441  all_lookups_iterator lookups_end() const;
1442
1443  /// udir_iterator - Iterates through the using-directives stored
1444  /// within this context.
1445  typedef UsingDirectiveDecl * const * udir_iterator;
1446
1447  typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
1448
1449  udir_iterator_range getUsingDirectives() const;
1450
1451  udir_iterator using_directives_begin() const {
1452    return getUsingDirectives().first;
1453  }
1454
1455  udir_iterator using_directives_end() const {
1456    return getUsingDirectives().second;
1457  }
1458
1459  // These are all defined in DependentDiagnostic.h.
1460  class ddiag_iterator;
1461  inline ddiag_iterator ddiag_begin() const;
1462  inline ddiag_iterator ddiag_end() const;
1463
1464  // Low-level accessors
1465
1466  /// \brief Mark the lookup table as needing to be built.  This should be
1467  /// used only if setHasExternalLexicalStorage() has been called.
1468  void setMustBuildLookupTable() {
1469    assert(ExternalLexicalStorage && "Requires external lexical storage");
1470    LookupPtr.setInt(true);
1471  }
1472
1473  /// \brief Retrieve the internal representation of the lookup structure.
1474  /// This may omit some names if we are lazily building the structure.
1475  StoredDeclsMap *getLookupPtr() const { return LookupPtr.getPointer(); }
1476
1477  /// \brief Ensure the lookup structure is fully-built and return it.
1478  StoredDeclsMap *buildLookup();
1479
1480  /// \brief Whether this DeclContext has external storage containing
1481  /// additional declarations that are lexically in this context.
1482  bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1483
1484  /// \brief State whether this DeclContext has external storage for
1485  /// declarations lexically in this context.
1486  void setHasExternalLexicalStorage(bool ES = true) {
1487    ExternalLexicalStorage = ES;
1488  }
1489
1490  /// \brief Whether this DeclContext has external storage containing
1491  /// additional declarations that are visible in this context.
1492  bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1493
1494  /// \brief State whether this DeclContext has external storage for
1495  /// declarations visible in this context.
1496  void setHasExternalVisibleStorage(bool ES = true) {
1497    ExternalVisibleStorage = ES;
1498  }
1499
1500  /// \brief Determine whether the given declaration is stored in the list of
1501  /// declarations lexically within this context.
1502  bool isDeclInLexicalTraversal(const Decl *D) const {
1503    return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1504                 D == LastDecl);
1505  }
1506
1507  static bool classof(const Decl *D);
1508  static bool classof(const DeclContext *D) { return true; }
1509
1510  LLVM_ATTRIBUTE_USED void dumpDeclContext() const;
1511
1512private:
1513  void LoadLexicalDeclsFromExternalStorage() const;
1514
1515  /// @brief Makes a declaration visible within this context, but
1516  /// suppresses searches for external declarations with the same
1517  /// name.
1518  ///
1519  /// Analogous to makeDeclVisibleInContext, but for the exclusive
1520  /// use of addDeclInternal().
1521  void makeDeclVisibleInContextInternal(NamedDecl *D);
1522
1523  friend class DependentDiagnostic;
1524  StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1525
1526  void buildLookupImpl(DeclContext *DCtx);
1527  void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1528                                         bool Rediscoverable);
1529  void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1530};
1531
1532inline bool Decl::isTemplateParameter() const {
1533  return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1534         getKind() == TemplateTemplateParm;
1535}
1536
1537// Specialization selected when ToTy is not a known subclass of DeclContext.
1538template <class ToTy,
1539          bool IsKnownSubtype = ::llvm::is_base_of< DeclContext, ToTy>::value>
1540struct cast_convert_decl_context {
1541  static const ToTy *doit(const DeclContext *Val) {
1542    return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1543  }
1544
1545  static ToTy *doit(DeclContext *Val) {
1546    return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1547  }
1548};
1549
1550// Specialization selected when ToTy is a known subclass of DeclContext.
1551template <class ToTy>
1552struct cast_convert_decl_context<ToTy, true> {
1553  static const ToTy *doit(const DeclContext *Val) {
1554    return static_cast<const ToTy*>(Val);
1555  }
1556
1557  static ToTy *doit(DeclContext *Val) {
1558    return static_cast<ToTy*>(Val);
1559  }
1560};
1561
1562
1563} // end clang.
1564
1565namespace llvm {
1566
1567/// isa<T>(DeclContext*)
1568template <typename To>
1569struct isa_impl<To, ::clang::DeclContext> {
1570  static bool doit(const ::clang::DeclContext &Val) {
1571    return To::classofKind(Val.getDeclKind());
1572  }
1573};
1574
1575/// cast<T>(DeclContext*)
1576template<class ToTy>
1577struct cast_convert_val<ToTy,
1578                        const ::clang::DeclContext,const ::clang::DeclContext> {
1579  static const ToTy &doit(const ::clang::DeclContext &Val) {
1580    return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1581  }
1582};
1583template<class ToTy>
1584struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
1585  static ToTy &doit(::clang::DeclContext &Val) {
1586    return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1587  }
1588};
1589template<class ToTy>
1590struct cast_convert_val<ToTy,
1591                     const ::clang::DeclContext*, const ::clang::DeclContext*> {
1592  static const ToTy *doit(const ::clang::DeclContext *Val) {
1593    return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1594  }
1595};
1596template<class ToTy>
1597struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
1598  static ToTy *doit(::clang::DeclContext *Val) {
1599    return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1600  }
1601};
1602
1603/// Implement cast_convert_val for Decl -> DeclContext conversions.
1604template<class FromTy>
1605struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1606  static ::clang::DeclContext &doit(const FromTy &Val) {
1607    return *FromTy::castToDeclContext(&Val);
1608  }
1609};
1610
1611template<class FromTy>
1612struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1613  static ::clang::DeclContext *doit(const FromTy *Val) {
1614    return FromTy::castToDeclContext(Val);
1615  }
1616};
1617
1618template<class FromTy>
1619struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1620  static const ::clang::DeclContext &doit(const FromTy &Val) {
1621    return *FromTy::castToDeclContext(&Val);
1622  }
1623};
1624
1625template<class FromTy>
1626struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1627  static const ::clang::DeclContext *doit(const FromTy *Val) {
1628    return FromTy::castToDeclContext(Val);
1629  }
1630};
1631
1632} // end namespace llvm
1633
1634#endif
1635