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