1 //===-- DeclBase.h - Base Classes for representing declarations -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Decl and DeclContext interfaces.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_DECLBASE_H
15 #define LLVM_CLANG_AST_DECLBASE_H
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"
26 class ASTMutationListener;
31 class DeclarationName;
32 class DependentDiagnostic;
35 class LinkageComputer;
36 class LinkageSpecDecl;
40 class ObjCCategoryDecl;
41 class ObjCCategoryImplDecl;
42 class ObjCContainerDecl;
44 class ObjCImplementationDecl;
45 class ObjCInterfaceDecl;
47 class ObjCProtocolDecl;
48 struct PrintingPolicy;
51 class TranslationUnitDecl;
52 class UsingDirectiveDecl;
56 // DeclContext* is only 4-byte aligned on 32-bit systems.
58 class PointerLikeTypeTraits<clang::DeclContext*> {
59 typedef clang::DeclContext* PT;
61 static inline void *getAsVoidPointer(PT P) { return P; }
62 static inline PT getFromVoidPointer(void *P) {
63 return static_cast<PT>(P);
65 enum { NumLowBitsAvailable = 2 };
71 /// \brief Captures the result of checking the availability of a
73 enum AvailabilityResult {
80 /// Decl - This represents one declaration (or definition), e.g. a variable,
81 /// typedef, function, struct, etc.
85 /// \brief Lists the kind of concrete classes of Decl.
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"
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 { };
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.
108 /// These are meant as bitmasks, so that searches in
109 /// C++ can look into the "tag" namespace during ordinary lookup.
111 /// Decl currently provides 15 bits of IDNS bits.
112 enum IdentifierNamespace {
113 /// Labels, declared with 'x:' and referenced with 'goto x'.
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.
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.
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
130 IDNS_Member = 0x0008,
132 /// Namespaces, declared with 'namespace foo {}'.
133 /// Lookup for nested-name-specifiers find these.
134 IDNS_Namespace = 0x0010,
136 /// Ordinary names. In C, everything that's not a label, tag,
137 /// or member ends up here.
138 IDNS_Ordinary = 0x0020,
140 /// Objective C \@protocol.
141 IDNS_ObjCProtocol = 0x0040,
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,
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,
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.
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,
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
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.
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
183 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
184 enum ObjCDeclQualifier {
189 OBJC_TQ_Bycopy = 0x8,
190 OBJC_TQ_Byref = 0x10,
191 OBJC_TQ_Oneway = 0x20
195 // Enumeration values used in the bits stored in NextInContextAndBits.
197 /// \brief Whether this declaration is a top-level declaration (function,
198 /// global variable, etc.) that is lexically inside an objc container
200 TopLevelDeclInObjCContainerFlag = 0x01,
202 /// \brief Whether this declaration is private to the module in which it was
204 ModulePrivateFlag = 0x02
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().
211 /// The extra two bits are used for the TopLevelDeclInObjCContainer and
212 /// ModulePrivate bits.
213 llvm::PointerIntPair<Decl *, 2, unsigned> NextInContextAndBits;
216 friend class DeclContext;
219 DeclContext *SemanticDC;
220 DeclContext *LexicalDC;
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).
233 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
235 /// void A::f(); // SemanticDC == namespace 'A'
236 /// // LexicalDC == global namespace
237 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
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*>();
244 inline DeclContext *getSemanticDC() const {
245 return DeclCtx.get<DeclContext*>();
248 /// Loc - The location of this decl.
251 /// DeclKind - This indicates which class this is.
252 unsigned DeclKind : 8;
254 /// InvalidDecl - This indicates a semantic error occurred.
255 unsigned InvalidDecl : 1;
257 /// HasAttrs - This indicates whether the decl has attributes or not.
258 unsigned HasAttrs : 1;
260 /// Implicit - Whether this declaration was implicitly generated by
261 /// the implementation rather than explicitly written by the user.
262 unsigned Implicit : 1;
264 /// \brief Whether this declaration was "used", meaning that a definition is
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;
274 /// \brief Whether statistic collection is enabled.
275 static bool StatisticsEnabled;
278 /// Access - Used by C++ decls for the access specifier.
279 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
281 friend class CXXClassMemberWrapper;
283 /// \brief Whether this declaration was loaded from an AST file.
284 unsigned FromASTFile : 1;
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.
291 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
292 unsigned IdentifierNamespace : 12;
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;
298 friend class ASTDeclWriter;
299 friend class ASTDeclReader;
300 friend class ASTReader;
301 friend class LinkageComputer;
303 template<typename decl_type> friend class Redeclarable;
306 void CheckAccessDeclContext() const;
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)
318 if (StatisticsEnabled) add(DK);
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)
328 if (StatisticsEnabled) add(DK);
333 /// \brief Allocate memory for a deserialized declaration.
335 /// This routine must be used to allocate memory for any declaration that is
336 /// deserialized from a module file.
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,
345 /// \brief Update a potentially out-of-date declaration.
346 void updateOutOfDate(IdentifierInfo &II) const;
348 Linkage getCachedLinkage() const {
349 return Linkage(CacheValidAndLinkage - 1);
352 void setCachedLinkage(Linkage L) const {
353 CacheValidAndLinkage = L + 1;
356 bool hasCachedLinkage() const {
357 return CacheValidAndLinkage;
362 /// \brief Source range that this declaration covers.
363 virtual SourceRange getSourceRange() const LLVM_READONLY {
364 return SourceRange(getLocation(), getLocation());
366 SourceLocation getLocStart() const LLVM_READONLY {
367 return getSourceRange().getBegin();
369 SourceLocation getLocEnd() const LLVM_READONLY {
370 return getSourceRange().getEnd();
373 SourceLocation getLocation() const { return Loc; }
374 void setLocation(SourceLocation L) { Loc = L; }
376 Kind getKind() const { return static_cast<Kind>(DeclKind); }
377 const char *getDeclKindName() const;
379 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
380 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
382 DeclContext *getDeclContext() {
384 return getSemanticDC();
385 return getMultipleDC()->SemanticDC;
387 const DeclContext *getDeclContext() const {
388 return const_cast<Decl*>(this)->getDeclContext();
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.
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();
401 TranslationUnitDecl *getTranslationUnitDecl();
402 const TranslationUnitDecl *getTranslationUnitDecl() const {
403 return const_cast<Decl*>(this)->getTranslationUnitDecl();
406 bool isInAnonymousNamespace() const;
408 ASTContext &getASTContext() const LLVM_READONLY;
410 void setAccess(AccessSpecifier AS) {
413 CheckAccessDeclContext();
417 AccessSpecifier getAccess() const {
419 CheckAccessDeclContext();
421 return AccessSpecifier(Access);
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);
430 bool hasAttrs() const { return HasAttrs; }
431 void setAttrs(const AttrVec& Attrs) {
432 return setAttrsImpl(Attrs, getASTContext());
434 AttrVec &getAttrs() {
435 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
437 const AttrVec &getAttrs() const;
440 void addAttr(Attr *A) {
442 getAttrs().push_back(A);
444 setAttrs(AttrVec(1, A));
447 typedef AttrVec::const_iterator attr_iterator;
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;
454 attr_iterator attr_end() const {
455 return hasAttrs() ? getAttrs().end() : 0;
458 template <typename T>
460 if (!HasAttrs) return;
462 AttrVec &Vec = getAttrs();
463 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
469 template <typename T>
470 specific_attr_iterator<T> specific_attr_begin() const {
471 return specific_attr_iterator<T>(attr_begin());
473 template <typename T>
474 specific_attr_iterator<T> specific_attr_end() const {
475 return specific_attr_iterator<T>(attr_end());
478 template<typename T> T *getAttr() const {
479 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : 0;
481 template<typename T> bool hasAttr() const {
482 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
485 /// getMaxAlignment - return the maximum alignment specified by attributes
486 /// on this decl, 0 if there are none.
487 unsigned getMaxAlignment() const;
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; }
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; }
500 /// \brief Whether this declaration was used, meaning that a definition
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;
508 /// \brief Set whether the declaration is used, in the sense of odr-use.
510 /// This should only be used immediately after creating a declaration.
511 void setIsUsed() { Used = true; }
513 /// \brief Mark the declaration used, in the sense of odr-use.
515 /// This notifies any mutation listeners in addition to setting a bit
516 /// indicating the declaration is used.
517 void markUsed(ASTContext &C);
519 /// \brief Whether this declaration was referenced.
520 bool isReferenced() const;
522 void setReferenced(bool R = true) { Referenced = R; }
524 /// \brief Whether this declaration is a top-level declaration (function,
525 /// global variable, etc.) that is lexically inside an objc container
527 bool isTopLevelDeclInObjCContainer() const {
528 return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag;
531 void setTopLevelDeclInObjCContainer(bool V = true) {
532 unsigned Bits = NextInContextAndBits.getInt();
534 Bits |= TopLevelDeclInObjCContainerFlag;
536 Bits &= ~TopLevelDeclInObjCContainerFlag;
537 NextInContextAndBits.setInt(Bits);
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;
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();
552 Bits |= ModulePrivateFlag;
554 Bits &= ~ModulePrivateFlag;
555 NextInContextAndBits.setInt(Bits);
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;
566 /// \brief Determine the availability of the given declaration.
568 /// This routine will determine the most restrictive availability of
569 /// the given declaration (e.g., preferring 'unavailable' to
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;
578 /// \brief Determine whether this declaration is marked 'deprecated'.
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;
587 /// \brief Determine whether this declaration is marked 'unavailable'.
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;
596 /// \brief Determine whether this is a weak-imported symbol.
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;
604 /// \brief Determines whether this symbol can be weak-imported,
605 /// e.g., whether it would be well-formed to add the weak_import
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;
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; }
616 /// \brief Retrieve the global declaration ID associated with this
617 /// declaration, which specifies where in the
618 unsigned getGlobalID() const {
620 return *((const unsigned*)this - 1);
624 /// \brief Retrieve the global ID of the module that owns this particular
626 unsigned getOwningModuleID() const {
628 return *((const unsigned*)this - 2);
634 Module *getOwningModuleSlow() const;
637 Module *getOwningModule() const {
638 if (!isFromASTFile())
641 return getOwningModuleSlow();
644 unsigned getIdentifierNamespace() const {
645 return IdentifierNamespace;
647 bool isInIdentifierNamespace(unsigned NS) const {
648 return getIdentifierNamespace() & NS;
650 static unsigned getIdentifierNamespaceForKind(Kind DK);
652 bool hasTagIdentifierNamespace() const {
653 return isTagIdentifierNamespace(getIdentifierNamespace());
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);
660 /// getLexicalDeclContext - The declaration context where this Decl was
661 /// lexically declared (LexicalDC). May be different from
662 /// getDeclContext() (SemanticDC).
666 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
668 /// void A::f(); // SemanticDC == namespace 'A'
669 /// // LexicalDC == global namespace
670 DeclContext *getLexicalDeclContext() {
672 return getSemanticDC();
673 return getMultipleDC()->LexicalDC;
675 const DeclContext *getLexicalDeclContext() const {
676 return const_cast<Decl*>(this)->getLexicalDeclContext();
679 virtual bool isOutOfLine() const {
680 return getLexicalDeclContext() != getDeclContext();
683 /// setDeclContext - Set both the semantic and lexical DeclContext
685 void setDeclContext(DeclContext *DC);
687 void setLexicalDeclContext(DeclContext *DC);
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;
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());
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();
711 /// \brief Whether this particular Decl is a canonical one.
712 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
715 /// \brief Returns the next redeclaration or itself if this is the only decl.
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; }
721 /// \brief Implementation of getPreviousDecl(), to be overridden by any
722 /// subclass that has a redeclaration chain.
723 virtual Decl *getPreviousDeclImpl() { return 0; }
725 /// \brief Implementation of getMostRecentDecl(), to be overridden by any
726 /// subclass that has a redeclaration chain.
727 virtual Decl *getMostRecentDeclImpl() { return this; }
730 /// \brief Iterates through all the redeclarations of the same decl.
731 class redecl_iterator {
732 /// Current - The current declaration.
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;
743 redecl_iterator() : Current(0) { }
744 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
746 reference operator*() const { return Current; }
747 value_type operator->() const { return Current; }
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);
758 redecl_iterator operator++(int) {
759 redecl_iterator tmp(*this);
764 friend bool operator==(redecl_iterator x, redecl_iterator y) {
765 return x.Current == y.Current;
767 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
768 return x.Current != y.Current;
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));
777 redecl_iterator redecls_end() const { return redecl_iterator(); }
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(); }
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();
789 /// \brief True if this is the first declaration in its redeclaration chain.
790 bool isFirstDecl() const {
791 return getPreviousDecl() == 0;
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(); }
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();
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; }
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; }
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;
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();
824 /// isTemplateParameter - Determines whether this declaration is a
825 /// template parameter.
826 bool isTemplateParameter() const;
828 /// isTemplateParameter - Determines whether this declaration is a
829 /// template parameter pack.
830 bool isTemplateParameterPack() const;
832 /// \brief Whether this declaration is a parameter pack.
833 bool isParameterPack() const;
835 /// \brief returns true if this declaration is a template
836 bool isTemplateDecl() const;
838 /// \brief Whether this declaration is a function or function template.
839 bool isFunctionOrFunctionTemplate() const;
841 /// \brief Changes the namespace of this declaration to reflect that it's
842 /// a function-local extern declaration.
844 /// These declarations appear in the lexical context of the extern
845 /// declaration, but in the semantic context of the enclosing namespace
847 void setLocalExternDecl() {
848 assert((IdentifierNamespace == IDNS_Ordinary ||
849 IdentifierNamespace == IDNS_OrdinaryFriend) &&
850 "namespace is not ordinary");
852 Decl *Prev = getPreviousDecl();
853 IdentifierNamespace &= ~IDNS_Ordinary;
855 IdentifierNamespace |= IDNS_LocalExtern;
856 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
857 IdentifierNamespace |= IDNS_Ordinary;
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;
867 /// \brief Changes the namespace of this declaration to reflect that it's
868 /// the object of a friend declaration.
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");
885 Decl *Prev = getPreviousDecl();
886 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
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;
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;
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.
909 /// \brief Determines whether this declaration is the object of a
910 /// friend declaration and, if so, what kind.
912 /// There is currently no direct way to find the associated FriendDecl.
913 FriendObjectKind getFriendObjectKind() const {
915 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
916 if (!mask) return FOK_None;
917 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
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;
929 static bool classofKind(Kind K) { return true; }
930 static DeclContext *castToDeclContext(const Decl *);
931 static Decl *castFromDeclContext(const DeclContext *);
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;
947 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
948 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
952 ASTMutationListener *getASTMutationListener() const;
955 /// \brief Determine whether two declarations declare the same entity.
956 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
963 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
966 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
967 /// doing something to a specific decl.
968 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
974 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
975 SourceManager &sm, const char *Msg)
976 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
978 virtual void print(raw_ostream &OS) const;
981 typedef llvm::MutableArrayRef<NamedDecl*> DeclContextLookupResult;
983 typedef ArrayRef<NamedDecl *> DeclContextLookupConstResult;
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):
989 /// TranslationUnitDecl
994 /// ObjCContainerDecl
999 /// DeclKind - This indicates which class this is.
1000 unsigned DeclKind : 8;
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;
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;
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
1016 mutable bool NeedToReconcileExternalVisibleStorage : 1;
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;
1028 /// FirstDecl - The first declaration stored within this declaration
1030 mutable Decl *FirstDecl;
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;
1038 friend class ExternalASTSource;
1039 friend class ASTDeclReader;
1040 friend class ASTWriter;
1042 /// \brief Build up a chain of declarations.
1044 /// \returns the first/last pair of declarations.
1045 static std::pair<Decl *, Decl *>
1046 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1048 DeclContext(Decl::Kind K)
1049 : DeclKind(K), ExternalLexicalStorage(false),
1050 ExternalVisibleStorage(false),
1051 NeedToReconcileExternalVisibleStorage(false), LookupPtr(0, false),
1052 FirstDecl(0), LastDecl(0) {}
1057 Decl::Kind getDeclKind() const {
1058 return static_cast<Decl::Kind>(DeclKind);
1060 const char *getDeclKindName() const;
1062 /// getParent - Returns the containing DeclContext.
1063 DeclContext *getParent() {
1064 return cast<Decl>(this)->getDeclContext();
1066 const DeclContext *getParent() const {
1067 return const_cast<DeclContext*>(this)->getParent();
1070 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1071 /// different from getParent, e.g.:
1076 /// struct A::S {}; // getParent() == namespace 'A'
1077 /// // getLexicalParent() == translation unit
1079 DeclContext *getLexicalParent() {
1080 return cast<Decl>(this)->getLexicalDeclContext();
1082 const DeclContext *getLexicalParent() const {
1083 return const_cast<DeclContext*>(this)->getLexicalParent();
1086 DeclContext *getLookupParent();
1088 const DeclContext *getLookupParent() const {
1089 return const_cast<DeclContext*>(this)->getLookupParent();
1092 ASTContext &getParentASTContext() const {
1093 return cast<Decl>(this)->getASTContext();
1096 bool isClosure() const {
1097 return DeclKind == Decl::Block;
1100 bool isObjCContainer() const {
1102 case Decl::ObjCCategory:
1103 case Decl::ObjCCategoryImpl:
1104 case Decl::ObjCImplementation:
1105 case Decl::ObjCInterface:
1106 case Decl::ObjCProtocol:
1112 bool isFunctionOrMethod() const {
1115 case Decl::Captured:
1116 case Decl::ObjCMethod:
1119 return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1123 bool isFileContext() const {
1124 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1127 bool isTranslationUnit() const {
1128 return DeclKind == Decl::TranslationUnit;
1131 bool isRecord() const {
1132 return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1135 bool isNamespace() const {
1136 return DeclKind == Decl::Namespace;
1139 bool isInlineNamespace() const;
1141 /// \brief Determines whether this context is dependent on a
1142 /// template parameter.
1143 bool isDependentContext() const;
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:
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;
1162 /// \brief Determines whether this context or some of its ancestors is a
1163 /// linkage specification context that specifies C linkage.
1164 bool isExternCContext() const;
1166 /// \brief Determines whether this context or some of its ancestors is a
1167 /// linkage specification context that specifies C++ linkage.
1168 bool isExternCXXContext() const;
1170 /// \brief Determine whether this declaration context is equivalent
1171 /// to the declaration context DC.
1172 bool Equals(const DeclContext *DC) const {
1173 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1176 /// \brief Determine whether this declaration context encloses the
1177 /// declaration context DC.
1178 bool Encloses(const DeclContext *DC) const;
1180 /// \brief Find the nearest non-closure ancestor of this context,
1181 /// i.e. the innermost semantic parent of this context which is not
1182 /// a closure. A context may be its own non-closure ancestor.
1183 Decl *getNonClosureAncestor();
1184 const Decl *getNonClosureAncestor() const {
1185 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1188 /// getPrimaryContext - There may be many different
1189 /// declarations of the same entity (including forward declarations
1190 /// of classes, multiple definitions of namespaces, etc.), each with
1191 /// a different set of declarations. This routine returns the
1192 /// "primary" DeclContext structure, which will contain the
1193 /// information needed to perform name lookup into this context.
1194 DeclContext *getPrimaryContext();
1195 const DeclContext *getPrimaryContext() const {
1196 return const_cast<DeclContext*>(this)->getPrimaryContext();
1199 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1200 /// other entities of the same name, or where it is a redeclaration if the
1201 /// two entities are compatible. This skips through transparent contexts.
1202 DeclContext *getRedeclContext();
1203 const DeclContext *getRedeclContext() const {
1204 return const_cast<DeclContext *>(this)->getRedeclContext();
1207 /// \brief Retrieve the nearest enclosing namespace context.
1208 DeclContext *getEnclosingNamespaceContext();
1209 const DeclContext *getEnclosingNamespaceContext() const {
1210 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1213 /// \brief Test if this context is part of the enclosing namespace set of
1214 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1215 /// isn't a namespace, this is equivalent to Equals().
1217 /// The enclosing namespace set of a namespace is the namespace and, if it is
1218 /// inline, its enclosing namespace, recursively.
1219 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1221 /// \brief Collects all of the declaration contexts that are semantically
1222 /// connected to this declaration context.
1224 /// For declaration contexts that have multiple semantically connected but
1225 /// syntactically distinct contexts, such as C++ namespaces, this routine
1226 /// retrieves the complete set of such declaration contexts in source order.
1227 /// For example, given:
1238 /// The \c Contexts parameter will contain both definitions of N.
1240 /// \param Contexts Will be cleared and set to the set of declaration
1241 /// contexts that are semanticaly connected to this declaration context,
1242 /// in source order, including this context (which may be the only result,
1243 /// for non-namespace contexts).
1244 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1246 /// decl_iterator - Iterates through the declarations stored
1247 /// within this context.
1248 class decl_iterator {
1249 /// Current - The current declaration.
1253 typedef Decl *value_type;
1254 typedef const value_type &reference;
1255 typedef const value_type *pointer;
1256 typedef std::forward_iterator_tag iterator_category;
1257 typedef std::ptrdiff_t difference_type;
1259 decl_iterator() : Current(0) { }
1260 explicit decl_iterator(Decl *C) : Current(C) { }
1262 reference operator*() const { return Current; }
1263 // This doesn't meet the iterator requirements, but it's convenient
1264 value_type operator->() const { return Current; }
1266 decl_iterator& operator++() {
1267 Current = Current->getNextDeclInContext();
1271 decl_iterator operator++(int) {
1272 decl_iterator tmp(*this);
1277 friend bool operator==(decl_iterator x, decl_iterator y) {
1278 return x.Current == y.Current;
1280 friend bool operator!=(decl_iterator x, decl_iterator y) {
1281 return x.Current != y.Current;
1285 /// decls_begin/decls_end - Iterate over the declarations stored in
1287 decl_iterator decls_begin() const;
1288 decl_iterator decls_end() const { return decl_iterator(); }
1289 bool decls_empty() const;
1291 /// noload_decls_begin/end - Iterate over the declarations stored in this
1292 /// context that are currently loaded; don't attempt to retrieve anything
1293 /// from an external source.
1294 decl_iterator noload_decls_begin() const;
1295 decl_iterator noload_decls_end() const { return decl_iterator(); }
1297 /// specific_decl_iterator - Iterates over a subrange of
1298 /// declarations stored in a DeclContext, providing only those that
1299 /// are of type SpecificDecl (or a class derived from it). This
1300 /// iterator is used, for example, to provide iteration over just
1301 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1302 template<typename SpecificDecl>
1303 class specific_decl_iterator {
1304 /// Current - The current, underlying declaration iterator, which
1305 /// will either be NULL or will point to a declaration of
1306 /// type SpecificDecl.
1307 DeclContext::decl_iterator Current;
1309 /// SkipToNextDecl - Advances the current position up to the next
1310 /// declaration of type SpecificDecl that also meets the criteria
1311 /// required by Acceptable.
1312 void SkipToNextDecl() {
1313 while (*Current && !isa<SpecificDecl>(*Current))
1318 typedef SpecificDecl *value_type;
1319 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1320 // type) if we ever have a need for them.
1321 typedef void reference;
1322 typedef void pointer;
1323 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1325 typedef std::forward_iterator_tag iterator_category;
1327 specific_decl_iterator() : Current() { }
1329 /// specific_decl_iterator - Construct a new iterator over a
1330 /// subset of the declarations the range [C,
1331 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1332 /// member function of SpecificDecl that should return true for
1333 /// all of the SpecificDecl instances that will be in the subset
1334 /// of iterators. For example, if you want Objective-C instance
1335 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1336 /// &ObjCMethodDecl::isInstanceMethod.
1337 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1341 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1342 // This doesn't meet the iterator requirements, but it's convenient
1343 value_type operator->() const { return **this; }
1345 specific_decl_iterator& operator++() {
1351 specific_decl_iterator operator++(int) {
1352 specific_decl_iterator tmp(*this);
1357 friend bool operator==(const specific_decl_iterator& x,
1358 const specific_decl_iterator& y) {
1359 return x.Current == y.Current;
1362 friend bool operator!=(const specific_decl_iterator& x,
1363 const specific_decl_iterator& y) {
1364 return x.Current != y.Current;
1368 /// \brief Iterates over a filtered subrange of declarations stored
1369 /// in a DeclContext.
1371 /// This iterator visits only those declarations that are of type
1372 /// SpecificDecl (or a class derived from it) and that meet some
1373 /// additional run-time criteria. This iterator is used, for
1374 /// example, to provide access to the instance methods within an
1375 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1376 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1377 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1378 class filtered_decl_iterator {
1379 /// Current - The current, underlying declaration iterator, which
1380 /// will either be NULL or will point to a declaration of
1381 /// type SpecificDecl.
1382 DeclContext::decl_iterator Current;
1384 /// SkipToNextDecl - Advances the current position up to the next
1385 /// declaration of type SpecificDecl that also meets the criteria
1386 /// required by Acceptable.
1387 void SkipToNextDecl() {
1389 (!isa<SpecificDecl>(*Current) ||
1390 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1395 typedef SpecificDecl *value_type;
1396 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1397 // type) if we ever have a need for them.
1398 typedef void reference;
1399 typedef void pointer;
1400 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1402 typedef std::forward_iterator_tag iterator_category;
1404 filtered_decl_iterator() : Current() { }
1406 /// filtered_decl_iterator - Construct a new iterator over a
1407 /// subset of the declarations the range [C,
1408 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1409 /// member function of SpecificDecl that should return true for
1410 /// all of the SpecificDecl instances that will be in the subset
1411 /// of iterators. For example, if you want Objective-C instance
1412 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1413 /// &ObjCMethodDecl::isInstanceMethod.
1414 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1418 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1419 value_type operator->() const { return cast<SpecificDecl>(*Current); }
1421 filtered_decl_iterator& operator++() {
1427 filtered_decl_iterator operator++(int) {
1428 filtered_decl_iterator tmp(*this);
1433 friend bool operator==(const filtered_decl_iterator& x,
1434 const filtered_decl_iterator& y) {
1435 return x.Current == y.Current;
1438 friend bool operator!=(const filtered_decl_iterator& x,
1439 const filtered_decl_iterator& y) {
1440 return x.Current != y.Current;
1444 /// @brief Add the declaration D into this context.
1446 /// This routine should be invoked when the declaration D has first
1447 /// been declared, to place D into the context where it was
1448 /// (lexically) defined. Every declaration must be added to one
1449 /// (and only one!) context, where it can be visited via
1450 /// [decls_begin(), decls_end()). Once a declaration has been added
1451 /// to its lexical context, the corresponding DeclContext owns the
1454 /// If D is also a NamedDecl, it will be made visible within its
1455 /// semantic context via makeDeclVisibleInContext.
1456 void addDecl(Decl *D);
1458 /// @brief Add the declaration D into this context, but suppress
1459 /// searches for external declarations with the same name.
1461 /// Although analogous in function to addDecl, this removes an
1462 /// important check. This is only useful if the Decl is being
1463 /// added in response to an external search; in all other cases,
1464 /// addDecl() is the right function to use.
1465 /// See the ASTImporter for use cases.
1466 void addDeclInternal(Decl *D);
1468 /// @brief Add the declaration D to this context without modifying
1469 /// any lookup tables.
1471 /// This is useful for some operations in dependent contexts where
1472 /// the semantic context might not be dependent; this basically
1473 /// only happens with friends.
1474 void addHiddenDecl(Decl *D);
1476 /// @brief Removes a declaration from this context.
1477 void removeDecl(Decl *D);
1479 /// @brief Checks whether a declaration is in this context.
1480 bool containsDecl(Decl *D) const;
1482 /// lookup_iterator - An iterator that provides access to the results
1483 /// of looking up a name within this context.
1484 typedef NamedDecl **lookup_iterator;
1486 /// lookup_const_iterator - An iterator that provides non-mutable
1487 /// access to the results of lookup up a name within this context.
1488 typedef NamedDecl * const * lookup_const_iterator;
1490 typedef DeclContextLookupResult lookup_result;
1491 typedef DeclContextLookupConstResult lookup_const_result;
1493 /// lookup - Find the declarations (if any) with the given Name in
1494 /// this context. Returns a range of iterators that contains all of
1495 /// the declarations with this name, with object, function, member,
1496 /// and enumerator names preceding any tag name. Note that this
1497 /// routine will not look into parent contexts.
1498 lookup_result lookup(DeclarationName Name);
1499 lookup_const_result lookup(DeclarationName Name) const {
1500 return const_cast<DeclContext*>(this)->lookup(Name);
1503 /// \brief Find the declarations with the given name that are visible
1504 /// within this context; don't attempt to retrieve anything from an
1505 /// external source.
1506 lookup_result noload_lookup(DeclarationName Name);
1508 /// \brief A simplistic name lookup mechanism that performs name lookup
1509 /// into this declaration context without consulting the external source.
1511 /// This function should almost never be used, because it subverts the
1512 /// usual relationship between a DeclContext and the external source.
1513 /// See the ASTImporter for the (few, but important) use cases.
1515 /// FIXME: This is very inefficient; replace uses of it with uses of
1517 void localUncachedLookup(DeclarationName Name,
1518 SmallVectorImpl<NamedDecl *> &Results);
1520 /// @brief Makes a declaration visible within this context.
1522 /// This routine makes the declaration D visible to name lookup
1523 /// within this context and, if this is a transparent context,
1524 /// within its parent contexts up to the first enclosing
1525 /// non-transparent context. Making a declaration visible within a
1526 /// context does not transfer ownership of a declaration, and a
1527 /// declaration can be visible in many contexts that aren't its
1528 /// lexical context.
1530 /// If D is a redeclaration of an existing declaration that is
1531 /// visible from this context, as determined by
1532 /// NamedDecl::declarationReplaces, the previous declaration will be
1533 /// replaced with D.
1534 void makeDeclVisibleInContext(NamedDecl *D);
1536 /// all_lookups_iterator - An iterator that provides a view over the results
1537 /// of looking up every possible name.
1538 class all_lookups_iterator;
1540 /// \brief Iterators over all possible lookups within this context.
1541 all_lookups_iterator lookups_begin() const;
1542 all_lookups_iterator lookups_end() const;
1544 /// \brief Iterators over all possible lookups within this context that are
1545 /// currently loaded; don't attempt to retrieve anything from an external
1547 all_lookups_iterator noload_lookups_begin() const;
1548 all_lookups_iterator noload_lookups_end() const;
1550 /// udir_iterator - Iterates through the using-directives stored
1551 /// within this context.
1552 typedef UsingDirectiveDecl * const * udir_iterator;
1554 typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
1556 udir_iterator_range getUsingDirectives() const;
1558 udir_iterator using_directives_begin() const {
1559 return getUsingDirectives().first;
1562 udir_iterator using_directives_end() const {
1563 return getUsingDirectives().second;
1566 // These are all defined in DependentDiagnostic.h.
1567 class ddiag_iterator;
1568 inline ddiag_iterator ddiag_begin() const;
1569 inline ddiag_iterator ddiag_end() const;
1571 // Low-level accessors
1573 /// \brief Mark the lookup table as needing to be built. This should be
1574 /// used only if setHasExternalLexicalStorage() has been called on any
1575 /// decl context for which this is the primary context.
1576 void setMustBuildLookupTable() {
1577 LookupPtr.setInt(true);
1580 /// \brief Retrieve the internal representation of the lookup structure.
1581 /// This may omit some names if we are lazily building the structure.
1582 StoredDeclsMap *getLookupPtr() const { return LookupPtr.getPointer(); }
1584 /// \brief Ensure the lookup structure is fully-built and return it.
1585 StoredDeclsMap *buildLookup();
1587 /// \brief Whether this DeclContext has external storage containing
1588 /// additional declarations that are lexically in this context.
1589 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1591 /// \brief State whether this DeclContext has external storage for
1592 /// declarations lexically in this context.
1593 void setHasExternalLexicalStorage(bool ES = true) {
1594 ExternalLexicalStorage = ES;
1597 /// \brief Whether this DeclContext has external storage containing
1598 /// additional declarations that are visible in this context.
1599 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1601 /// \brief State whether this DeclContext has external storage for
1602 /// declarations visible in this context.
1603 void setHasExternalVisibleStorage(bool ES = true) {
1604 ExternalVisibleStorage = ES;
1605 if (ES && LookupPtr.getPointer())
1606 NeedToReconcileExternalVisibleStorage = true;
1609 /// \brief Determine whether the given declaration is stored in the list of
1610 /// declarations lexically within this context.
1611 bool isDeclInLexicalTraversal(const Decl *D) const {
1612 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1616 static bool classof(const Decl *D);
1617 static bool classof(const DeclContext *D) { return true; }
1619 LLVM_ATTRIBUTE_USED void dumpDeclContext() const;
1620 LLVM_ATTRIBUTE_USED void dumpLookups() const;
1621 LLVM_ATTRIBUTE_USED void dumpLookups(llvm::raw_ostream &OS) const;
1624 void reconcileExternalVisibleStorage();
1625 void LoadLexicalDeclsFromExternalStorage() const;
1627 /// @brief Makes a declaration visible within this context, but
1628 /// suppresses searches for external declarations with the same
1631 /// Analogous to makeDeclVisibleInContext, but for the exclusive
1632 /// use of addDeclInternal().
1633 void makeDeclVisibleInContextInternal(NamedDecl *D);
1635 friend class DependentDiagnostic;
1636 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1638 template<decl_iterator (DeclContext::*Begin)() const,
1639 decl_iterator (DeclContext::*End)() const>
1640 void buildLookupImpl(DeclContext *DCtx);
1641 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1642 bool Rediscoverable);
1643 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1646 inline bool Decl::isTemplateParameter() const {
1647 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1648 getKind() == TemplateTemplateParm;
1651 // Specialization selected when ToTy is not a known subclass of DeclContext.
1652 template <class ToTy,
1653 bool IsKnownSubtype = ::llvm::is_base_of< DeclContext, ToTy>::value>
1654 struct cast_convert_decl_context {
1655 static const ToTy *doit(const DeclContext *Val) {
1656 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1659 static ToTy *doit(DeclContext *Val) {
1660 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1664 // Specialization selected when ToTy is a known subclass of DeclContext.
1665 template <class ToTy>
1666 struct cast_convert_decl_context<ToTy, true> {
1667 static const ToTy *doit(const DeclContext *Val) {
1668 return static_cast<const ToTy*>(Val);
1671 static ToTy *doit(DeclContext *Val) {
1672 return static_cast<ToTy*>(Val);
1681 /// isa<T>(DeclContext*)
1682 template <typename To>
1683 struct isa_impl<To, ::clang::DeclContext> {
1684 static bool doit(const ::clang::DeclContext &Val) {
1685 return To::classofKind(Val.getDeclKind());
1689 /// cast<T>(DeclContext*)
1690 template<class ToTy>
1691 struct 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);
1697 template<class ToTy>
1698 struct 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);
1703 template<class ToTy>
1704 struct cast_convert_val<ToTy,
1705 const ::clang::DeclContext*, const ::clang::DeclContext*> {
1706 static const ToTy *doit(const ::clang::DeclContext *Val) {
1707 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1710 template<class ToTy>
1711 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
1712 static ToTy *doit(::clang::DeclContext *Val) {
1713 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1717 /// Implement cast_convert_val for Decl -> DeclContext conversions.
1718 template<class FromTy>
1719 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1720 static ::clang::DeclContext &doit(const FromTy &Val) {
1721 return *FromTy::castToDeclContext(&Val);
1725 template<class FromTy>
1726 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1727 static ::clang::DeclContext *doit(const FromTy *Val) {
1728 return FromTy::castToDeclContext(Val);
1732 template<class FromTy>
1733 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1734 static const ::clang::DeclContext &doit(const FromTy &Val) {
1735 return *FromTy::castToDeclContext(&Val);
1739 template<class FromTy>
1740 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1741 static const ::clang::DeclContext *doit(const FromTy *Val) {
1742 return FromTy::castToDeclContext(Val);
1746 } // end namespace llvm