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/Specifiers.h"
20 #include "llvm/ADT/PointerUnion.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/PrettyStackTrace.h"
26 class ASTMutationListener;
31 class DeclarationName;
32 class DependentDiagnostic;
36 enum Linkage : unsigned char;
37 class LinkageComputer;
38 class LinkageSpecDecl;
42 class ObjCCategoryDecl;
43 class ObjCCategoryImplDecl;
44 class ObjCContainerDecl;
46 class ObjCImplementationDecl;
47 class ObjCInterfaceDecl;
49 class ObjCProtocolDecl;
50 struct PrintingPolicy;
54 class TranslationUnitDecl;
55 class UsingDirectiveDecl;
60 /// \brief Captures the result of checking the availability of a
62 enum AvailabilityResult {
69 /// Decl - This represents one declaration (or definition), e.g. a variable,
70 /// typedef, function, struct, etc.
74 /// \brief Lists the kind of concrete classes of Decl.
76 #define DECL(DERIVED, BASE) DERIVED,
77 #define ABSTRACT_DECL(DECL)
78 #define DECL_RANGE(BASE, START, END) \
79 first##BASE = START, last##BASE = END,
80 #define LAST_DECL_RANGE(BASE, START, END) \
81 first##BASE = START, last##BASE = END
82 #include "clang/AST/DeclNodes.inc"
85 /// \brief A placeholder type used to construct an empty shell of a
86 /// decl-derived type that will be filled in later (e.g., by some
87 /// deserialization method).
88 struct EmptyShell { };
90 /// IdentifierNamespace - The different namespaces in which
91 /// declarations may appear. According to C99 6.2.3, there are
92 /// four namespaces, labels, tags, members and ordinary
93 /// identifiers. C++ describes lookup completely differently:
94 /// certain lookups merely "ignore" certain kinds of declarations,
95 /// usually based on whether the declaration is of a type, etc.
97 /// These are meant as bitmasks, so that searches in
98 /// C++ can look into the "tag" namespace during ordinary lookup.
100 /// Decl currently provides 15 bits of IDNS bits.
101 enum IdentifierNamespace {
102 /// Labels, declared with 'x:' and referenced with 'goto x'.
105 /// Tags, declared with 'struct foo;' and referenced with
106 /// 'struct foo'. All tags are also types. This is what
107 /// elaborated-type-specifiers look for in C.
110 /// Types, declared with 'struct foo', typedefs, etc.
111 /// This is what elaborated-type-specifiers look for in C++,
112 /// but note that it's ill-formed to find a non-tag.
115 /// Members, declared with object declarations within tag
116 /// definitions. In C, these can only be found by "qualified"
117 /// lookup in member expressions. In C++, they're found by
119 IDNS_Member = 0x0008,
121 /// Namespaces, declared with 'namespace foo {}'.
122 /// Lookup for nested-name-specifiers find these.
123 IDNS_Namespace = 0x0010,
125 /// Ordinary names. In C, everything that's not a label, tag,
126 /// or member ends up here.
127 IDNS_Ordinary = 0x0020,
129 /// Objective C \@protocol.
130 IDNS_ObjCProtocol = 0x0040,
132 /// This declaration is a friend function. A friend function
133 /// declaration is always in this namespace but may also be in
134 /// IDNS_Ordinary if it was previously declared.
135 IDNS_OrdinaryFriend = 0x0080,
137 /// This declaration is a friend class. A friend class
138 /// declaration is always in this namespace but may also be in
139 /// IDNS_Tag|IDNS_Type if it was previously declared.
140 IDNS_TagFriend = 0x0100,
142 /// This declaration is a using declaration. A using declaration
143 /// *introduces* a number of other declarations into the current
144 /// scope, and those declarations use the IDNS of their targets,
145 /// but the actual using declarations go in this namespace.
148 /// This declaration is a C++ operator declared in a non-class
149 /// context. All such operators are also in IDNS_Ordinary.
150 /// C++ lexical operator lookup looks for these.
151 IDNS_NonMemberOperator = 0x0400,
153 /// This declaration is a function-local extern declaration of a
154 /// variable or function. This may also be IDNS_Ordinary if it
155 /// has been declared outside any function.
156 IDNS_LocalExtern = 0x0800
159 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
160 /// parameter types in method declarations. Other than remembering
161 /// them and mangling them into the method's signature string, these
162 /// are ignored by the compiler; they are consumed by certain
163 /// remote-messaging frameworks.
165 /// in, inout, and out are mutually exclusive and apply only to
166 /// method parameters. bycopy and byref are mutually exclusive and
167 /// apply only to method parameters (?). oneway applies only to
168 /// results. All of these expect their corresponding parameter to
169 /// have a particular type. None of this is currently enforced by
172 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
173 enum ObjCDeclQualifier {
178 OBJC_TQ_Bycopy = 0x8,
179 OBJC_TQ_Byref = 0x10,
180 OBJC_TQ_Oneway = 0x20
184 // Enumeration values used in the bits stored in NextInContextAndBits.
186 /// \brief Whether this declaration is a top-level declaration (function,
187 /// global variable, etc.) that is lexically inside an objc container
189 TopLevelDeclInObjCContainerFlag = 0x01,
191 /// \brief Whether this declaration is private to the module in which it was
193 ModulePrivateFlag = 0x02
196 /// \brief The next declaration within the same lexical
197 /// DeclContext. These pointers form the linked list that is
198 /// traversed via DeclContext's decls_begin()/decls_end().
200 /// The extra two bits are used for the TopLevelDeclInObjCContainer and
201 /// ModulePrivate bits.
202 llvm::PointerIntPair<Decl *, 2, unsigned> NextInContextAndBits;
205 friend class DeclContext;
208 DeclContext *SemanticDC;
209 DeclContext *LexicalDC;
213 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
214 /// For declarations that don't contain C++ scope specifiers, it contains
215 /// the DeclContext where the Decl was declared.
216 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
217 /// with the context where it semantically belongs (SemanticDC) and the
218 /// context where it was lexically declared (LexicalDC).
222 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
224 /// void A::f(); // SemanticDC == namespace 'A'
225 /// // LexicalDC == global namespace
226 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
228 inline bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
229 inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
230 inline MultipleDC *getMultipleDC() const {
231 return DeclCtx.get<MultipleDC*>();
233 inline DeclContext *getSemanticDC() const {
234 return DeclCtx.get<DeclContext*>();
237 /// Loc - The location of this decl.
240 /// DeclKind - This indicates which class this is.
241 unsigned DeclKind : 8;
243 /// InvalidDecl - This indicates a semantic error occurred.
244 unsigned InvalidDecl : 1;
246 /// HasAttrs - This indicates whether the decl has attributes or not.
247 unsigned HasAttrs : 1;
249 /// Implicit - Whether this declaration was implicitly generated by
250 /// the implementation rather than explicitly written by the user.
251 unsigned Implicit : 1;
253 /// \brief Whether this declaration was "used", meaning that a definition is
257 /// \brief Whether this declaration was "referenced".
258 /// The difference with 'Used' is whether the reference appears in a
259 /// evaluated context or not, e.g. functions used in uninstantiated templates
260 /// are regarded as "referenced" but not "used".
261 unsigned Referenced : 1;
263 /// \brief Whether statistic collection is enabled.
264 static bool StatisticsEnabled;
267 /// Access - Used by C++ decls for the access specifier.
268 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
270 friend class CXXClassMemberWrapper;
272 /// \brief Whether this declaration was loaded from an AST file.
273 unsigned FromASTFile : 1;
275 /// \brief Whether this declaration is hidden from normal name lookup, e.g.,
276 /// because it is was loaded from an AST file is either module-private or
277 /// because its submodule has not been made visible.
280 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
281 unsigned IdentifierNamespace : 12;
283 /// \brief If 0, we have not computed the linkage of this declaration.
284 /// Otherwise, it is the linkage + 1.
285 mutable unsigned CacheValidAndLinkage : 3;
287 friend class ASTDeclWriter;
288 friend class ASTDeclReader;
289 friend class ASTReader;
290 friend class LinkageComputer;
292 template<typename decl_type> friend class Redeclarable;
294 /// \brief Allocate memory for a deserialized declaration.
296 /// This routine must be used to allocate memory for any declaration that is
297 /// deserialized from a module file.
299 /// \param Size The size of the allocated object.
300 /// \param Ctx The context in which we will allocate memory.
301 /// \param ID The global ID of the deserialized declaration.
302 /// \param Extra The amount of extra space to allocate after the object.
303 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
304 std::size_t Extra = 0);
306 /// \brief Allocate memory for a non-deserialized declaration.
307 void *operator new(std::size_t Size, const ASTContext &Ctx,
308 DeclContext *Parent, std::size_t Extra = 0);
311 bool AccessDeclContextSanity() const;
315 Decl(Kind DK, DeclContext *DC, SourceLocation L)
316 : NextInContextAndBits(), DeclCtx(DC),
317 Loc(L), DeclKind(DK), InvalidDecl(0),
318 HasAttrs(false), Implicit(false), Used(false), Referenced(false),
319 Access(AS_none), FromASTFile(0), Hidden(0),
320 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
321 CacheValidAndLinkage(0)
323 if (StatisticsEnabled) add(DK);
326 Decl(Kind DK, EmptyShell Empty)
327 : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0),
328 HasAttrs(false), Implicit(false), Used(false), Referenced(false),
329 Access(AS_none), FromASTFile(0), Hidden(0),
330 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
331 CacheValidAndLinkage(0)
333 if (StatisticsEnabled) add(DK);
338 /// \brief Update a potentially out-of-date declaration.
339 void updateOutOfDate(IdentifierInfo &II) const;
341 Linkage getCachedLinkage() const {
342 return Linkage(CacheValidAndLinkage - 1);
345 void setCachedLinkage(Linkage L) const {
346 CacheValidAndLinkage = L + 1;
349 bool hasCachedLinkage() const {
350 return CacheValidAndLinkage;
355 /// \brief Source range that this declaration covers.
356 virtual SourceRange getSourceRange() const LLVM_READONLY {
357 return SourceRange(getLocation(), getLocation());
359 SourceLocation getLocStart() const LLVM_READONLY {
360 return getSourceRange().getBegin();
362 SourceLocation getLocEnd() const LLVM_READONLY {
363 return getSourceRange().getEnd();
366 SourceLocation getLocation() const { return Loc; }
367 void setLocation(SourceLocation L) { Loc = L; }
369 Kind getKind() const { return static_cast<Kind>(DeclKind); }
370 const char *getDeclKindName() const;
372 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
373 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
375 DeclContext *getDeclContext() {
377 return getSemanticDC();
378 return getMultipleDC()->SemanticDC;
380 const DeclContext *getDeclContext() const {
381 return const_cast<Decl*>(this)->getDeclContext();
384 /// Find the innermost non-closure ancestor of this declaration,
385 /// walking up through blocks, lambdas, etc. If that ancestor is
386 /// not a code context (!isFunctionOrMethod()), returns null.
388 /// A declaration may be its own non-closure context.
389 Decl *getNonClosureContext();
390 const Decl *getNonClosureContext() const {
391 return const_cast<Decl*>(this)->getNonClosureContext();
394 TranslationUnitDecl *getTranslationUnitDecl();
395 const TranslationUnitDecl *getTranslationUnitDecl() const {
396 return const_cast<Decl*>(this)->getTranslationUnitDecl();
399 bool isInAnonymousNamespace() const;
401 bool isInStdNamespace() const;
403 ASTContext &getASTContext() const LLVM_READONLY;
405 void setAccess(AccessSpecifier AS) {
407 assert(AccessDeclContextSanity());
410 AccessSpecifier getAccess() const {
411 assert(AccessDeclContextSanity());
412 return AccessSpecifier(Access);
415 /// \brief Retrieve the access specifier for this declaration, even though
416 /// it may not yet have been properly set.
417 AccessSpecifier getAccessUnsafe() const {
418 return AccessSpecifier(Access);
421 bool hasAttrs() const { return HasAttrs; }
422 void setAttrs(const AttrVec& Attrs) {
423 return setAttrsImpl(Attrs, getASTContext());
425 AttrVec &getAttrs() {
426 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
428 const AttrVec &getAttrs() const;
431 void addAttr(Attr *A) {
433 getAttrs().push_back(A);
435 setAttrs(AttrVec(1, A));
438 typedef AttrVec::const_iterator attr_iterator;
439 typedef llvm::iterator_range<attr_iterator> attr_range;
441 attr_range attrs() const {
442 return attr_range(attr_begin(), attr_end());
445 attr_iterator attr_begin() const {
446 return hasAttrs() ? getAttrs().begin() : nullptr;
448 attr_iterator attr_end() const {
449 return hasAttrs() ? getAttrs().end() : nullptr;
452 template <typename T>
454 if (!HasAttrs) return;
456 AttrVec &Vec = getAttrs();
457 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
463 template <typename T>
464 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
465 return llvm::iterator_range<specific_attr_iterator<T>>(
466 specific_attr_begin<T>(), specific_attr_end<T>());
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()) : nullptr;
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 any declaration of this entity was referenced.
520 bool isReferenced() const;
522 /// \brief Whether this declaration was referenced. This should not be relied
523 /// upon for anything other than debugging.
524 bool isThisDeclarationReferenced() const { return Referenced; }
526 void setReferenced(bool R = true) { Referenced = R; }
528 /// \brief Whether this declaration is a top-level declaration (function,
529 /// global variable, etc.) that is lexically inside an objc container
531 bool isTopLevelDeclInObjCContainer() const {
532 return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag;
535 void setTopLevelDeclInObjCContainer(bool V = true) {
536 unsigned Bits = NextInContextAndBits.getInt();
538 Bits |= TopLevelDeclInObjCContainerFlag;
540 Bits &= ~TopLevelDeclInObjCContainerFlag;
541 NextInContextAndBits.setInt(Bits);
544 /// \brief Whether this declaration was marked as being private to the
545 /// module in which it was defined.
546 bool isModulePrivate() const {
547 return NextInContextAndBits.getInt() & ModulePrivateFlag;
551 /// \brief Specify whether this declaration was marked as being private
552 /// to the module in which it was defined.
553 void setModulePrivate(bool MP = true) {
554 unsigned Bits = NextInContextAndBits.getInt();
556 Bits |= ModulePrivateFlag;
558 Bits &= ~ModulePrivateFlag;
559 NextInContextAndBits.setInt(Bits);
562 /// \brief Set the owning module ID.
563 void setOwningModuleID(unsigned ID) {
564 assert(isFromASTFile() && "Only works on a deserialized declaration");
565 *((unsigned*)this - 2) = ID;
570 /// \brief Determine the availability of the given declaration.
572 /// This routine will determine the most restrictive availability of
573 /// the given declaration (e.g., preferring 'unavailable' to
576 /// \param Message If non-NULL and the result is not \c
577 /// AR_Available, will be set to a (possibly empty) message
578 /// describing why the declaration has not been introduced, is
579 /// deprecated, or is unavailable.
580 AvailabilityResult getAvailability(std::string *Message = nullptr) const;
582 /// \brief Determine whether this declaration is marked 'deprecated'.
584 /// \param Message If non-NULL and the declaration is deprecated,
585 /// this will be set to the message describing why the declaration
586 /// was deprecated (which may be empty).
587 bool isDeprecated(std::string *Message = nullptr) const {
588 return getAvailability(Message) == AR_Deprecated;
591 /// \brief Determine whether this declaration is marked 'unavailable'.
593 /// \param Message If non-NULL and the declaration is unavailable,
594 /// this will be set to the message describing why the declaration
595 /// was made unavailable (which may be empty).
596 bool isUnavailable(std::string *Message = nullptr) const {
597 return getAvailability(Message) == AR_Unavailable;
600 /// \brief Determine whether this is a weak-imported symbol.
602 /// Weak-imported symbols are typically marked with the
603 /// 'weak_import' attribute, but may also be marked with an
604 /// 'availability' attribute where we're targing a platform prior to
605 /// the introduction of this feature.
606 bool isWeakImported() const;
608 /// \brief Determines whether this symbol can be weak-imported,
609 /// e.g., whether it would be well-formed to add the weak_import
612 /// \param IsDefinition Set to \c true to indicate that this
613 /// declaration cannot be weak-imported because it has a definition.
614 bool canBeWeakImported(bool &IsDefinition) const;
616 /// \brief Determine whether this declaration came from an AST file (such as
617 /// a precompiled header or module) rather than having been parsed.
618 bool isFromASTFile() const { return FromASTFile; }
620 /// \brief Retrieve the global declaration ID associated with this
621 /// declaration, which specifies where in the
622 unsigned getGlobalID() const {
624 return *((const unsigned*)this - 1);
628 /// \brief Retrieve the global ID of the module that owns this particular
630 unsigned getOwningModuleID() const {
632 return *((const unsigned*)this - 2);
638 Module *getOwningModuleSlow() const;
641 Module *getOwningModule() const {
642 if (!isFromASTFile())
645 return getOwningModuleSlow();
648 unsigned getIdentifierNamespace() const {
649 return IdentifierNamespace;
651 bool isInIdentifierNamespace(unsigned NS) const {
652 return getIdentifierNamespace() & NS;
654 static unsigned getIdentifierNamespaceForKind(Kind DK);
656 bool hasTagIdentifierNamespace() const {
657 return isTagIdentifierNamespace(getIdentifierNamespace());
659 static bool isTagIdentifierNamespace(unsigned NS) {
660 // TagDecls have Tag and Type set and may also have TagFriend.
661 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
664 /// getLexicalDeclContext - The declaration context where this Decl was
665 /// lexically declared (LexicalDC). May be different from
666 /// getDeclContext() (SemanticDC).
670 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
672 /// void A::f(); // SemanticDC == namespace 'A'
673 /// // LexicalDC == global namespace
674 DeclContext *getLexicalDeclContext() {
676 return getSemanticDC();
677 return getMultipleDC()->LexicalDC;
679 const DeclContext *getLexicalDeclContext() const {
680 return const_cast<Decl*>(this)->getLexicalDeclContext();
683 /// Determine whether this declaration is declared out of line (outside its
684 /// semantic context).
685 virtual bool isOutOfLine() const;
687 /// setDeclContext - Set both the semantic and lexical DeclContext
689 void setDeclContext(DeclContext *DC);
691 void setLexicalDeclContext(DeclContext *DC);
693 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
694 /// scoped decl is defined outside the current function or method. This is
695 /// roughly global variables and functions, but also handles enums (which
696 /// could be defined inside or outside a function etc).
697 bool isDefinedOutsideFunctionOrMethod() const {
698 return getParentFunctionOrMethod() == nullptr;
701 /// \brief If this decl is defined inside a function/method/block it returns
702 /// the corresponding DeclContext, otherwise it returns null.
703 const DeclContext *getParentFunctionOrMethod() const;
704 DeclContext *getParentFunctionOrMethod() {
705 return const_cast<DeclContext*>(
706 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
709 /// \brief Retrieves the "canonical" declaration of the given declaration.
710 virtual Decl *getCanonicalDecl() { return this; }
711 const Decl *getCanonicalDecl() const {
712 return const_cast<Decl*>(this)->getCanonicalDecl();
715 /// \brief Whether this particular Decl is a canonical one.
716 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
719 /// \brief Returns the next redeclaration or itself if this is the only decl.
721 /// Decl subclasses that can be redeclared should override this method so that
722 /// Decl::redecl_iterator can iterate over them.
723 virtual Decl *getNextRedeclarationImpl() { return this; }
725 /// \brief Implementation of getPreviousDecl(), to be overridden by any
726 /// subclass that has a redeclaration chain.
727 virtual Decl *getPreviousDeclImpl() { return nullptr; }
729 /// \brief Implementation of getMostRecentDecl(), to be overridden by any
730 /// subclass that has a redeclaration chain.
731 virtual Decl *getMostRecentDeclImpl() { return this; }
734 /// \brief Iterates through all the redeclarations of the same decl.
735 class redecl_iterator {
736 /// Current - The current declaration.
741 typedef Decl *value_type;
742 typedef const value_type &reference;
743 typedef const value_type *pointer;
744 typedef std::forward_iterator_tag iterator_category;
745 typedef std::ptrdiff_t difference_type;
747 redecl_iterator() : Current(nullptr) { }
748 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
750 reference operator*() const { return Current; }
751 value_type operator->() const { return Current; }
753 redecl_iterator& operator++() {
754 assert(Current && "Advancing while iterator has reached end");
755 // Get either previous decl or latest decl.
756 Decl *Next = Current->getNextRedeclarationImpl();
757 assert(Next && "Should return next redeclaration or itself, never null!");
758 Current = (Next != Starter) ? Next : nullptr;
762 redecl_iterator operator++(int) {
763 redecl_iterator tmp(*this);
768 friend bool operator==(redecl_iterator x, redecl_iterator y) {
769 return x.Current == y.Current;
771 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
772 return x.Current != y.Current;
776 typedef llvm::iterator_range<redecl_iterator> redecl_range;
778 /// \brief Returns an iterator range for all the redeclarations of the same
779 /// decl. It will iterate at least once (when this decl is the only one).
780 redecl_range redecls() const {
781 return redecl_range(redecls_begin(), redecls_end());
784 redecl_iterator redecls_begin() const {
785 return redecl_iterator(const_cast<Decl *>(this));
787 redecl_iterator redecls_end() const { return redecl_iterator(); }
789 /// \brief Retrieve the previous declaration that declares the same entity
790 /// as this declaration, or NULL if there is no previous declaration.
791 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
793 /// \brief Retrieve the most recent declaration that declares the same entity
794 /// as this declaration, or NULL if there is no previous declaration.
795 const Decl *getPreviousDecl() const {
796 return const_cast<Decl *>(this)->getPreviousDeclImpl();
799 /// \brief True if this is the first declaration in its redeclaration chain.
800 bool isFirstDecl() const {
801 return getPreviousDecl() == nullptr;
804 /// \brief Retrieve the most recent declaration that declares the same entity
805 /// as this declaration (which may be this declaration).
806 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
808 /// \brief Retrieve the most recent declaration that declares the same entity
809 /// as this declaration (which may be this declaration).
810 const Decl *getMostRecentDecl() const {
811 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
814 /// getBody - If this Decl represents a declaration for a body of code,
815 /// such as a function or method definition, this method returns the
816 /// top-level Stmt* of that body. Otherwise this method returns null.
817 virtual Stmt* getBody() const { return nullptr; }
819 /// \brief Returns true if this \c Decl represents a declaration for a body of
820 /// code, such as a function or method definition.
821 /// Note that \c hasBody can also return true if any redeclaration of this
822 /// \c Decl represents a declaration for a body of code.
823 virtual bool hasBody() const { return getBody() != nullptr; }
825 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
826 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
827 SourceLocation getBodyRBrace() const;
829 // global temp stats (until we have a per-module visitor)
830 static void add(Kind k);
831 static void EnableStatistics();
832 static void PrintStats();
834 /// isTemplateParameter - Determines whether this declaration is a
835 /// template parameter.
836 bool isTemplateParameter() const;
838 /// isTemplateParameter - Determines whether this declaration is a
839 /// template parameter pack.
840 bool isTemplateParameterPack() const;
842 /// \brief Whether this declaration is a parameter pack.
843 bool isParameterPack() const;
845 /// \brief returns true if this declaration is a template
846 bool isTemplateDecl() const;
848 /// \brief Whether this declaration is a function or function template.
849 bool isFunctionOrFunctionTemplate() const {
850 return (DeclKind >= Decl::firstFunction &&
851 DeclKind <= Decl::lastFunction) ||
852 DeclKind == FunctionTemplate;
855 /// \brief Returns the function itself, or the templated function if this is a
856 /// function template.
857 FunctionDecl *getAsFunction() LLVM_READONLY;
859 const FunctionDecl *getAsFunction() const {
860 return const_cast<Decl *>(this)->getAsFunction();
863 /// \brief Changes the namespace of this declaration to reflect that it's
864 /// a function-local extern declaration.
866 /// These declarations appear in the lexical context of the extern
867 /// declaration, but in the semantic context of the enclosing namespace
869 void setLocalExternDecl() {
870 assert((IdentifierNamespace == IDNS_Ordinary ||
871 IdentifierNamespace == IDNS_OrdinaryFriend) &&
872 "namespace is not ordinary");
874 Decl *Prev = getPreviousDecl();
875 IdentifierNamespace &= ~IDNS_Ordinary;
877 IdentifierNamespace |= IDNS_LocalExtern;
878 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
879 IdentifierNamespace |= IDNS_Ordinary;
882 /// \brief Determine whether this is a block-scope declaration with linkage.
883 /// This will either be a local variable declaration declared 'extern', or a
884 /// local function declaration.
885 bool isLocalExternDecl() {
886 return IdentifierNamespace & IDNS_LocalExtern;
889 /// \brief Changes the namespace of this declaration to reflect that it's
890 /// the object of a friend declaration.
892 /// These declarations appear in the lexical context of the friending
893 /// class, but in the semantic context of the actual entity. This property
894 /// applies only to a specific decl object; other redeclarations of the
895 /// same entity may not (and probably don't) share this property.
896 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
897 unsigned OldNS = IdentifierNamespace;
898 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
899 IDNS_TagFriend | IDNS_OrdinaryFriend |
900 IDNS_LocalExtern)) &&
901 "namespace includes neither ordinary nor tag");
902 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
903 IDNS_TagFriend | IDNS_OrdinaryFriend |
904 IDNS_LocalExtern)) &&
905 "namespace includes other than ordinary or tag");
907 Decl *Prev = getPreviousDecl();
908 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
910 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
911 IdentifierNamespace |= IDNS_TagFriend;
912 if (PerformFriendInjection ||
913 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
914 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
917 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | IDNS_LocalExtern)) {
918 IdentifierNamespace |= IDNS_OrdinaryFriend;
919 if (PerformFriendInjection ||
920 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
921 IdentifierNamespace |= IDNS_Ordinary;
925 enum FriendObjectKind {
926 FOK_None, ///< Not a friend object.
927 FOK_Declared, ///< A friend of a previously-declared entity.
928 FOK_Undeclared ///< A friend of a previously-undeclared entity.
931 /// \brief Determines whether this declaration is the object of a
932 /// friend declaration and, if so, what kind.
934 /// There is currently no direct way to find the associated FriendDecl.
935 FriendObjectKind getFriendObjectKind() const {
937 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
938 if (!mask) return FOK_None;
939 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
943 /// Specifies that this declaration is a C++ overloaded non-member.
944 void setNonMemberOperator() {
945 assert(getKind() == Function || getKind() == FunctionTemplate);
946 assert((IdentifierNamespace & IDNS_Ordinary) &&
947 "visible non-member operators should be in ordinary namespace");
948 IdentifierNamespace |= IDNS_NonMemberOperator;
951 static bool classofKind(Kind K) { return true; }
952 static DeclContext *castToDeclContext(const Decl *);
953 static Decl *castFromDeclContext(const DeclContext *);
955 void print(raw_ostream &Out, unsigned Indentation = 0,
956 bool PrintInstantiation = false) const;
957 void print(raw_ostream &Out, const PrintingPolicy &Policy,
958 unsigned Indentation = 0, bool PrintInstantiation = false) const;
959 static void printGroup(Decl** Begin, unsigned NumDecls,
960 raw_ostream &Out, const PrintingPolicy &Policy,
961 unsigned Indentation = 0);
962 // Debuggers don't usually respect default arguments.
964 // Same as dump(), but forces color printing.
965 void dumpColor() const;
966 void dump(raw_ostream &Out) const;
968 /// \brief Looks through the Decl's underlying type to extract a FunctionType
969 /// when possible. Will return null if the type underlying the Decl does not
970 /// have a FunctionType.
971 const FunctionType *getFunctionType(bool BlocksToo = true) const;
974 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
975 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
979 ASTMutationListener *getASTMutationListener() const;
982 /// \brief Determine whether two declarations declare the same entity.
983 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
990 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
993 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
994 /// doing something to a specific decl.
995 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1001 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1002 SourceManager &sm, const char *Msg)
1003 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1005 void print(raw_ostream &OS) const override;
1008 typedef MutableArrayRef<NamedDecl *> DeclContextLookupResult;
1010 typedef ArrayRef<NamedDecl *> DeclContextLookupConstResult;
1012 /// DeclContext - This is used only as base class of specific decl types that
1013 /// can act as declaration contexts. These decls are (only the top classes
1014 /// that directly derive from DeclContext are mentioned, not their subclasses):
1016 /// TranslationUnitDecl
1021 /// ObjCContainerDecl
1026 /// DeclKind - This indicates which class this is.
1027 unsigned DeclKind : 8;
1029 /// \brief Whether this declaration context also has some external
1030 /// storage that contains additional declarations that are lexically
1031 /// part of this context.
1032 mutable bool ExternalLexicalStorage : 1;
1034 /// \brief Whether this declaration context also has some external
1035 /// storage that contains additional declarations that are visible
1036 /// in this context.
1037 mutable bool ExternalVisibleStorage : 1;
1039 /// \brief Whether this declaration context has had external visible
1040 /// storage added since the last lookup. In this case, \c LookupPtr's
1041 /// invariant may not hold and needs to be fixed before we perform
1043 mutable bool NeedToReconcileExternalVisibleStorage : 1;
1045 /// \brief Pointer to the data structure used to lookup declarations
1046 /// within this context (or a DependentStoredDeclsMap if this is a
1047 /// dependent context), and a bool indicating whether we have lazily
1048 /// omitted any declarations from the map. We maintain the invariant
1049 /// that, if the map contains an entry for a DeclarationName (and we
1050 /// haven't lazily omitted anything), then it contains all relevant
1051 /// entries for that name.
1052 mutable llvm::PointerIntPair<StoredDeclsMap*, 1, bool> LookupPtr;
1055 /// FirstDecl - The first declaration stored within this declaration
1057 mutable Decl *FirstDecl;
1059 /// LastDecl - The last declaration stored within this declaration
1060 /// context. FIXME: We could probably cache this value somewhere
1061 /// outside of the DeclContext, to reduce the size of DeclContext by
1062 /// another pointer.
1063 mutable Decl *LastDecl;
1065 friend class ExternalASTSource;
1066 friend class ASTDeclReader;
1067 friend class ASTWriter;
1069 /// \brief Build up a chain of declarations.
1071 /// \returns the first/last pair of declarations.
1072 static std::pair<Decl *, Decl *>
1073 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1075 DeclContext(Decl::Kind K)
1076 : DeclKind(K), ExternalLexicalStorage(false),
1077 ExternalVisibleStorage(false),
1078 NeedToReconcileExternalVisibleStorage(false), LookupPtr(nullptr, false),
1079 FirstDecl(nullptr), LastDecl(nullptr) {}
1084 Decl::Kind getDeclKind() const {
1085 return static_cast<Decl::Kind>(DeclKind);
1087 const char *getDeclKindName() const;
1089 /// getParent - Returns the containing DeclContext.
1090 DeclContext *getParent() {
1091 return cast<Decl>(this)->getDeclContext();
1093 const DeclContext *getParent() const {
1094 return const_cast<DeclContext*>(this)->getParent();
1097 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1098 /// different from getParent, e.g.:
1103 /// struct A::S {}; // getParent() == namespace 'A'
1104 /// // getLexicalParent() == translation unit
1106 DeclContext *getLexicalParent() {
1107 return cast<Decl>(this)->getLexicalDeclContext();
1109 const DeclContext *getLexicalParent() const {
1110 return const_cast<DeclContext*>(this)->getLexicalParent();
1113 DeclContext *getLookupParent();
1115 const DeclContext *getLookupParent() const {
1116 return const_cast<DeclContext*>(this)->getLookupParent();
1119 ASTContext &getParentASTContext() const {
1120 return cast<Decl>(this)->getASTContext();
1123 bool isClosure() const {
1124 return DeclKind == Decl::Block;
1127 bool isObjCContainer() const {
1129 case Decl::ObjCCategory:
1130 case Decl::ObjCCategoryImpl:
1131 case Decl::ObjCImplementation:
1132 case Decl::ObjCInterface:
1133 case Decl::ObjCProtocol:
1139 bool isFunctionOrMethod() const {
1142 case Decl::Captured:
1143 case Decl::ObjCMethod:
1146 return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1150 bool isFileContext() const {
1151 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1154 bool isTranslationUnit() const {
1155 return DeclKind == Decl::TranslationUnit;
1158 bool isRecord() const {
1159 return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1162 bool isNamespace() const {
1163 return DeclKind == Decl::Namespace;
1166 bool isStdNamespace() const;
1168 bool isInlineNamespace() const;
1170 /// \brief Determines whether this context is dependent on a
1171 /// template parameter.
1172 bool isDependentContext() const;
1174 /// isTransparentContext - Determines whether this context is a
1175 /// "transparent" context, meaning that the members declared in this
1176 /// context are semantically declared in the nearest enclosing
1177 /// non-transparent (opaque) context but are lexically declared in
1178 /// this context. For example, consider the enumerators of an
1179 /// enumeration type:
1185 /// Here, E is a transparent context, so its enumerator (Val1) will
1186 /// appear (semantically) that it is in the same context of E.
1187 /// Examples of transparent contexts include: enumerations (except for
1188 /// C++0x scoped enums), and C++ linkage specifications.
1189 bool isTransparentContext() const;
1191 /// \brief Determines whether this context or some of its ancestors is a
1192 /// linkage specification context that specifies C linkage.
1193 bool isExternCContext() const;
1195 /// \brief Determines whether this context or some of its ancestors is a
1196 /// linkage specification context that specifies C++ linkage.
1197 bool isExternCXXContext() const;
1199 /// \brief Determine whether this declaration context is equivalent
1200 /// to the declaration context DC.
1201 bool Equals(const DeclContext *DC) const {
1202 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1205 /// \brief Determine whether this declaration context encloses the
1206 /// declaration context DC.
1207 bool Encloses(const DeclContext *DC) const;
1209 /// \brief Find the nearest non-closure ancestor of this context,
1210 /// i.e. the innermost semantic parent of this context which is not
1211 /// a closure. A context may be its own non-closure ancestor.
1212 Decl *getNonClosureAncestor();
1213 const Decl *getNonClosureAncestor() const {
1214 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1217 /// getPrimaryContext - There may be many different
1218 /// declarations of the same entity (including forward declarations
1219 /// of classes, multiple definitions of namespaces, etc.), each with
1220 /// a different set of declarations. This routine returns the
1221 /// "primary" DeclContext structure, which will contain the
1222 /// information needed to perform name lookup into this context.
1223 DeclContext *getPrimaryContext();
1224 const DeclContext *getPrimaryContext() const {
1225 return const_cast<DeclContext*>(this)->getPrimaryContext();
1228 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1229 /// other entities of the same name, or where it is a redeclaration if the
1230 /// two entities are compatible. This skips through transparent contexts.
1231 DeclContext *getRedeclContext();
1232 const DeclContext *getRedeclContext() const {
1233 return const_cast<DeclContext *>(this)->getRedeclContext();
1236 /// \brief Retrieve the nearest enclosing namespace context.
1237 DeclContext *getEnclosingNamespaceContext();
1238 const DeclContext *getEnclosingNamespaceContext() const {
1239 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1242 /// \brief Retrieve the outermost lexically enclosing record context.
1243 RecordDecl *getOuterLexicalRecordContext();
1244 const RecordDecl *getOuterLexicalRecordContext() const {
1245 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1248 /// \brief Test if this context is part of the enclosing namespace set of
1249 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1250 /// isn't a namespace, this is equivalent to Equals().
1252 /// The enclosing namespace set of a namespace is the namespace and, if it is
1253 /// inline, its enclosing namespace, recursively.
1254 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1256 /// \brief Collects all of the declaration contexts that are semantically
1257 /// connected to this declaration context.
1259 /// For declaration contexts that have multiple semantically connected but
1260 /// syntactically distinct contexts, such as C++ namespaces, this routine
1261 /// retrieves the complete set of such declaration contexts in source order.
1262 /// For example, given:
1273 /// The \c Contexts parameter will contain both definitions of N.
1275 /// \param Contexts Will be cleared and set to the set of declaration
1276 /// contexts that are semanticaly connected to this declaration context,
1277 /// in source order, including this context (which may be the only result,
1278 /// for non-namespace contexts).
1279 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1281 /// decl_iterator - Iterates through the declarations stored
1282 /// within this context.
1283 class decl_iterator {
1284 /// Current - The current declaration.
1288 typedef Decl *value_type;
1289 typedef const value_type &reference;
1290 typedef const value_type *pointer;
1291 typedef std::forward_iterator_tag iterator_category;
1292 typedef std::ptrdiff_t difference_type;
1294 decl_iterator() : Current(nullptr) { }
1295 explicit decl_iterator(Decl *C) : Current(C) { }
1297 reference operator*() const { return Current; }
1298 // This doesn't meet the iterator requirements, but it's convenient
1299 value_type operator->() const { return Current; }
1301 decl_iterator& operator++() {
1302 Current = Current->getNextDeclInContext();
1306 decl_iterator operator++(int) {
1307 decl_iterator tmp(*this);
1312 friend bool operator==(decl_iterator x, decl_iterator y) {
1313 return x.Current == y.Current;
1315 friend bool operator!=(decl_iterator x, decl_iterator y) {
1316 return x.Current != y.Current;
1320 typedef llvm::iterator_range<decl_iterator> decl_range;
1322 /// decls_begin/decls_end - Iterate over the declarations stored in
1324 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
1325 decl_iterator decls_begin() const;
1326 decl_iterator decls_end() const { return decl_iterator(); }
1327 bool decls_empty() const;
1329 /// noload_decls_begin/end - Iterate over the declarations stored in this
1330 /// context that are currently loaded; don't attempt to retrieve anything
1331 /// from an external source.
1332 decl_range noload_decls() const {
1333 return decl_range(noload_decls_begin(), noload_decls_end());
1335 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
1336 decl_iterator noload_decls_end() const { return decl_iterator(); }
1338 /// specific_decl_iterator - Iterates over a subrange of
1339 /// declarations stored in a DeclContext, providing only those that
1340 /// are of type SpecificDecl (or a class derived from it). This
1341 /// iterator is used, for example, to provide iteration over just
1342 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1343 template<typename SpecificDecl>
1344 class specific_decl_iterator {
1345 /// Current - The current, underlying declaration iterator, which
1346 /// will either be NULL or will point to a declaration of
1347 /// type SpecificDecl.
1348 DeclContext::decl_iterator Current;
1350 /// SkipToNextDecl - Advances the current position up to the next
1351 /// declaration of type SpecificDecl that also meets the criteria
1352 /// required by Acceptable.
1353 void SkipToNextDecl() {
1354 while (*Current && !isa<SpecificDecl>(*Current))
1359 typedef SpecificDecl *value_type;
1360 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1361 // type) if we ever have a need for them.
1362 typedef void reference;
1363 typedef void pointer;
1364 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1366 typedef std::forward_iterator_tag iterator_category;
1368 specific_decl_iterator() : Current() { }
1370 /// specific_decl_iterator - Construct a new iterator over a
1371 /// subset of the declarations the range [C,
1372 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1373 /// member function of SpecificDecl that should return true for
1374 /// all of the SpecificDecl instances that will be in the subset
1375 /// of iterators. For example, if you want Objective-C instance
1376 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1377 /// &ObjCMethodDecl::isInstanceMethod.
1378 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1382 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1383 // This doesn't meet the iterator requirements, but it's convenient
1384 value_type operator->() const { return **this; }
1386 specific_decl_iterator& operator++() {
1392 specific_decl_iterator operator++(int) {
1393 specific_decl_iterator tmp(*this);
1398 friend bool operator==(const specific_decl_iterator& x,
1399 const specific_decl_iterator& y) {
1400 return x.Current == y.Current;
1403 friend bool operator!=(const specific_decl_iterator& x,
1404 const specific_decl_iterator& y) {
1405 return x.Current != y.Current;
1409 /// \brief Iterates over a filtered subrange of declarations stored
1410 /// in a DeclContext.
1412 /// This iterator visits only those declarations that are of type
1413 /// SpecificDecl (or a class derived from it) and that meet some
1414 /// additional run-time criteria. This iterator is used, for
1415 /// example, to provide access to the instance methods within an
1416 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1417 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1418 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1419 class filtered_decl_iterator {
1420 /// Current - The current, underlying declaration iterator, which
1421 /// will either be NULL or will point to a declaration of
1422 /// type SpecificDecl.
1423 DeclContext::decl_iterator Current;
1425 /// SkipToNextDecl - Advances the current position up to the next
1426 /// declaration of type SpecificDecl that also meets the criteria
1427 /// required by Acceptable.
1428 void SkipToNextDecl() {
1430 (!isa<SpecificDecl>(*Current) ||
1431 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1436 typedef SpecificDecl *value_type;
1437 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1438 // type) if we ever have a need for them.
1439 typedef void reference;
1440 typedef void pointer;
1441 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1443 typedef std::forward_iterator_tag iterator_category;
1445 filtered_decl_iterator() : Current() { }
1447 /// filtered_decl_iterator - Construct a new iterator over a
1448 /// subset of the declarations the range [C,
1449 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1450 /// member function of SpecificDecl that should return true for
1451 /// all of the SpecificDecl instances that will be in the subset
1452 /// of iterators. For example, if you want Objective-C instance
1453 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1454 /// &ObjCMethodDecl::isInstanceMethod.
1455 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1459 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1460 value_type operator->() const { return cast<SpecificDecl>(*Current); }
1462 filtered_decl_iterator& operator++() {
1468 filtered_decl_iterator operator++(int) {
1469 filtered_decl_iterator tmp(*this);
1474 friend bool operator==(const filtered_decl_iterator& x,
1475 const filtered_decl_iterator& y) {
1476 return x.Current == y.Current;
1479 friend bool operator!=(const filtered_decl_iterator& x,
1480 const filtered_decl_iterator& y) {
1481 return x.Current != y.Current;
1485 /// @brief Add the declaration D into this context.
1487 /// This routine should be invoked when the declaration D has first
1488 /// been declared, to place D into the context where it was
1489 /// (lexically) defined. Every declaration must be added to one
1490 /// (and only one!) context, where it can be visited via
1491 /// [decls_begin(), decls_end()). Once a declaration has been added
1492 /// to its lexical context, the corresponding DeclContext owns the
1495 /// If D is also a NamedDecl, it will be made visible within its
1496 /// semantic context via makeDeclVisibleInContext.
1497 void addDecl(Decl *D);
1499 /// @brief Add the declaration D into this context, but suppress
1500 /// searches for external declarations with the same name.
1502 /// Although analogous in function to addDecl, this removes an
1503 /// important check. This is only useful if the Decl is being
1504 /// added in response to an external search; in all other cases,
1505 /// addDecl() is the right function to use.
1506 /// See the ASTImporter for use cases.
1507 void addDeclInternal(Decl *D);
1509 /// @brief Add the declaration D to this context without modifying
1510 /// any lookup tables.
1512 /// This is useful for some operations in dependent contexts where
1513 /// the semantic context might not be dependent; this basically
1514 /// only happens with friends.
1515 void addHiddenDecl(Decl *D);
1517 /// @brief Removes a declaration from this context.
1518 void removeDecl(Decl *D);
1520 /// @brief Checks whether a declaration is in this context.
1521 bool containsDecl(Decl *D) const;
1523 /// lookup_iterator - An iterator that provides access to the results
1524 /// of looking up a name within this context.
1525 typedef NamedDecl **lookup_iterator;
1527 /// lookup_const_iterator - An iterator that provides non-mutable
1528 /// access to the results of lookup up a name within this context.
1529 typedef NamedDecl * const * lookup_const_iterator;
1531 typedef DeclContextLookupResult lookup_result;
1532 typedef DeclContextLookupConstResult lookup_const_result;
1534 /// lookup - Find the declarations (if any) with the given Name in
1535 /// this context. Returns a range of iterators that contains all of
1536 /// the declarations with this name, with object, function, member,
1537 /// and enumerator names preceding any tag name. Note that this
1538 /// routine will not look into parent contexts.
1539 lookup_result lookup(DeclarationName Name);
1540 lookup_const_result lookup(DeclarationName Name) const {
1541 return const_cast<DeclContext*>(this)->lookup(Name);
1544 /// \brief Find the declarations with the given name that are visible
1545 /// within this context; don't attempt to retrieve anything from an
1546 /// external source.
1547 lookup_result noload_lookup(DeclarationName Name);
1549 /// \brief A simplistic name lookup mechanism that performs name lookup
1550 /// into this declaration context without consulting the external source.
1552 /// This function should almost never be used, because it subverts the
1553 /// usual relationship between a DeclContext and the external source.
1554 /// See the ASTImporter for the (few, but important) use cases.
1556 /// FIXME: This is very inefficient; replace uses of it with uses of
1558 void localUncachedLookup(DeclarationName Name,
1559 SmallVectorImpl<NamedDecl *> &Results);
1561 /// @brief Makes a declaration visible within this context.
1563 /// This routine makes the declaration D visible to name lookup
1564 /// within this context and, if this is a transparent context,
1565 /// within its parent contexts up to the first enclosing
1566 /// non-transparent context. Making a declaration visible within a
1567 /// context does not transfer ownership of a declaration, and a
1568 /// declaration can be visible in many contexts that aren't its
1569 /// lexical context.
1571 /// If D is a redeclaration of an existing declaration that is
1572 /// visible from this context, as determined by
1573 /// NamedDecl::declarationReplaces, the previous declaration will be
1574 /// replaced with D.
1575 void makeDeclVisibleInContext(NamedDecl *D);
1577 /// all_lookups_iterator - An iterator that provides a view over the results
1578 /// of looking up every possible name.
1579 class all_lookups_iterator;
1581 typedef llvm::iterator_range<all_lookups_iterator> lookups_range;
1583 lookups_range lookups() const;
1584 lookups_range noload_lookups() const;
1586 /// \brief Iterators over all possible lookups within this context.
1587 all_lookups_iterator lookups_begin() const;
1588 all_lookups_iterator lookups_end() const;
1590 /// \brief Iterators over all possible lookups within this context that are
1591 /// currently loaded; don't attempt to retrieve anything from an external
1593 all_lookups_iterator noload_lookups_begin() const;
1594 all_lookups_iterator noload_lookups_end() const;
1596 typedef llvm::iterator_range<UsingDirectiveDecl * const *> udir_range;
1598 udir_range using_directives() const;
1600 // These are all defined in DependentDiagnostic.h.
1601 class ddiag_iterator;
1602 typedef llvm::iterator_range<DeclContext::ddiag_iterator> ddiag_range;
1604 inline ddiag_range ddiags() const;
1606 // Low-level accessors
1608 /// \brief Mark the lookup table as needing to be built. This should be
1609 /// used only if setHasExternalLexicalStorage() has been called on any
1610 /// decl context for which this is the primary context.
1611 void setMustBuildLookupTable() {
1612 LookupPtr.setInt(true);
1615 /// \brief Retrieve the internal representation of the lookup structure.
1616 /// This may omit some names if we are lazily building the structure.
1617 StoredDeclsMap *getLookupPtr() const { return LookupPtr.getPointer(); }
1619 /// \brief Ensure the lookup structure is fully-built and return it.
1620 StoredDeclsMap *buildLookup();
1622 /// \brief Whether this DeclContext has external storage containing
1623 /// additional declarations that are lexically in this context.
1624 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1626 /// \brief State whether this DeclContext has external storage for
1627 /// declarations lexically in this context.
1628 void setHasExternalLexicalStorage(bool ES = true) {
1629 ExternalLexicalStorage = ES;
1632 /// \brief Whether this DeclContext has external storage containing
1633 /// additional declarations that are visible in this context.
1634 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1636 /// \brief State whether this DeclContext has external storage for
1637 /// declarations visible in this context.
1638 void setHasExternalVisibleStorage(bool ES = true) {
1639 ExternalVisibleStorage = ES;
1640 if (ES && LookupPtr.getPointer())
1641 NeedToReconcileExternalVisibleStorage = true;
1644 /// \brief Determine whether the given declaration is stored in the list of
1645 /// declarations lexically within this context.
1646 bool isDeclInLexicalTraversal(const Decl *D) const {
1647 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1651 static bool classof(const Decl *D);
1652 static bool classof(const DeclContext *D) { return true; }
1654 void dumpDeclContext() const;
1655 void dumpLookups() const;
1656 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false) const;
1659 void reconcileExternalVisibleStorage() const;
1660 void LoadLexicalDeclsFromExternalStorage() const;
1662 /// @brief Makes a declaration visible within this context, but
1663 /// suppresses searches for external declarations with the same
1666 /// Analogous to makeDeclVisibleInContext, but for the exclusive
1667 /// use of addDeclInternal().
1668 void makeDeclVisibleInContextInternal(NamedDecl *D);
1670 friend class DependentDiagnostic;
1671 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1673 template<decl_iterator (DeclContext::*Begin)() const,
1674 decl_iterator (DeclContext::*End)() const>
1675 void buildLookupImpl(DeclContext *DCtx);
1676 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1677 bool Rediscoverable);
1678 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1681 inline bool Decl::isTemplateParameter() const {
1682 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1683 getKind() == TemplateTemplateParm;
1686 // Specialization selected when ToTy is not a known subclass of DeclContext.
1687 template <class ToTy,
1688 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
1689 struct cast_convert_decl_context {
1690 static const ToTy *doit(const DeclContext *Val) {
1691 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1694 static ToTy *doit(DeclContext *Val) {
1695 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1699 // Specialization selected when ToTy is a known subclass of DeclContext.
1700 template <class ToTy>
1701 struct cast_convert_decl_context<ToTy, true> {
1702 static const ToTy *doit(const DeclContext *Val) {
1703 return static_cast<const ToTy*>(Val);
1706 static ToTy *doit(DeclContext *Val) {
1707 return static_cast<ToTy*>(Val);
1716 /// isa<T>(DeclContext*)
1717 template <typename To>
1718 struct isa_impl<To, ::clang::DeclContext> {
1719 static bool doit(const ::clang::DeclContext &Val) {
1720 return To::classofKind(Val.getDeclKind());
1724 /// cast<T>(DeclContext*)
1725 template<class ToTy>
1726 struct cast_convert_val<ToTy,
1727 const ::clang::DeclContext,const ::clang::DeclContext> {
1728 static const ToTy &doit(const ::clang::DeclContext &Val) {
1729 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1732 template<class ToTy>
1733 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
1734 static ToTy &doit(::clang::DeclContext &Val) {
1735 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1738 template<class ToTy>
1739 struct cast_convert_val<ToTy,
1740 const ::clang::DeclContext*, const ::clang::DeclContext*> {
1741 static const ToTy *doit(const ::clang::DeclContext *Val) {
1742 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1745 template<class ToTy>
1746 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
1747 static ToTy *doit(::clang::DeclContext *Val) {
1748 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1752 /// Implement cast_convert_val for Decl -> DeclContext conversions.
1753 template<class FromTy>
1754 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1755 static ::clang::DeclContext &doit(const FromTy &Val) {
1756 return *FromTy::castToDeclContext(&Val);
1760 template<class FromTy>
1761 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1762 static ::clang::DeclContext *doit(const FromTy *Val) {
1763 return FromTy::castToDeclContext(Val);
1767 template<class FromTy>
1768 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1769 static const ::clang::DeclContext &doit(const FromTy &Val) {
1770 return *FromTy::castToDeclContext(&Val);
1774 template<class FromTy>
1775 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1776 static const ::clang::DeclContext *doit(const FromTy *Val) {
1777 return FromTy::castToDeclContext(Val);
1781 } // end namespace llvm