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