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