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.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/PrettyStackTrace.h"
27 class ASTMutationListener;
32 class DeclarationName;
33 class DependentDiagnostic;
37 enum Linkage : unsigned char;
38 class LinkageComputer;
39 class LinkageSpecDecl;
43 class ObjCCategoryDecl;
44 class ObjCCategoryImplDecl;
45 class ObjCContainerDecl;
47 class ObjCImplementationDecl;
48 class ObjCInterfaceDecl;
50 class ObjCProtocolDecl;
51 struct PrintingPolicy;
55 class TranslationUnitDecl;
56 class UsingDirectiveDecl;
61 /// \brief Captures the result of checking the availability of a
63 enum AvailabilityResult {
70 /// Decl - This represents one declaration (or definition), e.g. a variable,
71 /// typedef, function, struct, etc.
73 /// Note: There are objects tacked on before the *beginning* of Decl
74 /// (and its subclasses) in its Decl::operator new(). Proper alignment
75 /// of all subclasses (not requiring more than DeclObjAlignment) is
76 /// asserted in DeclBase.cpp.
79 /// \brief Alignment guaranteed when allocating Decl and any subtypes.
80 enum { DeclObjAlignment = llvm::AlignOf<uint64_t>::Alignment };
82 /// \brief Lists the kind of concrete classes of Decl.
84 #define DECL(DERIVED, BASE) DERIVED,
85 #define ABSTRACT_DECL(DECL)
86 #define DECL_RANGE(BASE, START, END) \
87 first##BASE = START, last##BASE = END,
88 #define LAST_DECL_RANGE(BASE, START, END) \
89 first##BASE = START, last##BASE = END
90 #include "clang/AST/DeclNodes.inc"
93 /// \brief A placeholder type used to construct an empty shell of a
94 /// decl-derived type that will be filled in later (e.g., by some
95 /// deserialization method).
96 struct EmptyShell { };
98 /// IdentifierNamespace - The different namespaces in which
99 /// declarations may appear. According to C99 6.2.3, there are
100 /// four namespaces, labels, tags, members and ordinary
101 /// identifiers. C++ describes lookup completely differently:
102 /// certain lookups merely "ignore" certain kinds of declarations,
103 /// usually based on whether the declaration is of a type, etc.
105 /// These are meant as bitmasks, so that searches in
106 /// C++ can look into the "tag" namespace during ordinary lookup.
108 /// Decl currently provides 15 bits of IDNS bits.
109 enum IdentifierNamespace {
110 /// Labels, declared with 'x:' and referenced with 'goto x'.
113 /// Tags, declared with 'struct foo;' and referenced with
114 /// 'struct foo'. All tags are also types. This is what
115 /// elaborated-type-specifiers look for in C.
116 /// This also contains names that conflict with tags in the
117 /// same scope but that are otherwise ordinary names (non-type
118 /// template parameters and indirect field declarations).
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 /// member, or function-local extern 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. These act mostly like
167 /// invisible friend declarations, but are also visible to unqualified
168 /// lookup within the scope of the declaring function.
169 IDNS_LocalExtern = 0x0800
172 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
173 /// parameter types in method declarations. Other than remembering
174 /// them and mangling them into the method's signature string, these
175 /// are ignored by the compiler; they are consumed by certain
176 /// remote-messaging frameworks.
178 /// in, inout, and out are mutually exclusive and apply only to
179 /// method parameters. bycopy and byref are mutually exclusive and
180 /// apply only to method parameters (?). oneway applies only to
181 /// results. All of these expect their corresponding parameter to
182 /// have a particular type. None of this is currently enforced by
185 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
186 enum ObjCDeclQualifier {
191 OBJC_TQ_Bycopy = 0x8,
192 OBJC_TQ_Byref = 0x10,
193 OBJC_TQ_Oneway = 0x20,
195 /// The nullability qualifier is set when the nullability of the
196 /// result or parameter was expressed via a context-sensitive
198 OBJC_TQ_CSNullability = 0x40
202 // Enumeration values used in the bits stored in NextInContextAndBits.
204 /// \brief Whether this declaration is a top-level declaration (function,
205 /// global variable, etc.) that is lexically inside an objc container
207 TopLevelDeclInObjCContainerFlag = 0x01,
209 /// \brief Whether this declaration is private to the module in which it was
211 ModulePrivateFlag = 0x02
214 /// \brief The next declaration within the same lexical
215 /// DeclContext. These pointers form the linked list that is
216 /// traversed via DeclContext's decls_begin()/decls_end().
218 /// The extra two bits are used for the TopLevelDeclInObjCContainer and
219 /// ModulePrivate bits.
220 llvm::PointerIntPair<Decl *, 2, unsigned> NextInContextAndBits;
223 friend class DeclContext;
226 DeclContext *SemanticDC;
227 DeclContext *LexicalDC;
231 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
232 /// For declarations that don't contain C++ scope specifiers, it contains
233 /// the DeclContext where the Decl was declared.
234 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
235 /// with the context where it semantically belongs (SemanticDC) and the
236 /// context where it was lexically declared (LexicalDC).
240 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
242 /// void A::f(); // SemanticDC == namespace 'A'
243 /// // LexicalDC == global namespace
244 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
246 inline bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
247 inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
248 inline MultipleDC *getMultipleDC() const {
249 return DeclCtx.get<MultipleDC*>();
251 inline DeclContext *getSemanticDC() const {
252 return DeclCtx.get<DeclContext*>();
255 /// Loc - The location of this decl.
258 /// DeclKind - This indicates which class this is.
259 unsigned DeclKind : 8;
261 /// InvalidDecl - This indicates a semantic error occurred.
262 unsigned InvalidDecl : 1;
264 /// HasAttrs - This indicates whether the decl has attributes or not.
265 unsigned HasAttrs : 1;
267 /// Implicit - Whether this declaration was implicitly generated by
268 /// the implementation rather than explicitly written by the user.
269 unsigned Implicit : 1;
271 /// \brief Whether this declaration was "used", meaning that a definition is
275 /// \brief Whether this declaration was "referenced".
276 /// The difference with 'Used' is whether the reference appears in a
277 /// evaluated context or not, e.g. functions used in uninstantiated templates
278 /// are regarded as "referenced" but not "used".
279 unsigned Referenced : 1;
281 /// \brief Whether statistic collection is enabled.
282 static bool StatisticsEnabled;
285 /// Access - Used by C++ decls for the access specifier.
286 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
288 friend class CXXClassMemberWrapper;
290 /// \brief Whether this declaration was loaded from an AST file.
291 unsigned FromASTFile : 1;
293 /// \brief Whether this declaration is hidden from normal name lookup, e.g.,
294 /// because it is was loaded from an AST file is either module-private or
295 /// because its submodule has not been made visible.
298 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
299 unsigned IdentifierNamespace : 12;
301 /// \brief If 0, we have not computed the linkage of this declaration.
302 /// Otherwise, it is the linkage + 1.
303 mutable unsigned CacheValidAndLinkage : 3;
305 friend class ASTDeclWriter;
306 friend class ASTDeclReader;
307 friend class ASTReader;
308 friend class LinkageComputer;
310 template<typename decl_type> friend class Redeclarable;
312 /// \brief Allocate memory for a deserialized declaration.
314 /// This routine must be used to allocate memory for any declaration that is
315 /// deserialized from a module file.
317 /// \param Size The size of the allocated object.
318 /// \param Ctx The context in which we will allocate memory.
319 /// \param ID The global ID of the deserialized declaration.
320 /// \param Extra The amount of extra space to allocate after the object.
321 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
322 std::size_t Extra = 0);
324 /// \brief Allocate memory for a non-deserialized declaration.
325 void *operator new(std::size_t Size, const ASTContext &Ctx,
326 DeclContext *Parent, std::size_t Extra = 0);
329 bool AccessDeclContextSanity() const;
333 Decl(Kind DK, DeclContext *DC, SourceLocation L)
334 : NextInContextAndBits(), DeclCtx(DC),
335 Loc(L), DeclKind(DK), InvalidDecl(0),
336 HasAttrs(false), Implicit(false), Used(false), Referenced(false),
337 Access(AS_none), FromASTFile(0), Hidden(DC && cast<Decl>(DC)->Hidden),
338 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
339 CacheValidAndLinkage(0)
341 if (StatisticsEnabled) add(DK);
344 Decl(Kind DK, EmptyShell Empty)
345 : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0),
346 HasAttrs(false), Implicit(false), Used(false), Referenced(false),
347 Access(AS_none), FromASTFile(0), Hidden(0),
348 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
349 CacheValidAndLinkage(0)
351 if (StatisticsEnabled) add(DK);
356 /// \brief Update a potentially out-of-date declaration.
357 void updateOutOfDate(IdentifierInfo &II) const;
359 Linkage getCachedLinkage() const {
360 return Linkage(CacheValidAndLinkage - 1);
363 void setCachedLinkage(Linkage L) const {
364 CacheValidAndLinkage = L + 1;
367 bool hasCachedLinkage() const {
368 return CacheValidAndLinkage;
373 /// \brief Source range that this declaration covers.
374 virtual SourceRange getSourceRange() const LLVM_READONLY {
375 return SourceRange(getLocation(), getLocation());
377 SourceLocation getLocStart() const LLVM_READONLY {
378 return getSourceRange().getBegin();
380 SourceLocation getLocEnd() const LLVM_READONLY {
381 return getSourceRange().getEnd();
384 SourceLocation getLocation() const { return Loc; }
385 void setLocation(SourceLocation L) { Loc = L; }
387 Kind getKind() const { return static_cast<Kind>(DeclKind); }
388 const char *getDeclKindName() const;
390 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
391 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
393 DeclContext *getDeclContext() {
395 return getSemanticDC();
396 return getMultipleDC()->SemanticDC;
398 const DeclContext *getDeclContext() const {
399 return const_cast<Decl*>(this)->getDeclContext();
402 /// Find the innermost non-closure ancestor of this declaration,
403 /// walking up through blocks, lambdas, etc. If that ancestor is
404 /// not a code context (!isFunctionOrMethod()), returns null.
406 /// A declaration may be its own non-closure context.
407 Decl *getNonClosureContext();
408 const Decl *getNonClosureContext() const {
409 return const_cast<Decl*>(this)->getNonClosureContext();
412 TranslationUnitDecl *getTranslationUnitDecl();
413 const TranslationUnitDecl *getTranslationUnitDecl() const {
414 return const_cast<Decl*>(this)->getTranslationUnitDecl();
417 bool isInAnonymousNamespace() const;
419 bool isInStdNamespace() const;
421 ASTContext &getASTContext() const LLVM_READONLY;
423 void setAccess(AccessSpecifier AS) {
425 assert(AccessDeclContextSanity());
428 AccessSpecifier getAccess() const {
429 assert(AccessDeclContextSanity());
430 return AccessSpecifier(Access);
433 /// \brief Retrieve the access specifier for this declaration, even though
434 /// it may not yet have been properly set.
435 AccessSpecifier getAccessUnsafe() const {
436 return AccessSpecifier(Access);
439 bool hasAttrs() const { return HasAttrs; }
440 void setAttrs(const AttrVec& Attrs) {
441 return setAttrsImpl(Attrs, getASTContext());
443 AttrVec &getAttrs() {
444 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
446 const AttrVec &getAttrs() const;
449 void addAttr(Attr *A) {
451 getAttrs().push_back(A);
453 setAttrs(AttrVec(1, A));
456 typedef AttrVec::const_iterator attr_iterator;
457 typedef llvm::iterator_range<attr_iterator> attr_range;
459 attr_range attrs() const {
460 return attr_range(attr_begin(), attr_end());
463 attr_iterator attr_begin() const {
464 return hasAttrs() ? getAttrs().begin() : nullptr;
466 attr_iterator attr_end() const {
467 return hasAttrs() ? getAttrs().end() : nullptr;
470 template <typename T>
472 if (!HasAttrs) return;
474 AttrVec &Vec = getAttrs();
475 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
481 template <typename T>
482 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
483 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
486 template <typename T>
487 specific_attr_iterator<T> specific_attr_begin() const {
488 return specific_attr_iterator<T>(attr_begin());
490 template <typename T>
491 specific_attr_iterator<T> specific_attr_end() const {
492 return specific_attr_iterator<T>(attr_end());
495 template<typename T> T *getAttr() const {
496 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
498 template<typename T> bool hasAttr() const {
499 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
502 /// getMaxAlignment - return the maximum alignment specified by attributes
503 /// on this decl, 0 if there are none.
504 unsigned getMaxAlignment() const;
506 /// setInvalidDecl - Indicates the Decl had a semantic error. This
507 /// allows for graceful error recovery.
508 void setInvalidDecl(bool Invalid = true);
509 bool isInvalidDecl() const { return (bool) InvalidDecl; }
511 /// isImplicit - Indicates whether the declaration was implicitly
512 /// generated by the implementation. If false, this declaration
513 /// was written explicitly in the source code.
514 bool isImplicit() const { return Implicit; }
515 void setImplicit(bool I = true) { Implicit = I; }
517 /// \brief Whether this declaration was used, meaning that a definition
520 /// \param CheckUsedAttr When true, also consider the "used" attribute
521 /// (in addition to the "used" bit set by \c setUsed()) when determining
522 /// whether the function is used.
523 bool isUsed(bool CheckUsedAttr = true) const;
525 /// \brief Set whether the declaration is used, in the sense of odr-use.
527 /// This should only be used immediately after creating a declaration.
528 void setIsUsed() { Used = true; }
530 /// \brief Mark the declaration used, in the sense of odr-use.
532 /// This notifies any mutation listeners in addition to setting a bit
533 /// indicating the declaration is used.
534 void markUsed(ASTContext &C);
536 /// \brief Whether any declaration of this entity was referenced.
537 bool isReferenced() const;
539 /// \brief Whether this declaration was referenced. This should not be relied
540 /// upon for anything other than debugging.
541 bool isThisDeclarationReferenced() const { return Referenced; }
543 void setReferenced(bool R = true) { Referenced = R; }
545 /// \brief Whether this declaration is a top-level declaration (function,
546 /// global variable, etc.) that is lexically inside an objc container
548 bool isTopLevelDeclInObjCContainer() const {
549 return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag;
552 void setTopLevelDeclInObjCContainer(bool V = true) {
553 unsigned Bits = NextInContextAndBits.getInt();
555 Bits |= TopLevelDeclInObjCContainerFlag;
557 Bits &= ~TopLevelDeclInObjCContainerFlag;
558 NextInContextAndBits.setInt(Bits);
561 /// \brief Whether this declaration was marked as being private to the
562 /// module in which it was defined.
563 bool isModulePrivate() const {
564 return NextInContextAndBits.getInt() & ModulePrivateFlag;
568 /// \brief Specify whether this declaration was marked as being private
569 /// to the module in which it was defined.
570 void setModulePrivate(bool MP = true) {
571 unsigned Bits = NextInContextAndBits.getInt();
573 Bits |= ModulePrivateFlag;
575 Bits &= ~ModulePrivateFlag;
576 NextInContextAndBits.setInt(Bits);
579 /// \brief Set the owning module ID.
580 void setOwningModuleID(unsigned ID) {
581 assert(isFromASTFile() && "Only works on a deserialized declaration");
582 *((unsigned*)this - 2) = ID;
587 /// \brief Determine the availability of the given declaration.
589 /// This routine will determine the most restrictive availability of
590 /// the given declaration (e.g., preferring 'unavailable' to
593 /// \param Message If non-NULL and the result is not \c
594 /// AR_Available, will be set to a (possibly empty) message
595 /// describing why the declaration has not been introduced, is
596 /// deprecated, or is unavailable.
597 AvailabilityResult getAvailability(std::string *Message = nullptr) const;
599 /// \brief Determine whether this declaration is marked 'deprecated'.
601 /// \param Message If non-NULL and the declaration is deprecated,
602 /// this will be set to the message describing why the declaration
603 /// was deprecated (which may be empty).
604 bool isDeprecated(std::string *Message = nullptr) const {
605 return getAvailability(Message) == AR_Deprecated;
608 /// \brief Determine whether this declaration is marked 'unavailable'.
610 /// \param Message If non-NULL and the declaration is unavailable,
611 /// this will be set to the message describing why the declaration
612 /// was made unavailable (which may be empty).
613 bool isUnavailable(std::string *Message = nullptr) const {
614 return getAvailability(Message) == AR_Unavailable;
617 /// \brief Determine whether this is a weak-imported symbol.
619 /// Weak-imported symbols are typically marked with the
620 /// 'weak_import' attribute, but may also be marked with an
621 /// 'availability' attribute where we're targing a platform prior to
622 /// the introduction of this feature.
623 bool isWeakImported() const;
625 /// \brief Determines whether this symbol can be weak-imported,
626 /// e.g., whether it would be well-formed to add the weak_import
629 /// \param IsDefinition Set to \c true to indicate that this
630 /// declaration cannot be weak-imported because it has a definition.
631 bool canBeWeakImported(bool &IsDefinition) const;
633 /// \brief Determine whether this declaration came from an AST file (such as
634 /// a precompiled header or module) rather than having been parsed.
635 bool isFromASTFile() const { return FromASTFile; }
637 /// \brief Retrieve the global declaration ID associated with this
638 /// declaration, which specifies where in the
639 unsigned getGlobalID() const {
641 return *((const unsigned*)this - 1);
645 /// \brief Retrieve the global ID of the module that owns this particular
647 unsigned getOwningModuleID() const {
649 return *((const unsigned*)this - 2);
655 Module *getOwningModuleSlow() const;
657 bool hasLocalOwningModuleStorage() const;
660 /// \brief Get the imported owning module, if this decl is from an imported
661 /// (non-local) module.
662 Module *getImportedOwningModule() const {
663 if (!isFromASTFile())
666 return getOwningModuleSlow();
669 /// \brief Get the local owning module, if known. Returns nullptr if owner is
670 /// not yet known or declaration is not from a module.
671 Module *getLocalOwningModule() const {
672 if (isFromASTFile() || !Hidden)
674 return reinterpret_cast<Module *const *>(this)[-1];
676 void setLocalOwningModule(Module *M) {
677 assert(!isFromASTFile() && Hidden && hasLocalOwningModuleStorage() &&
678 "should not have a cached owning module");
679 reinterpret_cast<Module **>(this)[-1] = M;
682 unsigned getIdentifierNamespace() const {
683 return IdentifierNamespace;
685 bool isInIdentifierNamespace(unsigned NS) const {
686 return getIdentifierNamespace() & NS;
688 static unsigned getIdentifierNamespaceForKind(Kind DK);
690 bool hasTagIdentifierNamespace() const {
691 return isTagIdentifierNamespace(getIdentifierNamespace());
693 static bool isTagIdentifierNamespace(unsigned NS) {
694 // TagDecls have Tag and Type set and may also have TagFriend.
695 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
698 /// getLexicalDeclContext - The declaration context where this Decl was
699 /// lexically declared (LexicalDC). May be different from
700 /// getDeclContext() (SemanticDC).
704 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
706 /// void A::f(); // SemanticDC == namespace 'A'
707 /// // LexicalDC == global namespace
708 DeclContext *getLexicalDeclContext() {
710 return getSemanticDC();
711 return getMultipleDC()->LexicalDC;
713 const DeclContext *getLexicalDeclContext() const {
714 return const_cast<Decl*>(this)->getLexicalDeclContext();
717 /// Determine whether this declaration is declared out of line (outside its
718 /// semantic context).
719 virtual bool isOutOfLine() const;
721 /// setDeclContext - Set both the semantic and lexical DeclContext
723 void setDeclContext(DeclContext *DC);
725 void setLexicalDeclContext(DeclContext *DC);
727 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
728 /// scoped decl is defined outside the current function or method. This is
729 /// roughly global variables and functions, but also handles enums (which
730 /// could be defined inside or outside a function etc).
731 bool isDefinedOutsideFunctionOrMethod() const {
732 return getParentFunctionOrMethod() == nullptr;
735 /// \brief Returns true if this declaration lexically is inside a function.
736 /// It recognizes non-defining declarations as well as members of local
739 /// void foo() { void bar(); }
740 /// void foo2() { class ABC { void bar(); }; }
742 bool isLexicallyWithinFunctionOrMethod() const;
744 /// \brief If this decl is defined inside a function/method/block it returns
745 /// the corresponding DeclContext, otherwise it returns null.
746 const DeclContext *getParentFunctionOrMethod() const;
747 DeclContext *getParentFunctionOrMethod() {
748 return const_cast<DeclContext*>(
749 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
752 /// \brief Retrieves the "canonical" declaration of the given declaration.
753 virtual Decl *getCanonicalDecl() { return this; }
754 const Decl *getCanonicalDecl() const {
755 return const_cast<Decl*>(this)->getCanonicalDecl();
758 /// \brief Whether this particular Decl is a canonical one.
759 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
762 /// \brief Returns the next redeclaration or itself if this is the only decl.
764 /// Decl subclasses that can be redeclared should override this method so that
765 /// Decl::redecl_iterator can iterate over them.
766 virtual Decl *getNextRedeclarationImpl() { return this; }
768 /// \brief Implementation of getPreviousDecl(), to be overridden by any
769 /// subclass that has a redeclaration chain.
770 virtual Decl *getPreviousDeclImpl() { return nullptr; }
772 /// \brief Implementation of getMostRecentDecl(), to be overridden by any
773 /// subclass that has a redeclaration chain.
774 virtual Decl *getMostRecentDeclImpl() { return this; }
777 /// \brief Iterates through all the redeclarations of the same decl.
778 class redecl_iterator {
779 /// Current - The current declaration.
784 typedef Decl *value_type;
785 typedef const value_type &reference;
786 typedef const value_type *pointer;
787 typedef std::forward_iterator_tag iterator_category;
788 typedef std::ptrdiff_t difference_type;
790 redecl_iterator() : Current(nullptr) { }
791 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
793 reference operator*() const { return Current; }
794 value_type operator->() const { return Current; }
796 redecl_iterator& operator++() {
797 assert(Current && "Advancing while iterator has reached end");
798 // Get either previous decl or latest decl.
799 Decl *Next = Current->getNextRedeclarationImpl();
800 assert(Next && "Should return next redeclaration or itself, never null!");
801 Current = (Next != Starter) ? Next : nullptr;
805 redecl_iterator operator++(int) {
806 redecl_iterator tmp(*this);
811 friend bool operator==(redecl_iterator x, redecl_iterator y) {
812 return x.Current == y.Current;
814 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
815 return x.Current != y.Current;
819 typedef llvm::iterator_range<redecl_iterator> redecl_range;
821 /// \brief Returns an iterator range for all the redeclarations of the same
822 /// decl. It will iterate at least once (when this decl is the only one).
823 redecl_range redecls() const {
824 return redecl_range(redecls_begin(), redecls_end());
827 redecl_iterator redecls_begin() const {
828 return redecl_iterator(const_cast<Decl *>(this));
830 redecl_iterator redecls_end() const { return redecl_iterator(); }
832 /// \brief Retrieve the previous declaration that declares the same entity
833 /// as this declaration, or NULL if there is no previous declaration.
834 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
836 /// \brief Retrieve the most recent declaration that declares the same entity
837 /// as this declaration, or NULL if there is no previous declaration.
838 const Decl *getPreviousDecl() const {
839 return const_cast<Decl *>(this)->getPreviousDeclImpl();
842 /// \brief True if this is the first declaration in its redeclaration chain.
843 bool isFirstDecl() const {
844 return getPreviousDecl() == nullptr;
847 /// \brief Retrieve the most recent declaration that declares the same entity
848 /// as this declaration (which may be this declaration).
849 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
851 /// \brief Retrieve the most recent declaration that declares the same entity
852 /// as this declaration (which may be this declaration).
853 const Decl *getMostRecentDecl() const {
854 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
857 /// getBody - If this Decl represents a declaration for a body of code,
858 /// such as a function or method definition, this method returns the
859 /// top-level Stmt* of that body. Otherwise this method returns null.
860 virtual Stmt* getBody() const { return nullptr; }
862 /// \brief Returns true if this \c Decl represents a declaration for a body of
863 /// code, such as a function or method definition.
864 /// Note that \c hasBody can also return true if any redeclaration of this
865 /// \c Decl represents a declaration for a body of code.
866 virtual bool hasBody() const { return getBody() != nullptr; }
868 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
869 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
870 SourceLocation getBodyRBrace() const;
872 // global temp stats (until we have a per-module visitor)
873 static void add(Kind k);
874 static void EnableStatistics();
875 static void PrintStats();
877 /// isTemplateParameter - Determines whether this declaration is a
878 /// template parameter.
879 bool isTemplateParameter() const;
881 /// isTemplateParameter - Determines whether this declaration is a
882 /// template parameter pack.
883 bool isTemplateParameterPack() const;
885 /// \brief Whether this declaration is a parameter pack.
886 bool isParameterPack() const;
888 /// \brief returns true if this declaration is a template
889 bool isTemplateDecl() const;
891 /// \brief Whether this declaration is a function or function template.
892 bool isFunctionOrFunctionTemplate() const {
893 return (DeclKind >= Decl::firstFunction &&
894 DeclKind <= Decl::lastFunction) ||
895 DeclKind == FunctionTemplate;
898 /// \brief Returns the function itself, or the templated function if this is a
899 /// function template.
900 FunctionDecl *getAsFunction() LLVM_READONLY;
902 const FunctionDecl *getAsFunction() const {
903 return const_cast<Decl *>(this)->getAsFunction();
906 /// \brief Changes the namespace of this declaration to reflect that it's
907 /// a function-local extern declaration.
909 /// These declarations appear in the lexical context of the extern
910 /// declaration, but in the semantic context of the enclosing namespace
912 void setLocalExternDecl() {
913 assert((IdentifierNamespace == IDNS_Ordinary ||
914 IdentifierNamespace == IDNS_OrdinaryFriend) &&
915 "namespace is not ordinary");
917 Decl *Prev = getPreviousDecl();
918 IdentifierNamespace &= ~IDNS_Ordinary;
920 IdentifierNamespace |= IDNS_LocalExtern;
921 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
922 IdentifierNamespace |= IDNS_Ordinary;
925 /// \brief Determine whether this is a block-scope declaration with linkage.
926 /// This will either be a local variable declaration declared 'extern', or a
927 /// local function declaration.
928 bool isLocalExternDecl() {
929 return IdentifierNamespace & IDNS_LocalExtern;
932 /// \brief Changes the namespace of this declaration to reflect that it's
933 /// the object of a friend declaration.
935 /// These declarations appear in the lexical context of the friending
936 /// class, but in the semantic context of the actual entity. This property
937 /// applies only to a specific decl object; other redeclarations of the
938 /// same entity may not (and probably don't) share this property.
939 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
940 unsigned OldNS = IdentifierNamespace;
941 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
942 IDNS_TagFriend | IDNS_OrdinaryFriend |
943 IDNS_LocalExtern)) &&
944 "namespace includes neither ordinary nor tag");
945 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
946 IDNS_TagFriend | IDNS_OrdinaryFriend |
947 IDNS_LocalExtern)) &&
948 "namespace includes other than ordinary or tag");
950 Decl *Prev = getPreviousDecl();
951 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
953 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
954 IdentifierNamespace |= IDNS_TagFriend;
955 if (PerformFriendInjection ||
956 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
957 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
960 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | IDNS_LocalExtern)) {
961 IdentifierNamespace |= IDNS_OrdinaryFriend;
962 if (PerformFriendInjection ||
963 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
964 IdentifierNamespace |= IDNS_Ordinary;
968 enum FriendObjectKind {
969 FOK_None, ///< Not a friend object.
970 FOK_Declared, ///< A friend of a previously-declared entity.
971 FOK_Undeclared ///< A friend of a previously-undeclared entity.
974 /// \brief Determines whether this declaration is the object of a
975 /// friend declaration and, if so, what kind.
977 /// There is currently no direct way to find the associated FriendDecl.
978 FriendObjectKind getFriendObjectKind() const {
980 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
981 if (!mask) return FOK_None;
982 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
986 /// Specifies that this declaration is a C++ overloaded non-member.
987 void setNonMemberOperator() {
988 assert(getKind() == Function || getKind() == FunctionTemplate);
989 assert((IdentifierNamespace & IDNS_Ordinary) &&
990 "visible non-member operators should be in ordinary namespace");
991 IdentifierNamespace |= IDNS_NonMemberOperator;
994 static bool classofKind(Kind K) { return true; }
995 static DeclContext *castToDeclContext(const Decl *);
996 static Decl *castFromDeclContext(const DeclContext *);
998 void print(raw_ostream &Out, unsigned Indentation = 0,
999 bool PrintInstantiation = false) const;
1000 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1001 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1002 static void printGroup(Decl** Begin, unsigned NumDecls,
1003 raw_ostream &Out, const PrintingPolicy &Policy,
1004 unsigned Indentation = 0);
1005 // Debuggers don't usually respect default arguments.
1007 // Same as dump(), but forces color printing.
1008 void dumpColor() const;
1009 void dump(raw_ostream &Out) const;
1011 /// \brief Looks through the Decl's underlying type to extract a FunctionType
1012 /// when possible. Will return null if the type underlying the Decl does not
1013 /// have a FunctionType.
1014 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1017 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1018 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1022 ASTMutationListener *getASTMutationListener() const;
1025 /// \brief Determine whether two declarations declare the same entity.
1026 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1033 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1036 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1037 /// doing something to a specific decl.
1038 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1039 const Decl *TheDecl;
1042 const char *Message;
1044 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1045 SourceManager &sm, const char *Msg)
1046 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1048 void print(raw_ostream &OS) const override;
1051 /// \brief The results of name lookup within a DeclContext. This is either a
1052 /// single result (with no stable storage) or a collection of results (with
1053 /// stable storage provided by the lookup table).
1054 class DeclContextLookupResult {
1055 typedef ArrayRef<NamedDecl *> ResultTy;
1057 // If there is only one lookup result, it would be invalidated by
1058 // reallocations of the name table, so store it separately.
1061 static NamedDecl *const SingleElementDummyList;
1064 DeclContextLookupResult() : Result(), Single() {}
1065 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1066 : Result(Result), Single() {}
1067 DeclContextLookupResult(NamedDecl *Single)
1068 : Result(SingleElementDummyList), Single(Single) {}
1071 typedef llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1072 std::random_access_iterator_tag,
1073 NamedDecl *const> IteratorBase;
1074 class iterator : public IteratorBase {
1075 value_type SingleElement;
1078 iterator() : IteratorBase(), SingleElement() {}
1079 explicit iterator(pointer Pos, value_type Single = nullptr)
1080 : IteratorBase(Pos), SingleElement(Single) {}
1082 reference operator*() const {
1083 return SingleElement ? SingleElement : IteratorBase::operator*();
1086 typedef iterator const_iterator;
1087 typedef iterator::pointer pointer;
1088 typedef iterator::reference reference;
1090 iterator begin() const { return iterator(Result.begin(), Single); }
1091 iterator end() const { return iterator(Result.end(), Single); }
1093 bool empty() const { return Result.empty(); }
1094 pointer data() const { return Single ? &Single : Result.data(); }
1095 size_t size() const { return Single ? 1 : Result.size(); }
1096 reference front() const { return Single ? Single : Result.front(); }
1097 reference back() const { return Single ? Single : Result.back(); }
1098 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1100 // FIXME: Remove this from the interface
1101 DeclContextLookupResult slice(size_t N) const {
1102 DeclContextLookupResult Sliced = Result.slice(N);
1103 Sliced.Single = Single;
1108 /// DeclContext - This is used only as base class of specific decl types that
1109 /// can act as declaration contexts. These decls are (only the top classes
1110 /// that directly derive from DeclContext are mentioned, not their subclasses):
1112 /// TranslationUnitDecl
1117 /// ObjCContainerDecl
1122 /// DeclKind - This indicates which class this is.
1123 unsigned DeclKind : 8;
1125 /// \brief Whether this declaration context also has some external
1126 /// storage that contains additional declarations that are lexically
1127 /// part of this context.
1128 mutable bool ExternalLexicalStorage : 1;
1130 /// \brief Whether this declaration context also has some external
1131 /// storage that contains additional declarations that are visible
1132 /// in this context.
1133 mutable bool ExternalVisibleStorage : 1;
1135 /// \brief Whether this declaration context has had external visible
1136 /// storage added since the last lookup. In this case, \c LookupPtr's
1137 /// invariant may not hold and needs to be fixed before we perform
1139 mutable bool NeedToReconcileExternalVisibleStorage : 1;
1141 /// \brief If \c true, this context may have local lexical declarations
1142 /// that are missing from the lookup table.
1143 mutable bool HasLazyLocalLexicalLookups : 1;
1145 /// \brief If \c true, the external source may have lexical declarations
1146 /// that are missing from the lookup table.
1147 mutable bool HasLazyExternalLexicalLookups : 1;
1149 /// \brief If \c true, lookups should only return identifier from
1150 /// DeclContext scope (for example TranslationUnit). Used in
1151 /// LookupQualifiedName()
1152 mutable bool UseQualifiedLookup : 1;
1154 /// \brief Pointer to the data structure used to lookup declarations
1155 /// within this context (or a DependentStoredDeclsMap if this is a
1156 /// dependent context). We maintain the invariant that, if the map
1157 /// contains an entry for a DeclarationName (and we haven't lazily
1158 /// omitted anything), then it contains all relevant entries for that
1159 /// name (modulo the hasExternalDecls() flag).
1160 mutable StoredDeclsMap *LookupPtr;
1163 /// FirstDecl - The first declaration stored within this declaration
1165 mutable Decl *FirstDecl;
1167 /// LastDecl - The last declaration stored within this declaration
1168 /// context. FIXME: We could probably cache this value somewhere
1169 /// outside of the DeclContext, to reduce the size of DeclContext by
1170 /// another pointer.
1171 mutable Decl *LastDecl;
1173 friend class ExternalASTSource;
1174 friend class ASTDeclReader;
1175 friend class ASTWriter;
1177 /// \brief Build up a chain of declarations.
1179 /// \returns the first/last pair of declarations.
1180 static std::pair<Decl *, Decl *>
1181 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1183 DeclContext(Decl::Kind K)
1184 : DeclKind(K), ExternalLexicalStorage(false),
1185 ExternalVisibleStorage(false),
1186 NeedToReconcileExternalVisibleStorage(false),
1187 HasLazyLocalLexicalLookups(false), HasLazyExternalLexicalLookups(false),
1188 UseQualifiedLookup(false),
1189 LookupPtr(nullptr), FirstDecl(nullptr), LastDecl(nullptr) {}
1194 Decl::Kind getDeclKind() const {
1195 return static_cast<Decl::Kind>(DeclKind);
1197 const char *getDeclKindName() const;
1199 /// getParent - Returns the containing DeclContext.
1200 DeclContext *getParent() {
1201 return cast<Decl>(this)->getDeclContext();
1203 const DeclContext *getParent() const {
1204 return const_cast<DeclContext*>(this)->getParent();
1207 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1208 /// different from getParent, e.g.:
1213 /// struct A::S {}; // getParent() == namespace 'A'
1214 /// // getLexicalParent() == translation unit
1216 DeclContext *getLexicalParent() {
1217 return cast<Decl>(this)->getLexicalDeclContext();
1219 const DeclContext *getLexicalParent() const {
1220 return const_cast<DeclContext*>(this)->getLexicalParent();
1223 DeclContext *getLookupParent();
1225 const DeclContext *getLookupParent() const {
1226 return const_cast<DeclContext*>(this)->getLookupParent();
1229 ASTContext &getParentASTContext() const {
1230 return cast<Decl>(this)->getASTContext();
1233 bool isClosure() const {
1234 return DeclKind == Decl::Block;
1237 bool isObjCContainer() const {
1239 case Decl::ObjCCategory:
1240 case Decl::ObjCCategoryImpl:
1241 case Decl::ObjCImplementation:
1242 case Decl::ObjCInterface:
1243 case Decl::ObjCProtocol:
1249 bool isFunctionOrMethod() const {
1252 case Decl::Captured:
1253 case Decl::ObjCMethod:
1256 return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1260 /// \brief Test whether the context supports looking up names.
1261 bool isLookupContext() const {
1262 return !isFunctionOrMethod() && DeclKind != Decl::LinkageSpec;
1265 bool isFileContext() const {
1266 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1269 bool isTranslationUnit() const {
1270 return DeclKind == Decl::TranslationUnit;
1273 bool isRecord() const {
1274 return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1277 bool isNamespace() const {
1278 return DeclKind == Decl::Namespace;
1281 bool isStdNamespace() const;
1283 bool isInlineNamespace() const;
1285 /// \brief Determines whether this context is dependent on a
1286 /// template parameter.
1287 bool isDependentContext() const;
1289 /// isTransparentContext - Determines whether this context is a
1290 /// "transparent" context, meaning that the members declared in this
1291 /// context are semantically declared in the nearest enclosing
1292 /// non-transparent (opaque) context but are lexically declared in
1293 /// this context. For example, consider the enumerators of an
1294 /// enumeration type:
1300 /// Here, E is a transparent context, so its enumerator (Val1) will
1301 /// appear (semantically) that it is in the same context of E.
1302 /// Examples of transparent contexts include: enumerations (except for
1303 /// C++0x scoped enums), and C++ linkage specifications.
1304 bool isTransparentContext() const;
1306 /// \brief Determines whether this context or some of its ancestors is a
1307 /// linkage specification context that specifies C linkage.
1308 bool isExternCContext() const;
1310 /// \brief Determines whether this context or some of its ancestors is a
1311 /// linkage specification context that specifies C++ linkage.
1312 bool isExternCXXContext() const;
1314 /// \brief Determine whether this declaration context is equivalent
1315 /// to the declaration context DC.
1316 bool Equals(const DeclContext *DC) const {
1317 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1320 /// \brief Determine whether this declaration context encloses the
1321 /// declaration context DC.
1322 bool Encloses(const DeclContext *DC) const;
1324 /// \brief Find the nearest non-closure ancestor of this context,
1325 /// i.e. the innermost semantic parent of this context which is not
1326 /// a closure. A context may be its own non-closure ancestor.
1327 Decl *getNonClosureAncestor();
1328 const Decl *getNonClosureAncestor() const {
1329 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1332 /// getPrimaryContext - There may be many different
1333 /// declarations of the same entity (including forward declarations
1334 /// of classes, multiple definitions of namespaces, etc.), each with
1335 /// a different set of declarations. This routine returns the
1336 /// "primary" DeclContext structure, which will contain the
1337 /// information needed to perform name lookup into this context.
1338 DeclContext *getPrimaryContext();
1339 const DeclContext *getPrimaryContext() const {
1340 return const_cast<DeclContext*>(this)->getPrimaryContext();
1343 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1344 /// other entities of the same name, or where it is a redeclaration if the
1345 /// two entities are compatible. This skips through transparent contexts.
1346 DeclContext *getRedeclContext();
1347 const DeclContext *getRedeclContext() const {
1348 return const_cast<DeclContext *>(this)->getRedeclContext();
1351 /// \brief Retrieve the nearest enclosing namespace context.
1352 DeclContext *getEnclosingNamespaceContext();
1353 const DeclContext *getEnclosingNamespaceContext() const {
1354 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1357 /// \brief Retrieve the outermost lexically enclosing record context.
1358 RecordDecl *getOuterLexicalRecordContext();
1359 const RecordDecl *getOuterLexicalRecordContext() const {
1360 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1363 /// \brief Test if this context is part of the enclosing namespace set of
1364 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1365 /// isn't a namespace, this is equivalent to Equals().
1367 /// The enclosing namespace set of a namespace is the namespace and, if it is
1368 /// inline, its enclosing namespace, recursively.
1369 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1371 /// \brief Collects all of the declaration contexts that are semantically
1372 /// connected to this declaration context.
1374 /// For declaration contexts that have multiple semantically connected but
1375 /// syntactically distinct contexts, such as C++ namespaces, this routine
1376 /// retrieves the complete set of such declaration contexts in source order.
1377 /// For example, given:
1388 /// The \c Contexts parameter will contain both definitions of N.
1390 /// \param Contexts Will be cleared and set to the set of declaration
1391 /// contexts that are semanticaly connected to this declaration context,
1392 /// in source order, including this context (which may be the only result,
1393 /// for non-namespace contexts).
1394 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1396 /// decl_iterator - Iterates through the declarations stored
1397 /// within this context.
1398 class decl_iterator {
1399 /// Current - The current declaration.
1403 typedef Decl *value_type;
1404 typedef const value_type &reference;
1405 typedef const value_type *pointer;
1406 typedef std::forward_iterator_tag iterator_category;
1407 typedef std::ptrdiff_t difference_type;
1409 decl_iterator() : Current(nullptr) { }
1410 explicit decl_iterator(Decl *C) : Current(C) { }
1412 reference operator*() const { return Current; }
1413 // This doesn't meet the iterator requirements, but it's convenient
1414 value_type operator->() const { return Current; }
1416 decl_iterator& operator++() {
1417 Current = Current->getNextDeclInContext();
1421 decl_iterator operator++(int) {
1422 decl_iterator tmp(*this);
1427 friend bool operator==(decl_iterator x, decl_iterator y) {
1428 return x.Current == y.Current;
1430 friend bool operator!=(decl_iterator x, decl_iterator y) {
1431 return x.Current != y.Current;
1435 typedef llvm::iterator_range<decl_iterator> decl_range;
1437 /// decls_begin/decls_end - Iterate over the declarations stored in
1439 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
1440 decl_iterator decls_begin() const;
1441 decl_iterator decls_end() const { return decl_iterator(); }
1442 bool decls_empty() const;
1444 /// noload_decls_begin/end - Iterate over the declarations stored in this
1445 /// context that are currently loaded; don't attempt to retrieve anything
1446 /// from an external source.
1447 decl_range noload_decls() const {
1448 return decl_range(noload_decls_begin(), noload_decls_end());
1450 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
1451 decl_iterator noload_decls_end() const { return decl_iterator(); }
1453 /// specific_decl_iterator - Iterates over a subrange of
1454 /// declarations stored in a DeclContext, providing only those that
1455 /// are of type SpecificDecl (or a class derived from it). This
1456 /// iterator is used, for example, to provide iteration over just
1457 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1458 template<typename SpecificDecl>
1459 class specific_decl_iterator {
1460 /// Current - The current, underlying declaration iterator, which
1461 /// will either be NULL or will point to a declaration of
1462 /// type SpecificDecl.
1463 DeclContext::decl_iterator Current;
1465 /// SkipToNextDecl - Advances the current position up to the next
1466 /// declaration of type SpecificDecl that also meets the criteria
1467 /// required by Acceptable.
1468 void SkipToNextDecl() {
1469 while (*Current && !isa<SpecificDecl>(*Current))
1474 typedef SpecificDecl *value_type;
1475 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1476 // type) if we ever have a need for them.
1477 typedef void reference;
1478 typedef void pointer;
1479 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1481 typedef std::forward_iterator_tag iterator_category;
1483 specific_decl_iterator() : Current() { }
1485 /// specific_decl_iterator - Construct a new iterator over a
1486 /// subset of the declarations the range [C,
1487 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1488 /// member function of SpecificDecl that should return true for
1489 /// all of the SpecificDecl instances that will be in the subset
1490 /// of iterators. For example, if you want Objective-C instance
1491 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1492 /// &ObjCMethodDecl::isInstanceMethod.
1493 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1497 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1498 // This doesn't meet the iterator requirements, but it's convenient
1499 value_type operator->() const { return **this; }
1501 specific_decl_iterator& operator++() {
1507 specific_decl_iterator operator++(int) {
1508 specific_decl_iterator tmp(*this);
1513 friend bool operator==(const specific_decl_iterator& x,
1514 const specific_decl_iterator& y) {
1515 return x.Current == y.Current;
1518 friend bool operator!=(const specific_decl_iterator& x,
1519 const specific_decl_iterator& y) {
1520 return x.Current != y.Current;
1524 /// \brief Iterates over a filtered subrange of declarations stored
1525 /// in a DeclContext.
1527 /// This iterator visits only those declarations that are of type
1528 /// SpecificDecl (or a class derived from it) and that meet some
1529 /// additional run-time criteria. This iterator is used, for
1530 /// example, to provide access to the instance methods within an
1531 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1532 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1533 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1534 class filtered_decl_iterator {
1535 /// Current - The current, underlying declaration iterator, which
1536 /// will either be NULL or will point to a declaration of
1537 /// type SpecificDecl.
1538 DeclContext::decl_iterator Current;
1540 /// SkipToNextDecl - Advances the current position up to the next
1541 /// declaration of type SpecificDecl that also meets the criteria
1542 /// required by Acceptable.
1543 void SkipToNextDecl() {
1545 (!isa<SpecificDecl>(*Current) ||
1546 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1551 typedef SpecificDecl *value_type;
1552 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1553 // type) if we ever have a need for them.
1554 typedef void reference;
1555 typedef void pointer;
1556 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1558 typedef std::forward_iterator_tag iterator_category;
1560 filtered_decl_iterator() : Current() { }
1562 /// filtered_decl_iterator - Construct a new iterator over a
1563 /// subset of the declarations the range [C,
1564 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1565 /// member function of SpecificDecl that should return true for
1566 /// all of the SpecificDecl instances that will be in the subset
1567 /// of iterators. For example, if you want Objective-C instance
1568 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1569 /// &ObjCMethodDecl::isInstanceMethod.
1570 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1574 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1575 value_type operator->() const { return cast<SpecificDecl>(*Current); }
1577 filtered_decl_iterator& operator++() {
1583 filtered_decl_iterator operator++(int) {
1584 filtered_decl_iterator tmp(*this);
1589 friend bool operator==(const filtered_decl_iterator& x,
1590 const filtered_decl_iterator& y) {
1591 return x.Current == y.Current;
1594 friend bool operator!=(const filtered_decl_iterator& x,
1595 const filtered_decl_iterator& y) {
1596 return x.Current != y.Current;
1600 /// @brief Add the declaration D into this context.
1602 /// This routine should be invoked when the declaration D has first
1603 /// been declared, to place D into the context where it was
1604 /// (lexically) defined. Every declaration must be added to one
1605 /// (and only one!) context, where it can be visited via
1606 /// [decls_begin(), decls_end()). Once a declaration has been added
1607 /// to its lexical context, the corresponding DeclContext owns the
1610 /// If D is also a NamedDecl, it will be made visible within its
1611 /// semantic context via makeDeclVisibleInContext.
1612 void addDecl(Decl *D);
1614 /// @brief Add the declaration D into this context, but suppress
1615 /// searches for external declarations with the same name.
1617 /// Although analogous in function to addDecl, this removes an
1618 /// important check. This is only useful if the Decl is being
1619 /// added in response to an external search; in all other cases,
1620 /// addDecl() is the right function to use.
1621 /// See the ASTImporter for use cases.
1622 void addDeclInternal(Decl *D);
1624 /// @brief Add the declaration D to this context without modifying
1625 /// any lookup tables.
1627 /// This is useful for some operations in dependent contexts where
1628 /// the semantic context might not be dependent; this basically
1629 /// only happens with friends.
1630 void addHiddenDecl(Decl *D);
1632 /// @brief Removes a declaration from this context.
1633 void removeDecl(Decl *D);
1635 /// @brief Checks whether a declaration is in this context.
1636 bool containsDecl(Decl *D) const;
1638 typedef DeclContextLookupResult lookup_result;
1639 typedef lookup_result::iterator lookup_iterator;
1641 /// lookup - Find the declarations (if any) with the given Name in
1642 /// this context. Returns a range of iterators that contains all of
1643 /// the declarations with this name, with object, function, member,
1644 /// and enumerator names preceding any tag name. Note that this
1645 /// routine will not look into parent contexts.
1646 lookup_result lookup(DeclarationName Name) const;
1648 /// \brief Find the declarations with the given name that are visible
1649 /// within this context; don't attempt to retrieve anything from an
1650 /// external source.
1651 lookup_result noload_lookup(DeclarationName Name);
1653 /// \brief A simplistic name lookup mechanism that performs name lookup
1654 /// into this declaration context without consulting the external source.
1656 /// This function should almost never be used, because it subverts the
1657 /// usual relationship between a DeclContext and the external source.
1658 /// See the ASTImporter for the (few, but important) use cases.
1660 /// FIXME: This is very inefficient; replace uses of it with uses of
1662 void localUncachedLookup(DeclarationName Name,
1663 SmallVectorImpl<NamedDecl *> &Results);
1665 /// @brief Makes a declaration visible within this context.
1667 /// This routine makes the declaration D visible to name lookup
1668 /// within this context and, if this is a transparent context,
1669 /// within its parent contexts up to the first enclosing
1670 /// non-transparent context. Making a declaration visible within a
1671 /// context does not transfer ownership of a declaration, and a
1672 /// declaration can be visible in many contexts that aren't its
1673 /// lexical context.
1675 /// If D is a redeclaration of an existing declaration that is
1676 /// visible from this context, as determined by
1677 /// NamedDecl::declarationReplaces, the previous declaration will be
1678 /// replaced with D.
1679 void makeDeclVisibleInContext(NamedDecl *D);
1681 /// all_lookups_iterator - An iterator that provides a view over the results
1682 /// of looking up every possible name.
1683 class all_lookups_iterator;
1685 typedef llvm::iterator_range<all_lookups_iterator> lookups_range;
1687 lookups_range lookups() const;
1688 lookups_range noload_lookups() const;
1690 /// \brief Iterators over all possible lookups within this context.
1691 all_lookups_iterator lookups_begin() const;
1692 all_lookups_iterator lookups_end() const;
1694 /// \brief Iterators over all possible lookups within this context that are
1695 /// currently loaded; don't attempt to retrieve anything from an external
1697 all_lookups_iterator noload_lookups_begin() const;
1698 all_lookups_iterator noload_lookups_end() const;
1700 struct udir_iterator;
1701 typedef llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
1702 std::random_access_iterator_tag,
1703 UsingDirectiveDecl *> udir_iterator_base;
1704 struct udir_iterator : udir_iterator_base {
1705 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
1706 UsingDirectiveDecl *operator*() const;
1709 typedef llvm::iterator_range<udir_iterator> udir_range;
1711 udir_range using_directives() const;
1713 // These are all defined in DependentDiagnostic.h.
1714 class ddiag_iterator;
1715 typedef llvm::iterator_range<DeclContext::ddiag_iterator> ddiag_range;
1717 inline ddiag_range ddiags() const;
1719 // Low-level accessors
1721 /// \brief Mark that there are external lexical declarations that we need
1722 /// to include in our lookup table (and that are not available as external
1723 /// visible lookups). These extra lookup results will be found by walking
1724 /// the lexical declarations of this context. This should be used only if
1725 /// setHasExternalLexicalStorage() has been called on any decl context for
1726 /// which this is the primary context.
1727 void setMustBuildLookupTable() {
1728 assert(this == getPrimaryContext() &&
1729 "should only be called on primary context");
1730 HasLazyExternalLexicalLookups = true;
1733 /// \brief Retrieve the internal representation of the lookup structure.
1734 /// This may omit some names if we are lazily building the structure.
1735 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
1737 /// \brief Ensure the lookup structure is fully-built and return it.
1738 StoredDeclsMap *buildLookup();
1740 /// \brief Whether this DeclContext has external storage containing
1741 /// additional declarations that are lexically in this context.
1742 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1744 /// \brief State whether this DeclContext has external storage for
1745 /// declarations lexically in this context.
1746 void setHasExternalLexicalStorage(bool ES = true) {
1747 ExternalLexicalStorage = ES;
1750 /// \brief Whether this DeclContext has external storage containing
1751 /// additional declarations that are visible in this context.
1752 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1754 /// \brief State whether this DeclContext has external storage for
1755 /// declarations visible in this context.
1756 void setHasExternalVisibleStorage(bool ES = true) {
1757 ExternalVisibleStorage = ES;
1758 if (ES && LookupPtr)
1759 NeedToReconcileExternalVisibleStorage = true;
1762 /// \brief Determine whether the given declaration is stored in the list of
1763 /// declarations lexically within this context.
1764 bool isDeclInLexicalTraversal(const Decl *D) const {
1765 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1769 bool setUseQualifiedLookup(bool use = true) {
1770 bool old_value = UseQualifiedLookup;
1771 UseQualifiedLookup = use;
1775 bool shouldUseQualifiedLookup() const {
1776 return UseQualifiedLookup;
1779 static bool classof(const Decl *D);
1780 static bool classof(const DeclContext *D) { return true; }
1782 void dumpDeclContext() const;
1783 void dumpLookups() const;
1784 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false) const;
1787 void reconcileExternalVisibleStorage() const;
1788 bool LoadLexicalDeclsFromExternalStorage() const;
1790 /// @brief Makes a declaration visible within this context, but
1791 /// suppresses searches for external declarations with the same
1794 /// Analogous to makeDeclVisibleInContext, but for the exclusive
1795 /// use of addDeclInternal().
1796 void makeDeclVisibleInContextInternal(NamedDecl *D);
1798 friend class DependentDiagnostic;
1799 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1801 void buildLookupImpl(DeclContext *DCtx, bool Internal);
1802 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1803 bool Rediscoverable);
1804 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1807 inline bool Decl::isTemplateParameter() const {
1808 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1809 getKind() == TemplateTemplateParm;
1812 // Specialization selected when ToTy is not a known subclass of DeclContext.
1813 template <class ToTy,
1814 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
1815 struct cast_convert_decl_context {
1816 static const ToTy *doit(const DeclContext *Val) {
1817 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1820 static ToTy *doit(DeclContext *Val) {
1821 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1825 // Specialization selected when ToTy is a known subclass of DeclContext.
1826 template <class ToTy>
1827 struct cast_convert_decl_context<ToTy, true> {
1828 static const ToTy *doit(const DeclContext *Val) {
1829 return static_cast<const ToTy*>(Val);
1832 static ToTy *doit(DeclContext *Val) {
1833 return static_cast<ToTy*>(Val);
1842 /// isa<T>(DeclContext*)
1843 template <typename To>
1844 struct isa_impl<To, ::clang::DeclContext> {
1845 static bool doit(const ::clang::DeclContext &Val) {
1846 return To::classofKind(Val.getDeclKind());
1850 /// cast<T>(DeclContext*)
1851 template<class ToTy>
1852 struct cast_convert_val<ToTy,
1853 const ::clang::DeclContext,const ::clang::DeclContext> {
1854 static const ToTy &doit(const ::clang::DeclContext &Val) {
1855 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1858 template<class ToTy>
1859 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
1860 static ToTy &doit(::clang::DeclContext &Val) {
1861 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1864 template<class ToTy>
1865 struct cast_convert_val<ToTy,
1866 const ::clang::DeclContext*, const ::clang::DeclContext*> {
1867 static const ToTy *doit(const ::clang::DeclContext *Val) {
1868 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1871 template<class ToTy>
1872 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
1873 static ToTy *doit(::clang::DeclContext *Val) {
1874 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1878 /// Implement cast_convert_val for Decl -> DeclContext conversions.
1879 template<class FromTy>
1880 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1881 static ::clang::DeclContext &doit(const FromTy &Val) {
1882 return *FromTy::castToDeclContext(&Val);
1886 template<class FromTy>
1887 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1888 static ::clang::DeclContext *doit(const FromTy *Val) {
1889 return FromTy::castToDeclContext(Val);
1893 template<class FromTy>
1894 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1895 static const ::clang::DeclContext &doit(const FromTy &Val) {
1896 return *FromTy::castToDeclContext(&Val);
1900 template<class FromTy>
1901 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1902 static const ::clang::DeclContext *doit(const FromTy *Val) {
1903 return FromTy::castToDeclContext(Val);
1907 } // end namespace llvm