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