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