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