DeclBase.h revision 9a7e09fffbad657f775417252bc966098dfb1501
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 Retrieve the most recent declaration that declares the same entity
790  /// as this declaration (which may be this declaration).
791  Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
792
793  /// \brief Retrieve the most recent declaration that declares the same entity
794  /// as this declaration (which may be this declaration).
795  const Decl *getMostRecentDecl() const {
796    return const_cast<Decl *>(this)->getMostRecentDeclImpl();
797  }
798
799  /// getBody - If this Decl represents a declaration for a body of code,
800  ///  such as a function or method definition, this method returns the
801  ///  top-level Stmt* of that body.  Otherwise this method returns null.
802  virtual Stmt* getBody() const { return 0; }
803
804  /// \brief Returns true if this \c Decl represents a declaration for a body of
805  /// code, such as a function or method definition.
806  /// Note that \c hasBody can also return true if any redeclaration of this
807  /// \c Decl represents a declaration for a body of code.
808  virtual bool hasBody() const { return getBody() != 0; }
809
810  /// getBodyRBrace - Gets the right brace of the body, if a body exists.
811  /// This works whether the body is a CompoundStmt or a CXXTryStmt.
812  SourceLocation getBodyRBrace() const;
813
814  // global temp stats (until we have a per-module visitor)
815  static void add(Kind k);
816  static void EnableStatistics();
817  static void PrintStats();
818
819  /// isTemplateParameter - Determines whether this declaration is a
820  /// template parameter.
821  bool isTemplateParameter() const;
822
823  /// isTemplateParameter - Determines whether this declaration is a
824  /// template parameter pack.
825  bool isTemplateParameterPack() const;
826
827  /// \brief Whether this declaration is a parameter pack.
828  bool isParameterPack() const;
829
830  /// \brief returns true if this declaration is a template
831  bool isTemplateDecl() const;
832
833  /// \brief Whether this declaration is a function or function template.
834  bool isFunctionOrFunctionTemplate() const;
835
836  /// \brief Changes the namespace of this declaration to reflect that it's
837  /// a function-local extern declaration.
838  ///
839  /// These declarations appear in the lexical context of the extern
840  /// declaration, but in the semantic context of the enclosing namespace
841  /// scope.
842  void setLocalExternDecl() {
843    assert((IdentifierNamespace == IDNS_Ordinary ||
844            IdentifierNamespace == IDNS_OrdinaryFriend) &&
845           "namespace is not ordinary");
846
847    Decl *Prev = getPreviousDecl();
848    IdentifierNamespace &= ~IDNS_Ordinary;
849
850    IdentifierNamespace |= IDNS_LocalExtern;
851    if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
852      IdentifierNamespace |= IDNS_Ordinary;
853  }
854
855  /// \brief Determine whether this is a block-scope declaration with linkage.
856  /// This will either be a local variable declaration declared 'extern', or a
857  /// local function declaration.
858  bool isLocalExternDecl() {
859    return IdentifierNamespace & IDNS_LocalExtern;
860  }
861
862  /// \brief Changes the namespace of this declaration to reflect that it's
863  /// the object of a friend declaration.
864  ///
865  /// These declarations appear in the lexical context of the friending
866  /// class, but in the semantic context of the actual entity.  This property
867  /// applies only to a specific decl object;  other redeclarations of the
868  /// same entity may not (and probably don't) share this property.
869  void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
870    unsigned OldNS = IdentifierNamespace;
871    assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
872                     IDNS_TagFriend | IDNS_OrdinaryFriend |
873                     IDNS_LocalExtern)) &&
874           "namespace includes neither ordinary nor tag");
875    assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
876                       IDNS_TagFriend | IDNS_OrdinaryFriend |
877                       IDNS_LocalExtern)) &&
878           "namespace includes other than ordinary or tag");
879
880    Decl *Prev = getPreviousDecl();
881    IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
882
883    if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
884      IdentifierNamespace |= IDNS_TagFriend;
885      if (PerformFriendInjection ||
886          (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
887        IdentifierNamespace |= IDNS_Tag | IDNS_Type;
888    }
889
890    if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | IDNS_LocalExtern)) {
891      IdentifierNamespace |= IDNS_OrdinaryFriend;
892      if (PerformFriendInjection ||
893          (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
894        IdentifierNamespace |= IDNS_Ordinary;
895    }
896  }
897
898  enum FriendObjectKind {
899    FOK_None,      ///< Not a friend object.
900    FOK_Declared,  ///< A friend of a previously-declared entity.
901    FOK_Undeclared ///< A friend of a previously-undeclared entity.
902  };
903
904  /// \brief Determines whether this declaration is the object of a
905  /// friend declaration and, if so, what kind.
906  ///
907  /// There is currently no direct way to find the associated FriendDecl.
908  FriendObjectKind getFriendObjectKind() const {
909    unsigned mask =
910        (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
911    if (!mask) return FOK_None;
912    return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
913                                                             : FOK_Undeclared);
914  }
915
916  /// Specifies that this declaration is a C++ overloaded non-member.
917  void setNonMemberOperator() {
918    assert(getKind() == Function || getKind() == FunctionTemplate);
919    assert((IdentifierNamespace & IDNS_Ordinary) &&
920           "visible non-member operators should be in ordinary namespace");
921    IdentifierNamespace |= IDNS_NonMemberOperator;
922  }
923
924  static bool classofKind(Kind K) { return true; }
925  static DeclContext *castToDeclContext(const Decl *);
926  static Decl *castFromDeclContext(const DeclContext *);
927
928  void print(raw_ostream &Out, unsigned Indentation = 0,
929             bool PrintInstantiation = false) const;
930  void print(raw_ostream &Out, const PrintingPolicy &Policy,
931             unsigned Indentation = 0, bool PrintInstantiation = false) const;
932  static void printGroup(Decl** Begin, unsigned NumDecls,
933                         raw_ostream &Out, const PrintingPolicy &Policy,
934                         unsigned Indentation = 0);
935  // Debuggers don't usually respect default arguments.
936  LLVM_ATTRIBUTE_USED void dump() const;
937  // Same as dump(), but forces color printing.
938  LLVM_ATTRIBUTE_USED void dumpColor() const;
939  void dump(raw_ostream &Out) const;
940
941private:
942  void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
943  void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
944                           ASTContext &Ctx);
945
946protected:
947  ASTMutationListener *getASTMutationListener() const;
948};
949
950/// \brief Determine whether two declarations declare the same entity.
951inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
952  if (!D1 || !D2)
953    return false;
954
955  if (D1 == D2)
956    return true;
957
958  return D1->getCanonicalDecl() == D2->getCanonicalDecl();
959}
960
961/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
962/// doing something to a specific decl.
963class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
964  const Decl *TheDecl;
965  SourceLocation Loc;
966  SourceManager &SM;
967  const char *Message;
968public:
969  PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
970                       SourceManager &sm, const char *Msg)
971  : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
972
973  virtual void print(raw_ostream &OS) const;
974};
975
976typedef llvm::MutableArrayRef<NamedDecl*> DeclContextLookupResult;
977
978typedef ArrayRef<NamedDecl *> DeclContextLookupConstResult;
979
980/// DeclContext - This is used only as base class of specific decl types that
981/// can act as declaration contexts. These decls are (only the top classes
982/// that directly derive from DeclContext are mentioned, not their subclasses):
983///
984///   TranslationUnitDecl
985///   NamespaceDecl
986///   FunctionDecl
987///   TagDecl
988///   ObjCMethodDecl
989///   ObjCContainerDecl
990///   LinkageSpecDecl
991///   BlockDecl
992///
993class DeclContext {
994  /// DeclKind - This indicates which class this is.
995  unsigned DeclKind : 8;
996
997  /// \brief Whether this declaration context also has some external
998  /// storage that contains additional declarations that are lexically
999  /// part of this context.
1000  mutable bool ExternalLexicalStorage : 1;
1001
1002  /// \brief Whether this declaration context also has some external
1003  /// storage that contains additional declarations that are visible
1004  /// in this context.
1005  mutable bool ExternalVisibleStorage : 1;
1006
1007  /// \brief Whether this declaration context has had external visible
1008  /// storage added since the last lookup. In this case, \c LookupPtr's
1009  /// invariant may not hold and needs to be fixed before we perform
1010  /// another lookup.
1011  mutable bool NeedToReconcileExternalVisibleStorage : 1;
1012
1013  /// \brief Pointer to the data structure used to lookup declarations
1014  /// within this context (or a DependentStoredDeclsMap if this is a
1015  /// dependent context), and a bool indicating whether we have lazily
1016  /// omitted any declarations from the map. We maintain the invariant
1017  /// that, if the map contains an entry for a DeclarationName (and we
1018  /// haven't lazily omitted anything), then it contains all relevant
1019  /// entries for that name.
1020  mutable llvm::PointerIntPair<StoredDeclsMap*, 1, bool> LookupPtr;
1021
1022protected:
1023  /// FirstDecl - The first declaration stored within this declaration
1024  /// context.
1025  mutable Decl *FirstDecl;
1026
1027  /// LastDecl - The last declaration stored within this declaration
1028  /// context. FIXME: We could probably cache this value somewhere
1029  /// outside of the DeclContext, to reduce the size of DeclContext by
1030  /// another pointer.
1031  mutable Decl *LastDecl;
1032
1033  friend class ExternalASTSource;
1034  friend class ASTDeclReader;
1035  friend class ASTWriter;
1036
1037  /// \brief Build up a chain of declarations.
1038  ///
1039  /// \returns the first/last pair of declarations.
1040  static std::pair<Decl *, Decl *>
1041  BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1042
1043  DeclContext(Decl::Kind K)
1044      : DeclKind(K), ExternalLexicalStorage(false),
1045        ExternalVisibleStorage(false),
1046        NeedToReconcileExternalVisibleStorage(false), LookupPtr(0, false),
1047        FirstDecl(0), LastDecl(0) {}
1048
1049public:
1050  ~DeclContext();
1051
1052  Decl::Kind getDeclKind() const {
1053    return static_cast<Decl::Kind>(DeclKind);
1054  }
1055  const char *getDeclKindName() const;
1056
1057  /// getParent - Returns the containing DeclContext.
1058  DeclContext *getParent() {
1059    return cast<Decl>(this)->getDeclContext();
1060  }
1061  const DeclContext *getParent() const {
1062    return const_cast<DeclContext*>(this)->getParent();
1063  }
1064
1065  /// getLexicalParent - Returns the containing lexical DeclContext. May be
1066  /// different from getParent, e.g.:
1067  ///
1068  ///   namespace A {
1069  ///      struct S;
1070  ///   }
1071  ///   struct A::S {}; // getParent() == namespace 'A'
1072  ///                   // getLexicalParent() == translation unit
1073  ///
1074  DeclContext *getLexicalParent() {
1075    return cast<Decl>(this)->getLexicalDeclContext();
1076  }
1077  const DeclContext *getLexicalParent() const {
1078    return const_cast<DeclContext*>(this)->getLexicalParent();
1079  }
1080
1081  DeclContext *getLookupParent();
1082
1083  const DeclContext *getLookupParent() const {
1084    return const_cast<DeclContext*>(this)->getLookupParent();
1085  }
1086
1087  ASTContext &getParentASTContext() const {
1088    return cast<Decl>(this)->getASTContext();
1089  }
1090
1091  bool isClosure() const {
1092    return DeclKind == Decl::Block;
1093  }
1094
1095  bool isObjCContainer() const {
1096    switch (DeclKind) {
1097        case Decl::ObjCCategory:
1098        case Decl::ObjCCategoryImpl:
1099        case Decl::ObjCImplementation:
1100        case Decl::ObjCInterface:
1101        case Decl::ObjCProtocol:
1102            return true;
1103    }
1104    return false;
1105  }
1106
1107  bool isFunctionOrMethod() const {
1108    switch (DeclKind) {
1109    case Decl::Block:
1110    case Decl::Captured:
1111    case Decl::ObjCMethod:
1112      return true;
1113    default:
1114      return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1115    }
1116  }
1117
1118  bool isFileContext() const {
1119    return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1120  }
1121
1122  bool isTranslationUnit() const {
1123    return DeclKind == Decl::TranslationUnit;
1124  }
1125
1126  bool isRecord() const {
1127    return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1128  }
1129
1130  bool isNamespace() const {
1131    return DeclKind == Decl::Namespace;
1132  }
1133
1134  bool isInlineNamespace() const;
1135
1136  /// \brief Determines whether this context is dependent on a
1137  /// template parameter.
1138  bool isDependentContext() const;
1139
1140  /// isTransparentContext - Determines whether this context is a
1141  /// "transparent" context, meaning that the members declared in this
1142  /// context are semantically declared in the nearest enclosing
1143  /// non-transparent (opaque) context but are lexically declared in
1144  /// this context. For example, consider the enumerators of an
1145  /// enumeration type:
1146  /// @code
1147  /// enum E {
1148  ///   Val1
1149  /// };
1150  /// @endcode
1151  /// Here, E is a transparent context, so its enumerator (Val1) will
1152  /// appear (semantically) that it is in the same context of E.
1153  /// Examples of transparent contexts include: enumerations (except for
1154  /// C++0x scoped enums), and C++ linkage specifications.
1155  bool isTransparentContext() const;
1156
1157  /// \brief Determine whether this declaration context is equivalent
1158  /// to the declaration context DC.
1159  bool Equals(const DeclContext *DC) const {
1160    return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1161  }
1162
1163  /// \brief Determine whether this declaration context encloses the
1164  /// declaration context DC.
1165  bool Encloses(const DeclContext *DC) const;
1166
1167  /// \brief Find the nearest non-closure ancestor of this context,
1168  /// i.e. the innermost semantic parent of this context which is not
1169  /// a closure.  A context may be its own non-closure ancestor.
1170  Decl *getNonClosureAncestor();
1171  const Decl *getNonClosureAncestor() const {
1172    return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1173  }
1174
1175  /// getPrimaryContext - There may be many different
1176  /// declarations of the same entity (including forward declarations
1177  /// of classes, multiple definitions of namespaces, etc.), each with
1178  /// a different set of declarations. This routine returns the
1179  /// "primary" DeclContext structure, which will contain the
1180  /// information needed to perform name lookup into this context.
1181  DeclContext *getPrimaryContext();
1182  const DeclContext *getPrimaryContext() const {
1183    return const_cast<DeclContext*>(this)->getPrimaryContext();
1184  }
1185
1186  /// getRedeclContext - Retrieve the context in which an entity conflicts with
1187  /// other entities of the same name, or where it is a redeclaration if the
1188  /// two entities are compatible. This skips through transparent contexts.
1189  DeclContext *getRedeclContext();
1190  const DeclContext *getRedeclContext() const {
1191    return const_cast<DeclContext *>(this)->getRedeclContext();
1192  }
1193
1194  /// \brief Retrieve the nearest enclosing namespace context.
1195  DeclContext *getEnclosingNamespaceContext();
1196  const DeclContext *getEnclosingNamespaceContext() const {
1197    return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1198  }
1199
1200  /// \brief Test if this context is part of the enclosing namespace set of
1201  /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1202  /// isn't a namespace, this is equivalent to Equals().
1203  ///
1204  /// The enclosing namespace set of a namespace is the namespace and, if it is
1205  /// inline, its enclosing namespace, recursively.
1206  bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1207
1208  /// \brief Collects all of the declaration contexts that are semantically
1209  /// connected to this declaration context.
1210  ///
1211  /// For declaration contexts that have multiple semantically connected but
1212  /// syntactically distinct contexts, such as C++ namespaces, this routine
1213  /// retrieves the complete set of such declaration contexts in source order.
1214  /// For example, given:
1215  ///
1216  /// \code
1217  /// namespace N {
1218  ///   int x;
1219  /// }
1220  /// namespace N {
1221  ///   int y;
1222  /// }
1223  /// \endcode
1224  ///
1225  /// The \c Contexts parameter will contain both definitions of N.
1226  ///
1227  /// \param Contexts Will be cleared and set to the set of declaration
1228  /// contexts that are semanticaly connected to this declaration context,
1229  /// in source order, including this context (which may be the only result,
1230  /// for non-namespace contexts).
1231  void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1232
1233  /// decl_iterator - Iterates through the declarations stored
1234  /// within this context.
1235  class decl_iterator {
1236    /// Current - The current declaration.
1237    Decl *Current;
1238
1239  public:
1240    typedef Decl *value_type;
1241    typedef const value_type &reference;
1242    typedef const value_type *pointer;
1243    typedef std::forward_iterator_tag iterator_category;
1244    typedef std::ptrdiff_t            difference_type;
1245
1246    decl_iterator() : Current(0) { }
1247    explicit decl_iterator(Decl *C) : Current(C) { }
1248
1249    reference operator*() const { return Current; }
1250    // This doesn't meet the iterator requirements, but it's convenient
1251    value_type operator->() const { return Current; }
1252
1253    decl_iterator& operator++() {
1254      Current = Current->getNextDeclInContext();
1255      return *this;
1256    }
1257
1258    decl_iterator operator++(int) {
1259      decl_iterator tmp(*this);
1260      ++(*this);
1261      return tmp;
1262    }
1263
1264    friend bool operator==(decl_iterator x, decl_iterator y) {
1265      return x.Current == y.Current;
1266    }
1267    friend bool operator!=(decl_iterator x, decl_iterator y) {
1268      return x.Current != y.Current;
1269    }
1270  };
1271
1272  /// decls_begin/decls_end - Iterate over the declarations stored in
1273  /// this context.
1274  decl_iterator decls_begin() const;
1275  decl_iterator decls_end() const { return decl_iterator(); }
1276  bool decls_empty() const;
1277
1278  /// noload_decls_begin/end - Iterate over the declarations stored in this
1279  /// context that are currently loaded; don't attempt to retrieve anything
1280  /// from an external source.
1281  decl_iterator noload_decls_begin() const;
1282  decl_iterator noload_decls_end() const { return decl_iterator(); }
1283
1284  /// specific_decl_iterator - Iterates over a subrange of
1285  /// declarations stored in a DeclContext, providing only those that
1286  /// are of type SpecificDecl (or a class derived from it). This
1287  /// iterator is used, for example, to provide iteration over just
1288  /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1289  template<typename SpecificDecl>
1290  class specific_decl_iterator {
1291    /// Current - The current, underlying declaration iterator, which
1292    /// will either be NULL or will point to a declaration of
1293    /// type SpecificDecl.
1294    DeclContext::decl_iterator Current;
1295
1296    /// SkipToNextDecl - Advances the current position up to the next
1297    /// declaration of type SpecificDecl that also meets the criteria
1298    /// required by Acceptable.
1299    void SkipToNextDecl() {
1300      while (*Current && !isa<SpecificDecl>(*Current))
1301        ++Current;
1302    }
1303
1304  public:
1305    typedef SpecificDecl *value_type;
1306    // TODO: Add reference and pointer typedefs (with some appropriate proxy
1307    // type) if we ever have a need for them.
1308    typedef void reference;
1309    typedef void pointer;
1310    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1311      difference_type;
1312    typedef std::forward_iterator_tag iterator_category;
1313
1314    specific_decl_iterator() : Current() { }
1315
1316    /// specific_decl_iterator - Construct a new iterator over a
1317    /// subset of the declarations the range [C,
1318    /// end-of-declarations). If A is non-NULL, it is a pointer to a
1319    /// member function of SpecificDecl that should return true for
1320    /// all of the SpecificDecl instances that will be in the subset
1321    /// of iterators. For example, if you want Objective-C instance
1322    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1323    /// &ObjCMethodDecl::isInstanceMethod.
1324    explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1325      SkipToNextDecl();
1326    }
1327
1328    value_type operator*() const { return cast<SpecificDecl>(*Current); }
1329    // This doesn't meet the iterator requirements, but it's convenient
1330    value_type operator->() const { return **this; }
1331
1332    specific_decl_iterator& operator++() {
1333      ++Current;
1334      SkipToNextDecl();
1335      return *this;
1336    }
1337
1338    specific_decl_iterator operator++(int) {
1339      specific_decl_iterator tmp(*this);
1340      ++(*this);
1341      return tmp;
1342    }
1343
1344    friend bool operator==(const specific_decl_iterator& x,
1345                           const specific_decl_iterator& y) {
1346      return x.Current == y.Current;
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
1355  /// \brief Iterates over a filtered subrange of declarations stored
1356  /// in a DeclContext.
1357  ///
1358  /// This iterator visits only those declarations that are of type
1359  /// SpecificDecl (or a class derived from it) and that meet some
1360  /// additional run-time criteria. This iterator is used, for
1361  /// example, to provide access to the instance methods within an
1362  /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1363  /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1364  template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1365  class filtered_decl_iterator {
1366    /// Current - The current, underlying declaration iterator, which
1367    /// will either be NULL or will point to a declaration of
1368    /// type SpecificDecl.
1369    DeclContext::decl_iterator Current;
1370
1371    /// SkipToNextDecl - Advances the current position up to the next
1372    /// declaration of type SpecificDecl that also meets the criteria
1373    /// required by Acceptable.
1374    void SkipToNextDecl() {
1375      while (*Current &&
1376             (!isa<SpecificDecl>(*Current) ||
1377              (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1378        ++Current;
1379    }
1380
1381  public:
1382    typedef SpecificDecl *value_type;
1383    // TODO: Add reference and pointer typedefs (with some appropriate proxy
1384    // type) if we ever have a need for them.
1385    typedef void reference;
1386    typedef void pointer;
1387    typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1388      difference_type;
1389    typedef std::forward_iterator_tag iterator_category;
1390
1391    filtered_decl_iterator() : Current() { }
1392
1393    /// filtered_decl_iterator - Construct a new iterator over a
1394    /// subset of the declarations the range [C,
1395    /// end-of-declarations). If A is non-NULL, it is a pointer to a
1396    /// member function of SpecificDecl that should return true for
1397    /// all of the SpecificDecl instances that will be in the subset
1398    /// of iterators. For example, if you want Objective-C instance
1399    /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1400    /// &ObjCMethodDecl::isInstanceMethod.
1401    explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1402      SkipToNextDecl();
1403    }
1404
1405    value_type operator*() const { return cast<SpecificDecl>(*Current); }
1406    value_type operator->() const { return cast<SpecificDecl>(*Current); }
1407
1408    filtered_decl_iterator& operator++() {
1409      ++Current;
1410      SkipToNextDecl();
1411      return *this;
1412    }
1413
1414    filtered_decl_iterator operator++(int) {
1415      filtered_decl_iterator tmp(*this);
1416      ++(*this);
1417      return tmp;
1418    }
1419
1420    friend bool operator==(const filtered_decl_iterator& x,
1421                           const filtered_decl_iterator& y) {
1422      return x.Current == y.Current;
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
1431  /// @brief Add the declaration D into this context.
1432  ///
1433  /// This routine should be invoked when the declaration D has first
1434  /// been declared, to place D into the context where it was
1435  /// (lexically) defined. Every declaration must be added to one
1436  /// (and only one!) context, where it can be visited via
1437  /// [decls_begin(), decls_end()). Once a declaration has been added
1438  /// to its lexical context, the corresponding DeclContext owns the
1439  /// declaration.
1440  ///
1441  /// If D is also a NamedDecl, it will be made visible within its
1442  /// semantic context via makeDeclVisibleInContext.
1443  void addDecl(Decl *D);
1444
1445  /// @brief Add the declaration D into this context, but suppress
1446  /// searches for external declarations with the same name.
1447  ///
1448  /// Although analogous in function to addDecl, this removes an
1449  /// important check.  This is only useful if the Decl is being
1450  /// added in response to an external search; in all other cases,
1451  /// addDecl() is the right function to use.
1452  /// See the ASTImporter for use cases.
1453  void addDeclInternal(Decl *D);
1454
1455  /// @brief Add the declaration D to this context without modifying
1456  /// any lookup tables.
1457  ///
1458  /// This is useful for some operations in dependent contexts where
1459  /// the semantic context might not be dependent;  this basically
1460  /// only happens with friends.
1461  void addHiddenDecl(Decl *D);
1462
1463  /// @brief Removes a declaration from this context.
1464  void removeDecl(Decl *D);
1465
1466  /// @brief Checks whether a declaration is in this context.
1467  bool containsDecl(Decl *D) const;
1468
1469  /// lookup_iterator - An iterator that provides access to the results
1470  /// of looking up a name within this context.
1471  typedef NamedDecl **lookup_iterator;
1472
1473  /// lookup_const_iterator - An iterator that provides non-mutable
1474  /// access to the results of lookup up a name within this context.
1475  typedef NamedDecl * const * lookup_const_iterator;
1476
1477  typedef DeclContextLookupResult lookup_result;
1478  typedef DeclContextLookupConstResult lookup_const_result;
1479
1480  /// lookup - Find the declarations (if any) with the given Name in
1481  /// this context. Returns a range of iterators that contains all of
1482  /// the declarations with this name, with object, function, member,
1483  /// and enumerator names preceding any tag name. Note that this
1484  /// routine will not look into parent contexts.
1485  lookup_result lookup(DeclarationName Name);
1486  lookup_const_result lookup(DeclarationName Name) const {
1487    return const_cast<DeclContext*>(this)->lookup(Name);
1488  }
1489
1490  /// \brief Find the declarations with the given name that are visible
1491  /// within this context; don't attempt to retrieve anything from an
1492  /// external source.
1493  lookup_result noload_lookup(DeclarationName Name);
1494
1495  /// \brief A simplistic name lookup mechanism that performs name lookup
1496  /// into this declaration context without consulting the external source.
1497  ///
1498  /// This function should almost never be used, because it subverts the
1499  /// usual relationship between a DeclContext and the external source.
1500  /// See the ASTImporter for the (few, but important) use cases.
1501  ///
1502  /// FIXME: This is very inefficient; replace uses of it with uses of
1503  /// noload_lookup.
1504  void localUncachedLookup(DeclarationName Name,
1505                           SmallVectorImpl<NamedDecl *> &Results);
1506
1507  /// @brief Makes a declaration visible within this context.
1508  ///
1509  /// This routine makes the declaration D visible to name lookup
1510  /// within this context and, if this is a transparent context,
1511  /// within its parent contexts up to the first enclosing
1512  /// non-transparent context. Making a declaration visible within a
1513  /// context does not transfer ownership of a declaration, and a
1514  /// declaration can be visible in many contexts that aren't its
1515  /// lexical context.
1516  ///
1517  /// If D is a redeclaration of an existing declaration that is
1518  /// visible from this context, as determined by
1519  /// NamedDecl::declarationReplaces, the previous declaration will be
1520  /// replaced with D.
1521  void makeDeclVisibleInContext(NamedDecl *D);
1522
1523  /// all_lookups_iterator - An iterator that provides a view over the results
1524  /// of looking up every possible name.
1525  class all_lookups_iterator;
1526
1527  /// \brief Iterators over all possible lookups within this context.
1528  all_lookups_iterator lookups_begin() const;
1529  all_lookups_iterator lookups_end() const;
1530
1531  /// \brief Iterators over all possible lookups within this context that are
1532  /// currently loaded; don't attempt to retrieve anything from an external
1533  /// source.
1534  all_lookups_iterator noload_lookups_begin() const;
1535  all_lookups_iterator noload_lookups_end() const;
1536
1537  /// udir_iterator - Iterates through the using-directives stored
1538  /// within this context.
1539  typedef UsingDirectiveDecl * const * udir_iterator;
1540
1541  typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
1542
1543  udir_iterator_range getUsingDirectives() const;
1544
1545  udir_iterator using_directives_begin() const {
1546    return getUsingDirectives().first;
1547  }
1548
1549  udir_iterator using_directives_end() const {
1550    return getUsingDirectives().second;
1551  }
1552
1553  // These are all defined in DependentDiagnostic.h.
1554  class ddiag_iterator;
1555  inline ddiag_iterator ddiag_begin() const;
1556  inline ddiag_iterator ddiag_end() const;
1557
1558  // Low-level accessors
1559
1560  /// \brief Mark the lookup table as needing to be built.  This should be
1561  /// used only if setHasExternalLexicalStorage() has been called on any
1562  /// decl context for which this is the primary context.
1563  void setMustBuildLookupTable() {
1564    LookupPtr.setInt(true);
1565  }
1566
1567  /// \brief Retrieve the internal representation of the lookup structure.
1568  /// This may omit some names if we are lazily building the structure.
1569  StoredDeclsMap *getLookupPtr() const { return LookupPtr.getPointer(); }
1570
1571  /// \brief Ensure the lookup structure is fully-built and return it.
1572  StoredDeclsMap *buildLookup();
1573
1574  /// \brief Whether this DeclContext has external storage containing
1575  /// additional declarations that are lexically in this context.
1576  bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1577
1578  /// \brief State whether this DeclContext has external storage for
1579  /// declarations lexically in this context.
1580  void setHasExternalLexicalStorage(bool ES = true) {
1581    ExternalLexicalStorage = ES;
1582  }
1583
1584  /// \brief Whether this DeclContext has external storage containing
1585  /// additional declarations that are visible in this context.
1586  bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1587
1588  /// \brief State whether this DeclContext has external storage for
1589  /// declarations visible in this context.
1590  void setHasExternalVisibleStorage(bool ES = true) {
1591    ExternalVisibleStorage = ES;
1592    if (ES && LookupPtr.getPointer())
1593      NeedToReconcileExternalVisibleStorage = true;
1594  }
1595
1596  /// \brief Determine whether the given declaration is stored in the list of
1597  /// declarations lexically within this context.
1598  bool isDeclInLexicalTraversal(const Decl *D) const {
1599    return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1600                 D == LastDecl);
1601  }
1602
1603  static bool classof(const Decl *D);
1604  static bool classof(const DeclContext *D) { return true; }
1605
1606  LLVM_ATTRIBUTE_USED void dumpDeclContext() const;
1607  LLVM_ATTRIBUTE_USED void dumpLookups() const;
1608  LLVM_ATTRIBUTE_USED void dumpLookups(llvm::raw_ostream &OS) const;
1609
1610private:
1611  void reconcileExternalVisibleStorage();
1612  void LoadLexicalDeclsFromExternalStorage() const;
1613
1614  /// @brief Makes a declaration visible within this context, but
1615  /// suppresses searches for external declarations with the same
1616  /// name.
1617  ///
1618  /// Analogous to makeDeclVisibleInContext, but for the exclusive
1619  /// use of addDeclInternal().
1620  void makeDeclVisibleInContextInternal(NamedDecl *D);
1621
1622  friend class DependentDiagnostic;
1623  StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1624
1625  template<decl_iterator (DeclContext::*Begin)() const,
1626           decl_iterator (DeclContext::*End)() const>
1627  void buildLookupImpl(DeclContext *DCtx);
1628  void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1629                                         bool Rediscoverable);
1630  void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1631};
1632
1633inline bool Decl::isTemplateParameter() const {
1634  return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1635         getKind() == TemplateTemplateParm;
1636}
1637
1638// Specialization selected when ToTy is not a known subclass of DeclContext.
1639template <class ToTy,
1640          bool IsKnownSubtype = ::llvm::is_base_of< DeclContext, ToTy>::value>
1641struct cast_convert_decl_context {
1642  static const ToTy *doit(const DeclContext *Val) {
1643    return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1644  }
1645
1646  static ToTy *doit(DeclContext *Val) {
1647    return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1648  }
1649};
1650
1651// Specialization selected when ToTy is a known subclass of DeclContext.
1652template <class ToTy>
1653struct cast_convert_decl_context<ToTy, true> {
1654  static const ToTy *doit(const DeclContext *Val) {
1655    return static_cast<const ToTy*>(Val);
1656  }
1657
1658  static ToTy *doit(DeclContext *Val) {
1659    return static_cast<ToTy*>(Val);
1660  }
1661};
1662
1663
1664} // end clang.
1665
1666namespace llvm {
1667
1668/// isa<T>(DeclContext*)
1669template <typename To>
1670struct isa_impl<To, ::clang::DeclContext> {
1671  static bool doit(const ::clang::DeclContext &Val) {
1672    return To::classofKind(Val.getDeclKind());
1673  }
1674};
1675
1676/// cast<T>(DeclContext*)
1677template<class ToTy>
1678struct cast_convert_val<ToTy,
1679                        const ::clang::DeclContext,const ::clang::DeclContext> {
1680  static const ToTy &doit(const ::clang::DeclContext &Val) {
1681    return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1682  }
1683};
1684template<class ToTy>
1685struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
1686  static ToTy &doit(::clang::DeclContext &Val) {
1687    return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1688  }
1689};
1690template<class ToTy>
1691struct cast_convert_val<ToTy,
1692                     const ::clang::DeclContext*, const ::clang::DeclContext*> {
1693  static const ToTy *doit(const ::clang::DeclContext *Val) {
1694    return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1695  }
1696};
1697template<class ToTy>
1698struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
1699  static ToTy *doit(::clang::DeclContext *Val) {
1700    return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1701  }
1702};
1703
1704/// Implement cast_convert_val for Decl -> DeclContext conversions.
1705template<class FromTy>
1706struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1707  static ::clang::DeclContext &doit(const FromTy &Val) {
1708    return *FromTy::castToDeclContext(&Val);
1709  }
1710};
1711
1712template<class FromTy>
1713struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1714  static ::clang::DeclContext *doit(const FromTy *Val) {
1715    return FromTy::castToDeclContext(Val);
1716  }
1717};
1718
1719template<class FromTy>
1720struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1721  static const ::clang::DeclContext &doit(const FromTy &Val) {
1722    return *FromTy::castToDeclContext(&Val);
1723  }
1724};
1725
1726template<class FromTy>
1727struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1728  static const ::clang::DeclContext *doit(const FromTy *Val) {
1729    return FromTy::castToDeclContext(Val);
1730  }
1731};
1732
1733} // end namespace llvm
1734
1735#endif
1736