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