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