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 "clang/Basic/VersionTuple.h"
21 #include "llvm/ADT/PointerUnion.h"
22 #include "llvm/ADT/iterator.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/PrettyStackTrace.h"
28 class ASTMutationListener;
33 class DeclarationName;
34 class DependentDiagnostic;
39 enum Linkage : unsigned char;
40 class LinkageComputer;
41 class LinkageSpecDecl;
45 class ObjCCategoryDecl;
46 class ObjCCategoryImplDecl;
47 class ObjCContainerDecl;
49 class ObjCImplementationDecl;
50 class ObjCInterfaceDecl;
52 class ObjCProtocolDecl;
53 struct PrintingPolicy;
58 class TranslationUnitDecl;
59 class UsingDirectiveDecl;
64 /// \brief Captures the result of checking the availability of a
66 enum AvailabilityResult {
73 /// Decl - This represents one declaration (or definition), e.g. a variable,
74 /// typedef, function, struct, etc.
76 /// Note: There are objects tacked on before the *beginning* of Decl
77 /// (and its subclasses) in its Decl::operator new(). Proper alignment
78 /// of all subclasses (not requiring more than the alignment of Decl) is
79 /// asserted in DeclBase.cpp.
80 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) Decl {
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,
171 /// This declaration is an OpenMP user defined reduction construction.
172 IDNS_OMPReduction = 0x1000
175 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
176 /// parameter types in method declarations. Other than remembering
177 /// them and mangling them into the method's signature string, these
178 /// are ignored by the compiler; they are consumed by certain
179 /// remote-messaging frameworks.
181 /// in, inout, and out are mutually exclusive and apply only to
182 /// method parameters. bycopy and byref are mutually exclusive and
183 /// apply only to method parameters (?). oneway applies only to
184 /// results. All of these expect their corresponding parameter to
185 /// have a particular type. None of this is currently enforced by
188 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
189 enum ObjCDeclQualifier {
194 OBJC_TQ_Bycopy = 0x8,
195 OBJC_TQ_Byref = 0x10,
196 OBJC_TQ_Oneway = 0x20,
198 /// The nullability qualifier is set when the nullability of the
199 /// result or parameter was expressed via a context-sensitive
201 OBJC_TQ_CSNullability = 0x40
205 // Enumeration values used in the bits stored in NextInContextAndBits.
207 /// \brief Whether this declaration is a top-level declaration (function,
208 /// global variable, etc.) that is lexically inside an objc container
210 TopLevelDeclInObjCContainerFlag = 0x01,
212 /// \brief Whether this declaration is private to the module in which it was
214 ModulePrivateFlag = 0x02
217 /// \brief The next declaration within the same lexical
218 /// DeclContext. These pointers form the linked list that is
219 /// traversed via DeclContext's decls_begin()/decls_end().
221 /// The extra two bits are used for the TopLevelDeclInObjCContainer and
222 /// ModulePrivate bits.
223 llvm::PointerIntPair<Decl *, 2, unsigned> NextInContextAndBits;
226 friend class DeclContext;
229 DeclContext *SemanticDC;
230 DeclContext *LexicalDC;
234 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
235 /// For declarations that don't contain C++ scope specifiers, it contains
236 /// the DeclContext where the Decl was declared.
237 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
238 /// with the context where it semantically belongs (SemanticDC) and the
239 /// context where it was lexically declared (LexicalDC).
243 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
245 /// void A::f(); // SemanticDC == namespace 'A'
246 /// // LexicalDC == global namespace
247 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
249 inline bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
250 inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
251 inline MultipleDC *getMultipleDC() const {
252 return DeclCtx.get<MultipleDC*>();
254 inline DeclContext *getSemanticDC() const {
255 return DeclCtx.get<DeclContext*>();
258 /// Loc - The location of this decl.
261 /// DeclKind - This indicates which class this is.
262 unsigned DeclKind : 7;
264 /// InvalidDecl - This indicates a semantic error occurred.
265 unsigned InvalidDecl : 1;
267 /// HasAttrs - This indicates whether the decl has attributes or not.
268 unsigned HasAttrs : 1;
270 /// Implicit - Whether this declaration was implicitly generated by
271 /// the implementation rather than explicitly written by the user.
272 unsigned Implicit : 1;
274 /// \brief Whether this declaration was "used", meaning that a definition is
278 /// \brief Whether this declaration was "referenced".
279 /// The difference with 'Used' is whether the reference appears in a
280 /// evaluated context or not, e.g. functions used in uninstantiated templates
281 /// are regarded as "referenced" but not "used".
282 unsigned Referenced : 1;
284 /// \brief Whether statistic collection is enabled.
285 static bool StatisticsEnabled;
288 /// Access - Used by C++ decls for the access specifier.
289 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
291 friend class CXXClassMemberWrapper;
293 /// \brief Whether this declaration was loaded from an AST file.
294 unsigned FromASTFile : 1;
296 /// \brief Whether this declaration is hidden from normal name lookup, e.g.,
297 /// because it is was loaded from an AST file is either module-private or
298 /// because its submodule has not been made visible.
301 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
302 unsigned IdentifierNamespace : 13;
304 /// \brief If 0, we have not computed the linkage of this declaration.
305 /// Otherwise, it is the linkage + 1.
306 mutable unsigned CacheValidAndLinkage : 3;
308 friend class ASTDeclWriter;
309 friend class ASTDeclReader;
310 friend class ASTReader;
311 friend class LinkageComputer;
313 template<typename decl_type> friend class Redeclarable;
315 /// \brief Allocate memory for a deserialized declaration.
317 /// This routine must be used to allocate memory for any declaration that is
318 /// deserialized from a module file.
320 /// \param Size The size of the allocated object.
321 /// \param Ctx The context in which we will allocate memory.
322 /// \param ID The global ID of the deserialized declaration.
323 /// \param Extra The amount of extra space to allocate after the object.
324 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
325 std::size_t Extra = 0);
327 /// \brief Allocate memory for a non-deserialized declaration.
328 void *operator new(std::size_t Size, const ASTContext &Ctx,
329 DeclContext *Parent, std::size_t Extra = 0);
332 bool AccessDeclContextSanity() const;
336 Decl(Kind DK, DeclContext *DC, SourceLocation L)
337 : NextInContextAndBits(), DeclCtx(DC),
338 Loc(L), DeclKind(DK), InvalidDecl(0),
339 HasAttrs(false), Implicit(false), Used(false), Referenced(false),
340 Access(AS_none), FromASTFile(0), Hidden(DC && cast<Decl>(DC)->Hidden),
341 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
342 CacheValidAndLinkage(0)
344 if (StatisticsEnabled) add(DK);
347 Decl(Kind DK, EmptyShell Empty)
348 : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0),
349 HasAttrs(false), Implicit(false), Used(false), Referenced(false),
350 Access(AS_none), FromASTFile(0), Hidden(0),
351 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
352 CacheValidAndLinkage(0)
354 if (StatisticsEnabled) add(DK);
359 /// \brief Update a potentially out-of-date declaration.
360 void updateOutOfDate(IdentifierInfo &II) const;
362 Linkage getCachedLinkage() const {
363 return Linkage(CacheValidAndLinkage - 1);
366 void setCachedLinkage(Linkage L) const {
367 CacheValidAndLinkage = L + 1;
370 bool hasCachedLinkage() const {
371 return CacheValidAndLinkage;
376 /// \brief Source range that this declaration covers.
377 virtual SourceRange getSourceRange() const LLVM_READONLY {
378 return SourceRange(getLocation(), getLocation());
380 SourceLocation getLocStart() const LLVM_READONLY {
381 return getSourceRange().getBegin();
383 SourceLocation getLocEnd() const LLVM_READONLY {
384 return getSourceRange().getEnd();
387 SourceLocation getLocation() const { return Loc; }
388 void setLocation(SourceLocation L) { Loc = L; }
390 Kind getKind() const { return static_cast<Kind>(DeclKind); }
391 const char *getDeclKindName() const;
393 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
394 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
396 DeclContext *getDeclContext() {
398 return getSemanticDC();
399 return getMultipleDC()->SemanticDC;
401 const DeclContext *getDeclContext() const {
402 return const_cast<Decl*>(this)->getDeclContext();
405 /// Find the innermost non-closure ancestor of this declaration,
406 /// walking up through blocks, lambdas, etc. If that ancestor is
407 /// not a code context (!isFunctionOrMethod()), returns null.
409 /// A declaration may be its own non-closure context.
410 Decl *getNonClosureContext();
411 const Decl *getNonClosureContext() const {
412 return const_cast<Decl*>(this)->getNonClosureContext();
415 TranslationUnitDecl *getTranslationUnitDecl();
416 const TranslationUnitDecl *getTranslationUnitDecl() const {
417 return const_cast<Decl*>(this)->getTranslationUnitDecl();
420 bool isInAnonymousNamespace() const;
422 bool isInStdNamespace() const;
424 ASTContext &getASTContext() const LLVM_READONLY;
426 void setAccess(AccessSpecifier AS) {
428 assert(AccessDeclContextSanity());
431 AccessSpecifier getAccess() const {
432 assert(AccessDeclContextSanity());
433 return AccessSpecifier(Access);
436 /// \brief Retrieve the access specifier for this declaration, even though
437 /// it may not yet have been properly set.
438 AccessSpecifier getAccessUnsafe() const {
439 return AccessSpecifier(Access);
442 bool hasAttrs() const { return HasAttrs; }
443 void setAttrs(const AttrVec& Attrs) {
444 return setAttrsImpl(Attrs, getASTContext());
446 AttrVec &getAttrs() {
447 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
449 const AttrVec &getAttrs() const;
452 void addAttr(Attr *A) {
454 getAttrs().push_back(A);
456 setAttrs(AttrVec(1, A));
459 typedef AttrVec::const_iterator attr_iterator;
460 typedef llvm::iterator_range<attr_iterator> attr_range;
462 attr_range attrs() const {
463 return attr_range(attr_begin(), attr_end());
466 attr_iterator attr_begin() const {
467 return hasAttrs() ? getAttrs().begin() : nullptr;
469 attr_iterator attr_end() const {
470 return hasAttrs() ? getAttrs().end() : nullptr;
473 template <typename T>
475 if (!HasAttrs) return;
477 AttrVec &Vec = getAttrs();
478 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
484 template <typename T>
485 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
486 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
489 template <typename T>
490 specific_attr_iterator<T> specific_attr_begin() const {
491 return specific_attr_iterator<T>(attr_begin());
493 template <typename T>
494 specific_attr_iterator<T> specific_attr_end() const {
495 return specific_attr_iterator<T>(attr_end());
498 template<typename T> T *getAttr() const {
499 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
501 template<typename T> bool hasAttr() const {
502 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
505 /// getMaxAlignment - return the maximum alignment specified by attributes
506 /// on this decl, 0 if there are none.
507 unsigned getMaxAlignment() const;
509 /// setInvalidDecl - Indicates the Decl had a semantic error. This
510 /// allows for graceful error recovery.
511 void setInvalidDecl(bool Invalid = true);
512 bool isInvalidDecl() const { return (bool) InvalidDecl; }
514 /// isImplicit - Indicates whether the declaration was implicitly
515 /// generated by the implementation. If false, this declaration
516 /// was written explicitly in the source code.
517 bool isImplicit() const { return Implicit; }
518 void setImplicit(bool I = true) { Implicit = I; }
520 /// \brief Whether *any* (re-)declaration of the entity was used, meaning that
521 /// a definition is required.
523 /// \param CheckUsedAttr When true, also consider the "used" attribute
524 /// (in addition to the "used" bit set by \c setUsed()) when determining
525 /// whether the function is used.
526 bool isUsed(bool CheckUsedAttr = true) const;
528 /// \brief Set whether the declaration is used, in the sense of odr-use.
530 /// This should only be used immediately after creating a declaration.
531 /// It intentionally doesn't notify any listeners.
532 void setIsUsed() { getCanonicalDecl()->Used = true; }
534 /// \brief Mark the declaration used, in the sense of odr-use.
536 /// This notifies any mutation listeners in addition to setting a bit
537 /// indicating the declaration is used.
538 void markUsed(ASTContext &C);
540 /// \brief Whether any declaration of this entity was referenced.
541 bool isReferenced() const;
543 /// \brief Whether this declaration was referenced. This should not be relied
544 /// upon for anything other than debugging.
545 bool isThisDeclarationReferenced() const { return Referenced; }
547 void setReferenced(bool R = true) { Referenced = R; }
549 /// \brief Whether this declaration is a top-level declaration (function,
550 /// global variable, etc.) that is lexically inside an objc container
552 bool isTopLevelDeclInObjCContainer() const {
553 return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag;
556 void setTopLevelDeclInObjCContainer(bool V = true) {
557 unsigned Bits = NextInContextAndBits.getInt();
559 Bits |= TopLevelDeclInObjCContainerFlag;
561 Bits &= ~TopLevelDeclInObjCContainerFlag;
562 NextInContextAndBits.setInt(Bits);
565 /// \brief Whether this declaration was marked as being private to the
566 /// module in which it was defined.
567 bool isModulePrivate() const {
568 return NextInContextAndBits.getInt() & ModulePrivateFlag;
571 /// \brief Whether this declaration is exported (by virtue of being lexically
572 /// within an ExportDecl or by being a NamespaceDecl).
573 bool isExported() const;
575 /// Return true if this declaration has an attribute which acts as
576 /// definition of the entity, such as 'alias' or 'ifunc'.
577 bool hasDefiningAttr() const;
579 /// Return this declaration's defining attribute if it has one.
580 const Attr *getDefiningAttr() const;
583 /// \brief Specify whether this declaration was marked as being private
584 /// to the module in which it was defined.
585 void setModulePrivate(bool MP = true) {
586 unsigned Bits = NextInContextAndBits.getInt();
588 Bits |= ModulePrivateFlag;
590 Bits &= ~ModulePrivateFlag;
591 NextInContextAndBits.setInt(Bits);
594 /// \brief Set the owning module ID.
595 void setOwningModuleID(unsigned ID) {
596 assert(isFromASTFile() && "Only works on a deserialized declaration");
597 *((unsigned*)this - 2) = ID;
602 /// \brief Determine the availability of the given declaration.
604 /// This routine will determine the most restrictive availability of
605 /// the given declaration (e.g., preferring 'unavailable' to
608 /// \param Message If non-NULL and the result is not \c
609 /// AR_Available, will be set to a (possibly empty) message
610 /// describing why the declaration has not been introduced, is
611 /// deprecated, or is unavailable.
613 /// \param EnclosingVersion The version to compare with. If empty, assume the
614 /// deployment target version.
616 getAvailability(std::string *Message = nullptr,
617 VersionTuple EnclosingVersion = VersionTuple()) const;
619 /// \brief Determine whether this declaration is marked 'deprecated'.
621 /// \param Message If non-NULL and the declaration is deprecated,
622 /// this will be set to the message describing why the declaration
623 /// was deprecated (which may be empty).
624 bool isDeprecated(std::string *Message = nullptr) const {
625 return getAvailability(Message) == AR_Deprecated;
628 /// \brief Determine whether this declaration is marked 'unavailable'.
630 /// \param Message If non-NULL and the declaration is unavailable,
631 /// this will be set to the message describing why the declaration
632 /// was made unavailable (which may be empty).
633 bool isUnavailable(std::string *Message = nullptr) const {
634 return getAvailability(Message) == AR_Unavailable;
637 /// \brief Determine whether this is a weak-imported symbol.
639 /// Weak-imported symbols are typically marked with the
640 /// 'weak_import' attribute, but may also be marked with an
641 /// 'availability' attribute where we're targing a platform prior to
642 /// the introduction of this feature.
643 bool isWeakImported() const;
645 /// \brief Determines whether this symbol can be weak-imported,
646 /// e.g., whether it would be well-formed to add the weak_import
649 /// \param IsDefinition Set to \c true to indicate that this
650 /// declaration cannot be weak-imported because it has a definition.
651 bool canBeWeakImported(bool &IsDefinition) const;
653 /// \brief Determine whether this declaration came from an AST file (such as
654 /// a precompiled header or module) rather than having been parsed.
655 bool isFromASTFile() const { return FromASTFile; }
657 /// \brief Retrieve the global declaration ID associated with this
658 /// declaration, which specifies where in the
659 unsigned getGlobalID() const {
661 return *((const unsigned*)this - 1);
665 /// \brief Retrieve the global ID of the module that owns this particular
667 unsigned getOwningModuleID() const {
669 return *((const unsigned*)this - 2);
675 Module *getOwningModuleSlow() const;
677 bool hasLocalOwningModuleStorage() const;
680 /// \brief Get the imported owning module, if this decl is from an imported
681 /// (non-local) module.
682 Module *getImportedOwningModule() const {
683 if (!isFromASTFile())
686 return getOwningModuleSlow();
689 /// \brief Get the local owning module, if known. Returns nullptr if owner is
690 /// not yet known or declaration is not from a module.
691 Module *getLocalOwningModule() const {
692 if (isFromASTFile() || !Hidden)
694 return reinterpret_cast<Module *const *>(this)[-1];
696 void setLocalOwningModule(Module *M) {
697 assert(!isFromASTFile() && Hidden && hasLocalOwningModuleStorage() &&
698 "should not have a cached owning module");
699 reinterpret_cast<Module **>(this)[-1] = M;
702 unsigned getIdentifierNamespace() const {
703 return IdentifierNamespace;
705 bool isInIdentifierNamespace(unsigned NS) const {
706 return getIdentifierNamespace() & NS;
708 static unsigned getIdentifierNamespaceForKind(Kind DK);
710 bool hasTagIdentifierNamespace() const {
711 return isTagIdentifierNamespace(getIdentifierNamespace());
713 static bool isTagIdentifierNamespace(unsigned NS) {
714 // TagDecls have Tag and Type set and may also have TagFriend.
715 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
718 /// getLexicalDeclContext - The declaration context where this Decl was
719 /// lexically declared (LexicalDC). May be different from
720 /// getDeclContext() (SemanticDC).
724 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
726 /// void A::f(); // SemanticDC == namespace 'A'
727 /// // LexicalDC == global namespace
728 DeclContext *getLexicalDeclContext() {
730 return getSemanticDC();
731 return getMultipleDC()->LexicalDC;
733 const DeclContext *getLexicalDeclContext() const {
734 return const_cast<Decl*>(this)->getLexicalDeclContext();
737 /// Determine whether this declaration is declared out of line (outside its
738 /// semantic context).
739 virtual bool isOutOfLine() const;
741 /// setDeclContext - Set both the semantic and lexical DeclContext
743 void setDeclContext(DeclContext *DC);
745 void setLexicalDeclContext(DeclContext *DC);
747 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
748 /// scoped decl is defined outside the current function or method. This is
749 /// roughly global variables and functions, but also handles enums (which
750 /// could be defined inside or outside a function etc).
751 bool isDefinedOutsideFunctionOrMethod() const {
752 return getParentFunctionOrMethod() == nullptr;
755 /// \brief Returns true if this declaration lexically is inside a function.
756 /// It recognizes non-defining declarations as well as members of local
759 /// void foo() { void bar(); }
760 /// void foo2() { class ABC { void bar(); }; }
762 bool isLexicallyWithinFunctionOrMethod() const;
764 /// \brief If this decl is defined inside a function/method/block it returns
765 /// the corresponding DeclContext, otherwise it returns null.
766 const DeclContext *getParentFunctionOrMethod() const;
767 DeclContext *getParentFunctionOrMethod() {
768 return const_cast<DeclContext*>(
769 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
772 /// \brief Retrieves the "canonical" declaration of the given declaration.
773 virtual Decl *getCanonicalDecl() { return this; }
774 const Decl *getCanonicalDecl() const {
775 return const_cast<Decl*>(this)->getCanonicalDecl();
778 /// \brief Whether this particular Decl is a canonical one.
779 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
782 /// \brief Returns the next redeclaration or itself if this is the only decl.
784 /// Decl subclasses that can be redeclared should override this method so that
785 /// Decl::redecl_iterator can iterate over them.
786 virtual Decl *getNextRedeclarationImpl() { return this; }
788 /// \brief Implementation of getPreviousDecl(), to be overridden by any
789 /// subclass that has a redeclaration chain.
790 virtual Decl *getPreviousDeclImpl() { return nullptr; }
792 /// \brief Implementation of getMostRecentDecl(), to be overridden by any
793 /// subclass that has a redeclaration chain.
794 virtual Decl *getMostRecentDeclImpl() { return this; }
797 /// \brief Iterates through all the redeclarations of the same decl.
798 class redecl_iterator {
799 /// Current - The current declaration.
804 typedef Decl *value_type;
805 typedef const value_type &reference;
806 typedef const value_type *pointer;
807 typedef std::forward_iterator_tag iterator_category;
808 typedef std::ptrdiff_t difference_type;
810 redecl_iterator() : Current(nullptr) { }
811 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
813 reference operator*() const { return Current; }
814 value_type operator->() const { return Current; }
816 redecl_iterator& operator++() {
817 assert(Current && "Advancing while iterator has reached end");
818 // Get either previous decl or latest decl.
819 Decl *Next = Current->getNextRedeclarationImpl();
820 assert(Next && "Should return next redeclaration or itself, never null!");
821 Current = (Next != Starter) ? Next : nullptr;
825 redecl_iterator operator++(int) {
826 redecl_iterator tmp(*this);
831 friend bool operator==(redecl_iterator x, redecl_iterator y) {
832 return x.Current == y.Current;
834 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
835 return x.Current != y.Current;
839 typedef llvm::iterator_range<redecl_iterator> redecl_range;
841 /// \brief Returns an iterator range for all the redeclarations of the same
842 /// decl. It will iterate at least once (when this decl is the only one).
843 redecl_range redecls() const {
844 return redecl_range(redecls_begin(), redecls_end());
847 redecl_iterator redecls_begin() const {
848 return redecl_iterator(const_cast<Decl *>(this));
850 redecl_iterator redecls_end() const { return redecl_iterator(); }
852 /// \brief Retrieve the previous declaration that declares the same entity
853 /// as this declaration, or NULL if there is no previous declaration.
854 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
856 /// \brief Retrieve the most recent declaration that declares the same entity
857 /// as this declaration, or NULL if there is no previous declaration.
858 const Decl *getPreviousDecl() const {
859 return const_cast<Decl *>(this)->getPreviousDeclImpl();
862 /// \brief True if this is the first declaration in its redeclaration chain.
863 bool isFirstDecl() const {
864 return getPreviousDecl() == nullptr;
867 /// \brief Retrieve the most recent declaration that declares the same entity
868 /// as this declaration (which may be this declaration).
869 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
871 /// \brief Retrieve the most recent declaration that declares the same entity
872 /// as this declaration (which may be this declaration).
873 const Decl *getMostRecentDecl() const {
874 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
877 /// getBody - If this Decl represents a declaration for a body of code,
878 /// such as a function or method definition, this method returns the
879 /// top-level Stmt* of that body. Otherwise this method returns null.
880 virtual Stmt* getBody() const { return nullptr; }
882 /// \brief Returns true if this \c Decl represents a declaration for a body of
883 /// code, such as a function or method definition.
884 /// Note that \c hasBody can also return true if any redeclaration of this
885 /// \c Decl represents a declaration for a body of code.
886 virtual bool hasBody() const { return getBody() != nullptr; }
888 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
889 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
890 SourceLocation getBodyRBrace() const;
892 // global temp stats (until we have a per-module visitor)
893 static void add(Kind k);
894 static void EnableStatistics();
895 static void PrintStats();
897 /// isTemplateParameter - Determines whether this declaration is a
898 /// template parameter.
899 bool isTemplateParameter() const;
901 /// isTemplateParameter - Determines whether this declaration is a
902 /// template parameter pack.
903 bool isTemplateParameterPack() const;
905 /// \brief Whether this declaration is a parameter pack.
906 bool isParameterPack() const;
908 /// \brief returns true if this declaration is a template
909 bool isTemplateDecl() const;
911 /// \brief Whether this declaration is a function or function template.
912 bool isFunctionOrFunctionTemplate() const {
913 return (DeclKind >= Decl::firstFunction &&
914 DeclKind <= Decl::lastFunction) ||
915 DeclKind == FunctionTemplate;
918 /// \brief If this is a declaration that describes some template, this
919 /// method returns that template declaration.
920 TemplateDecl *getDescribedTemplate() const;
922 /// \brief Returns the function itself, or the templated function if this is a
923 /// function template.
924 FunctionDecl *getAsFunction() LLVM_READONLY;
926 const FunctionDecl *getAsFunction() const {
927 return const_cast<Decl *>(this)->getAsFunction();
930 /// \brief Changes the namespace of this declaration to reflect that it's
931 /// a function-local extern declaration.
933 /// These declarations appear in the lexical context of the extern
934 /// declaration, but in the semantic context of the enclosing namespace
936 void setLocalExternDecl() {
937 assert((IdentifierNamespace == IDNS_Ordinary ||
938 IdentifierNamespace == IDNS_OrdinaryFriend) &&
939 "namespace is not ordinary");
941 Decl *Prev = getPreviousDecl();
942 IdentifierNamespace &= ~IDNS_Ordinary;
944 IdentifierNamespace |= IDNS_LocalExtern;
945 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
946 IdentifierNamespace |= IDNS_Ordinary;
949 /// \brief Determine whether this is a block-scope declaration with linkage.
950 /// This will either be a local variable declaration declared 'extern', or a
951 /// local function declaration.
952 bool isLocalExternDecl() {
953 return IdentifierNamespace & IDNS_LocalExtern;
956 /// \brief Changes the namespace of this declaration to reflect that it's
957 /// the object of a friend declaration.
959 /// These declarations appear in the lexical context of the friending
960 /// class, but in the semantic context of the actual entity. This property
961 /// applies only to a specific decl object; other redeclarations of the
962 /// same entity may not (and probably don't) share this property.
963 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
964 unsigned OldNS = IdentifierNamespace;
965 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
966 IDNS_TagFriend | IDNS_OrdinaryFriend |
967 IDNS_LocalExtern)) &&
968 "namespace includes neither ordinary nor tag");
969 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
970 IDNS_TagFriend | IDNS_OrdinaryFriend |
971 IDNS_LocalExtern)) &&
972 "namespace includes other than ordinary or tag");
974 Decl *Prev = getPreviousDecl();
975 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
977 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
978 IdentifierNamespace |= IDNS_TagFriend;
979 if (PerformFriendInjection ||
980 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
981 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
984 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | IDNS_LocalExtern)) {
985 IdentifierNamespace |= IDNS_OrdinaryFriend;
986 if (PerformFriendInjection ||
987 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
988 IdentifierNamespace |= IDNS_Ordinary;
992 enum FriendObjectKind {
993 FOK_None, ///< Not a friend object.
994 FOK_Declared, ///< A friend of a previously-declared entity.
995 FOK_Undeclared ///< A friend of a previously-undeclared entity.
998 /// \brief Determines whether this declaration is the object of a
999 /// friend declaration and, if so, what kind.
1001 /// There is currently no direct way to find the associated FriendDecl.
1002 FriendObjectKind getFriendObjectKind() const {
1004 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1005 if (!mask) return FOK_None;
1006 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1010 /// Specifies that this declaration is a C++ overloaded non-member.
1011 void setNonMemberOperator() {
1012 assert(getKind() == Function || getKind() == FunctionTemplate);
1013 assert((IdentifierNamespace & IDNS_Ordinary) &&
1014 "visible non-member operators should be in ordinary namespace");
1015 IdentifierNamespace |= IDNS_NonMemberOperator;
1018 static bool classofKind(Kind K) { return true; }
1019 static DeclContext *castToDeclContext(const Decl *);
1020 static Decl *castFromDeclContext(const DeclContext *);
1022 void print(raw_ostream &Out, unsigned Indentation = 0,
1023 bool PrintInstantiation = false) const;
1024 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1025 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1026 static void printGroup(Decl** Begin, unsigned NumDecls,
1027 raw_ostream &Out, const PrintingPolicy &Policy,
1028 unsigned Indentation = 0);
1029 // Debuggers don't usually respect default arguments.
1031 // Same as dump(), but forces color printing.
1032 void dumpColor() const;
1033 void dump(raw_ostream &Out) const;
1035 /// \brief Looks through the Decl's underlying type to extract a FunctionType
1036 /// when possible. Will return null if the type underlying the Decl does not
1037 /// have a FunctionType.
1038 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1041 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1042 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1046 ASTMutationListener *getASTMutationListener() const;
1049 /// \brief Determine whether two declarations declare the same entity.
1050 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1057 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1060 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1061 /// doing something to a specific decl.
1062 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1063 const Decl *TheDecl;
1066 const char *Message;
1068 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1069 SourceManager &sm, const char *Msg)
1070 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1072 void print(raw_ostream &OS) const override;
1075 /// \brief The results of name lookup within a DeclContext. This is either a
1076 /// single result (with no stable storage) or a collection of results (with
1077 /// stable storage provided by the lookup table).
1078 class DeclContextLookupResult {
1079 typedef ArrayRef<NamedDecl *> ResultTy;
1081 // If there is only one lookup result, it would be invalidated by
1082 // reallocations of the name table, so store it separately.
1085 static NamedDecl *const SingleElementDummyList;
1088 DeclContextLookupResult() : Result(), Single() {}
1089 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1090 : Result(Result), Single() {}
1091 DeclContextLookupResult(NamedDecl *Single)
1092 : Result(SingleElementDummyList), Single(Single) {}
1095 typedef llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1096 std::random_access_iterator_tag,
1097 NamedDecl *const> IteratorBase;
1098 class iterator : public IteratorBase {
1099 value_type SingleElement;
1102 iterator() : IteratorBase(), SingleElement() {}
1103 explicit iterator(pointer Pos, value_type Single = nullptr)
1104 : IteratorBase(Pos), SingleElement(Single) {}
1106 reference operator*() const {
1107 return SingleElement ? SingleElement : IteratorBase::operator*();
1110 typedef iterator const_iterator;
1111 typedef iterator::pointer pointer;
1112 typedef iterator::reference reference;
1114 iterator begin() const { return iterator(Result.begin(), Single); }
1115 iterator end() const { return iterator(Result.end(), Single); }
1117 bool empty() const { return Result.empty(); }
1118 pointer data() const { return Single ? &Single : Result.data(); }
1119 size_t size() const { return Single ? 1 : Result.size(); }
1120 reference front() const { return Single ? Single : Result.front(); }
1121 reference back() const { return Single ? Single : Result.back(); }
1122 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1124 // FIXME: Remove this from the interface
1125 DeclContextLookupResult slice(size_t N) const {
1126 DeclContextLookupResult Sliced = Result.slice(N);
1127 Sliced.Single = Single;
1132 /// DeclContext - This is used only as base class of specific decl types that
1133 /// can act as declaration contexts. These decls are (only the top classes
1134 /// that directly derive from DeclContext are mentioned, not their subclasses):
1136 /// TranslationUnitDecl
1141 /// ObjCContainerDecl
1145 /// OMPDeclareReductionDecl
1148 /// DeclKind - This indicates which class this is.
1149 unsigned DeclKind : 8;
1151 /// \brief Whether this declaration context also has some external
1152 /// storage that contains additional declarations that are lexically
1153 /// part of this context.
1154 mutable bool ExternalLexicalStorage : 1;
1156 /// \brief Whether this declaration context also has some external
1157 /// storage that contains additional declarations that are visible
1158 /// in this context.
1159 mutable bool ExternalVisibleStorage : 1;
1161 /// \brief Whether this declaration context has had external visible
1162 /// storage added since the last lookup. In this case, \c LookupPtr's
1163 /// invariant may not hold and needs to be fixed before we perform
1165 mutable bool NeedToReconcileExternalVisibleStorage : 1;
1167 /// \brief If \c true, this context may have local lexical declarations
1168 /// that are missing from the lookup table.
1169 mutable bool HasLazyLocalLexicalLookups : 1;
1171 /// \brief If \c true, the external source may have lexical declarations
1172 /// that are missing from the lookup table.
1173 mutable bool HasLazyExternalLexicalLookups : 1;
1175 /// \brief If \c true, lookups should only return identifier from
1176 /// DeclContext scope (for example TranslationUnit). Used in
1177 /// LookupQualifiedName()
1178 mutable bool UseQualifiedLookup : 1;
1180 /// \brief Pointer to the data structure used to lookup declarations
1181 /// within this context (or a DependentStoredDeclsMap if this is a
1182 /// dependent context). We maintain the invariant that, if the map
1183 /// contains an entry for a DeclarationName (and we haven't lazily
1184 /// omitted anything), then it contains all relevant entries for that
1185 /// name (modulo the hasExternalDecls() flag).
1186 mutable StoredDeclsMap *LookupPtr;
1189 /// FirstDecl - The first declaration stored within this declaration
1191 mutable Decl *FirstDecl;
1193 /// LastDecl - The last declaration stored within this declaration
1194 /// context. FIXME: We could probably cache this value somewhere
1195 /// outside of the DeclContext, to reduce the size of DeclContext by
1196 /// another pointer.
1197 mutable Decl *LastDecl;
1199 friend class ExternalASTSource;
1200 friend class ASTDeclReader;
1201 friend class ASTWriter;
1203 /// \brief Build up a chain of declarations.
1205 /// \returns the first/last pair of declarations.
1206 static std::pair<Decl *, Decl *>
1207 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1209 DeclContext(Decl::Kind K)
1210 : DeclKind(K), ExternalLexicalStorage(false),
1211 ExternalVisibleStorage(false),
1212 NeedToReconcileExternalVisibleStorage(false),
1213 HasLazyLocalLexicalLookups(false), HasLazyExternalLexicalLookups(false),
1214 UseQualifiedLookup(false),
1215 LookupPtr(nullptr), FirstDecl(nullptr), LastDecl(nullptr) {}
1220 Decl::Kind getDeclKind() const {
1221 return static_cast<Decl::Kind>(DeclKind);
1223 const char *getDeclKindName() const;
1225 /// getParent - Returns the containing DeclContext.
1226 DeclContext *getParent() {
1227 return cast<Decl>(this)->getDeclContext();
1229 const DeclContext *getParent() const {
1230 return const_cast<DeclContext*>(this)->getParent();
1233 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1234 /// different from getParent, e.g.:
1239 /// struct A::S {}; // getParent() == namespace 'A'
1240 /// // getLexicalParent() == translation unit
1242 DeclContext *getLexicalParent() {
1243 return cast<Decl>(this)->getLexicalDeclContext();
1245 const DeclContext *getLexicalParent() const {
1246 return const_cast<DeclContext*>(this)->getLexicalParent();
1249 DeclContext *getLookupParent();
1251 const DeclContext *getLookupParent() const {
1252 return const_cast<DeclContext*>(this)->getLookupParent();
1255 ASTContext &getParentASTContext() const {
1256 return cast<Decl>(this)->getASTContext();
1259 bool isClosure() const {
1260 return DeclKind == Decl::Block;
1263 bool isObjCContainer() const {
1265 case Decl::ObjCCategory:
1266 case Decl::ObjCCategoryImpl:
1267 case Decl::ObjCImplementation:
1268 case Decl::ObjCInterface:
1269 case Decl::ObjCProtocol:
1275 bool isFunctionOrMethod() const {
1278 case Decl::Captured:
1279 case Decl::ObjCMethod:
1282 return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1286 /// \brief Test whether the context supports looking up names.
1287 bool isLookupContext() const {
1288 return !isFunctionOrMethod() && DeclKind != Decl::LinkageSpec &&
1289 DeclKind != Decl::Export;
1292 bool isFileContext() const {
1293 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1296 bool isTranslationUnit() const {
1297 return DeclKind == Decl::TranslationUnit;
1300 bool isRecord() const {
1301 return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1304 bool isNamespace() const {
1305 return DeclKind == Decl::Namespace;
1308 bool isStdNamespace() const;
1310 bool isInlineNamespace() const;
1312 /// \brief Determines whether this context is dependent on a
1313 /// template parameter.
1314 bool isDependentContext() const;
1316 /// isTransparentContext - Determines whether this context is a
1317 /// "transparent" context, meaning that the members declared in this
1318 /// context are semantically declared in the nearest enclosing
1319 /// non-transparent (opaque) context but are lexically declared in
1320 /// this context. For example, consider the enumerators of an
1321 /// enumeration type:
1327 /// Here, E is a transparent context, so its enumerator (Val1) will
1328 /// appear (semantically) that it is in the same context of E.
1329 /// Examples of transparent contexts include: enumerations (except for
1330 /// C++0x scoped enums), and C++ linkage specifications.
1331 bool isTransparentContext() const;
1333 /// \brief Determines whether this context or some of its ancestors is a
1334 /// linkage specification context that specifies C linkage.
1335 bool isExternCContext() const;
1337 /// \brief Retrieve the nearest enclosing C linkage specification context.
1338 const LinkageSpecDecl *getExternCContext() const;
1340 /// \brief Determines whether this context or some of its ancestors is a
1341 /// linkage specification context that specifies C++ linkage.
1342 bool isExternCXXContext() const;
1344 /// \brief Determine whether this declaration context is equivalent
1345 /// to the declaration context DC.
1346 bool Equals(const DeclContext *DC) const {
1347 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1350 /// \brief Determine whether this declaration context encloses the
1351 /// declaration context DC.
1352 bool Encloses(const DeclContext *DC) const;
1354 /// \brief Find the nearest non-closure ancestor of this context,
1355 /// i.e. the innermost semantic parent of this context which is not
1356 /// a closure. A context may be its own non-closure ancestor.
1357 Decl *getNonClosureAncestor();
1358 const Decl *getNonClosureAncestor() const {
1359 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1362 /// getPrimaryContext - There may be many different
1363 /// declarations of the same entity (including forward declarations
1364 /// of classes, multiple definitions of namespaces, etc.), each with
1365 /// a different set of declarations. This routine returns the
1366 /// "primary" DeclContext structure, which will contain the
1367 /// information needed to perform name lookup into this context.
1368 DeclContext *getPrimaryContext();
1369 const DeclContext *getPrimaryContext() const {
1370 return const_cast<DeclContext*>(this)->getPrimaryContext();
1373 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1374 /// other entities of the same name, or where it is a redeclaration if the
1375 /// two entities are compatible. This skips through transparent contexts.
1376 DeclContext *getRedeclContext();
1377 const DeclContext *getRedeclContext() const {
1378 return const_cast<DeclContext *>(this)->getRedeclContext();
1381 /// \brief Retrieve the nearest enclosing namespace context.
1382 DeclContext *getEnclosingNamespaceContext();
1383 const DeclContext *getEnclosingNamespaceContext() const {
1384 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1387 /// \brief Retrieve the outermost lexically enclosing record context.
1388 RecordDecl *getOuterLexicalRecordContext();
1389 const RecordDecl *getOuterLexicalRecordContext() const {
1390 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1393 /// \brief Test if this context is part of the enclosing namespace set of
1394 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1395 /// isn't a namespace, this is equivalent to Equals().
1397 /// The enclosing namespace set of a namespace is the namespace and, if it is
1398 /// inline, its enclosing namespace, recursively.
1399 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1401 /// \brief Collects all of the declaration contexts that are semantically
1402 /// connected to this declaration context.
1404 /// For declaration contexts that have multiple semantically connected but
1405 /// syntactically distinct contexts, such as C++ namespaces, this routine
1406 /// retrieves the complete set of such declaration contexts in source order.
1407 /// For example, given:
1418 /// The \c Contexts parameter will contain both definitions of N.
1420 /// \param Contexts Will be cleared and set to the set of declaration
1421 /// contexts that are semanticaly connected to this declaration context,
1422 /// in source order, including this context (which may be the only result,
1423 /// for non-namespace contexts).
1424 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1426 /// decl_iterator - Iterates through the declarations stored
1427 /// within this context.
1428 class decl_iterator {
1429 /// Current - The current declaration.
1433 typedef Decl *value_type;
1434 typedef const value_type &reference;
1435 typedef const value_type *pointer;
1436 typedef std::forward_iterator_tag iterator_category;
1437 typedef std::ptrdiff_t difference_type;
1439 decl_iterator() : Current(nullptr) { }
1440 explicit decl_iterator(Decl *C) : Current(C) { }
1442 reference operator*() const { return Current; }
1443 // This doesn't meet the iterator requirements, but it's convenient
1444 value_type operator->() const { return Current; }
1446 decl_iterator& operator++() {
1447 Current = Current->getNextDeclInContext();
1451 decl_iterator operator++(int) {
1452 decl_iterator tmp(*this);
1457 friend bool operator==(decl_iterator x, decl_iterator y) {
1458 return x.Current == y.Current;
1460 friend bool operator!=(decl_iterator x, decl_iterator y) {
1461 return x.Current != y.Current;
1465 typedef llvm::iterator_range<decl_iterator> decl_range;
1467 /// decls_begin/decls_end - Iterate over the declarations stored in
1469 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
1470 decl_iterator decls_begin() const;
1471 decl_iterator decls_end() const { return decl_iterator(); }
1472 bool decls_empty() const;
1474 /// noload_decls_begin/end - Iterate over the declarations stored in this
1475 /// context that are currently loaded; don't attempt to retrieve anything
1476 /// from an external source.
1477 decl_range noload_decls() const {
1478 return decl_range(noload_decls_begin(), noload_decls_end());
1480 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
1481 decl_iterator noload_decls_end() const { return decl_iterator(); }
1483 /// specific_decl_iterator - Iterates over a subrange of
1484 /// declarations stored in a DeclContext, providing only those that
1485 /// are of type SpecificDecl (or a class derived from it). This
1486 /// iterator is used, for example, to provide iteration over just
1487 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1488 template<typename SpecificDecl>
1489 class specific_decl_iterator {
1490 /// Current - The current, underlying declaration iterator, which
1491 /// will either be NULL or will point to a declaration of
1492 /// type SpecificDecl.
1493 DeclContext::decl_iterator Current;
1495 /// SkipToNextDecl - Advances the current position up to the next
1496 /// declaration of type SpecificDecl that also meets the criteria
1497 /// required by Acceptable.
1498 void SkipToNextDecl() {
1499 while (*Current && !isa<SpecificDecl>(*Current))
1504 typedef SpecificDecl *value_type;
1505 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1506 // type) if we ever have a need for them.
1507 typedef void reference;
1508 typedef void pointer;
1509 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1511 typedef std::forward_iterator_tag iterator_category;
1513 specific_decl_iterator() : Current() { }
1515 /// specific_decl_iterator - Construct a new iterator over a
1516 /// subset of the declarations the range [C,
1517 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1518 /// member function of SpecificDecl that should return true for
1519 /// all of the SpecificDecl instances that will be in the subset
1520 /// of iterators. For example, if you want Objective-C instance
1521 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1522 /// &ObjCMethodDecl::isInstanceMethod.
1523 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1527 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1528 // This doesn't meet the iterator requirements, but it's convenient
1529 value_type operator->() const { return **this; }
1531 specific_decl_iterator& operator++() {
1537 specific_decl_iterator operator++(int) {
1538 specific_decl_iterator tmp(*this);
1543 friend bool operator==(const specific_decl_iterator& x,
1544 const specific_decl_iterator& y) {
1545 return x.Current == y.Current;
1548 friend bool operator!=(const specific_decl_iterator& x,
1549 const specific_decl_iterator& y) {
1550 return x.Current != y.Current;
1554 /// \brief Iterates over a filtered subrange of declarations stored
1555 /// in a DeclContext.
1557 /// This iterator visits only those declarations that are of type
1558 /// SpecificDecl (or a class derived from it) and that meet some
1559 /// additional run-time criteria. This iterator is used, for
1560 /// example, to provide access to the instance methods within an
1561 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1562 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1563 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1564 class filtered_decl_iterator {
1565 /// Current - The current, underlying declaration iterator, which
1566 /// will either be NULL or will point to a declaration of
1567 /// type SpecificDecl.
1568 DeclContext::decl_iterator Current;
1570 /// SkipToNextDecl - Advances the current position up to the next
1571 /// declaration of type SpecificDecl that also meets the criteria
1572 /// required by Acceptable.
1573 void SkipToNextDecl() {
1575 (!isa<SpecificDecl>(*Current) ||
1576 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1581 typedef SpecificDecl *value_type;
1582 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1583 // type) if we ever have a need for them.
1584 typedef void reference;
1585 typedef void pointer;
1586 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1588 typedef std::forward_iterator_tag iterator_category;
1590 filtered_decl_iterator() : Current() { }
1592 /// filtered_decl_iterator - Construct a new iterator over a
1593 /// subset of the declarations the range [C,
1594 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1595 /// member function of SpecificDecl that should return true for
1596 /// all of the SpecificDecl instances that will be in the subset
1597 /// of iterators. For example, if you want Objective-C instance
1598 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1599 /// &ObjCMethodDecl::isInstanceMethod.
1600 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1604 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1605 value_type operator->() const { return cast<SpecificDecl>(*Current); }
1607 filtered_decl_iterator& operator++() {
1613 filtered_decl_iterator operator++(int) {
1614 filtered_decl_iterator tmp(*this);
1619 friend bool operator==(const filtered_decl_iterator& x,
1620 const filtered_decl_iterator& y) {
1621 return x.Current == y.Current;
1624 friend bool operator!=(const filtered_decl_iterator& x,
1625 const filtered_decl_iterator& y) {
1626 return x.Current != y.Current;
1630 /// @brief Add the declaration D into this context.
1632 /// This routine should be invoked when the declaration D has first
1633 /// been declared, to place D into the context where it was
1634 /// (lexically) defined. Every declaration must be added to one
1635 /// (and only one!) context, where it can be visited via
1636 /// [decls_begin(), decls_end()). Once a declaration has been added
1637 /// to its lexical context, the corresponding DeclContext owns the
1640 /// If D is also a NamedDecl, it will be made visible within its
1641 /// semantic context via makeDeclVisibleInContext.
1642 void addDecl(Decl *D);
1644 /// @brief Add the declaration D into this context, but suppress
1645 /// searches for external declarations with the same name.
1647 /// Although analogous in function to addDecl, this removes an
1648 /// important check. This is only useful if the Decl is being
1649 /// added in response to an external search; in all other cases,
1650 /// addDecl() is the right function to use.
1651 /// See the ASTImporter for use cases.
1652 void addDeclInternal(Decl *D);
1654 /// @brief Add the declaration D to this context without modifying
1655 /// any lookup tables.
1657 /// This is useful for some operations in dependent contexts where
1658 /// the semantic context might not be dependent; this basically
1659 /// only happens with friends.
1660 void addHiddenDecl(Decl *D);
1662 /// @brief Removes a declaration from this context.
1663 void removeDecl(Decl *D);
1665 /// @brief Checks whether a declaration is in this context.
1666 bool containsDecl(Decl *D) const;
1668 typedef DeclContextLookupResult lookup_result;
1669 typedef lookup_result::iterator lookup_iterator;
1671 /// lookup - Find the declarations (if any) with the given Name in
1672 /// this context. Returns a range of iterators that contains all of
1673 /// the declarations with this name, with object, function, member,
1674 /// and enumerator names preceding any tag name. Note that this
1675 /// routine will not look into parent contexts.
1676 lookup_result lookup(DeclarationName Name) const;
1678 /// \brief Find the declarations with the given name that are visible
1679 /// within this context; don't attempt to retrieve anything from an
1680 /// external source.
1681 lookup_result noload_lookup(DeclarationName Name);
1683 /// \brief A simplistic name lookup mechanism that performs name lookup
1684 /// into this declaration context without consulting the external source.
1686 /// This function should almost never be used, because it subverts the
1687 /// usual relationship between a DeclContext and the external source.
1688 /// See the ASTImporter for the (few, but important) use cases.
1690 /// FIXME: This is very inefficient; replace uses of it with uses of
1692 void localUncachedLookup(DeclarationName Name,
1693 SmallVectorImpl<NamedDecl *> &Results);
1695 /// @brief Makes a declaration visible within this context.
1697 /// This routine makes the declaration D visible to name lookup
1698 /// within this context and, if this is a transparent context,
1699 /// within its parent contexts up to the first enclosing
1700 /// non-transparent context. Making a declaration visible within a
1701 /// context does not transfer ownership of a declaration, and a
1702 /// declaration can be visible in many contexts that aren't its
1703 /// lexical context.
1705 /// If D is a redeclaration of an existing declaration that is
1706 /// visible from this context, as determined by
1707 /// NamedDecl::declarationReplaces, the previous declaration will be
1708 /// replaced with D.
1709 void makeDeclVisibleInContext(NamedDecl *D);
1711 /// all_lookups_iterator - An iterator that provides a view over the results
1712 /// of looking up every possible name.
1713 class all_lookups_iterator;
1715 typedef llvm::iterator_range<all_lookups_iterator> lookups_range;
1717 lookups_range lookups() const;
1718 lookups_range noload_lookups() const;
1720 /// \brief Iterators over all possible lookups within this context.
1721 all_lookups_iterator lookups_begin() const;
1722 all_lookups_iterator lookups_end() const;
1724 /// \brief Iterators over all possible lookups within this context that are
1725 /// currently loaded; don't attempt to retrieve anything from an external
1727 all_lookups_iterator noload_lookups_begin() const;
1728 all_lookups_iterator noload_lookups_end() const;
1730 struct udir_iterator;
1731 typedef llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
1732 std::random_access_iterator_tag,
1733 UsingDirectiveDecl *> udir_iterator_base;
1734 struct udir_iterator : udir_iterator_base {
1735 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
1736 UsingDirectiveDecl *operator*() const;
1739 typedef llvm::iterator_range<udir_iterator> udir_range;
1741 udir_range using_directives() const;
1743 // These are all defined in DependentDiagnostic.h.
1744 class ddiag_iterator;
1745 typedef llvm::iterator_range<DeclContext::ddiag_iterator> ddiag_range;
1747 inline ddiag_range ddiags() const;
1749 // Low-level accessors
1751 /// \brief Mark that there are external lexical declarations that we need
1752 /// to include in our lookup table (and that are not available as external
1753 /// visible lookups). These extra lookup results will be found by walking
1754 /// the lexical declarations of this context. This should be used only if
1755 /// setHasExternalLexicalStorage() has been called on any decl context for
1756 /// which this is the primary context.
1757 void setMustBuildLookupTable() {
1758 assert(this == getPrimaryContext() &&
1759 "should only be called on primary context");
1760 HasLazyExternalLexicalLookups = true;
1763 /// \brief Retrieve the internal representation of the lookup structure.
1764 /// This may omit some names if we are lazily building the structure.
1765 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
1767 /// \brief Ensure the lookup structure is fully-built and return it.
1768 StoredDeclsMap *buildLookup();
1770 /// \brief Whether this DeclContext has external storage containing
1771 /// additional declarations that are lexically in this context.
1772 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1774 /// \brief State whether this DeclContext has external storage for
1775 /// declarations lexically in this context.
1776 void setHasExternalLexicalStorage(bool ES = true) {
1777 ExternalLexicalStorage = ES;
1780 /// \brief Whether this DeclContext has external storage containing
1781 /// additional declarations that are visible in this context.
1782 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1784 /// \brief State whether this DeclContext has external storage for
1785 /// declarations visible in this context.
1786 void setHasExternalVisibleStorage(bool ES = true) {
1787 ExternalVisibleStorage = ES;
1788 if (ES && LookupPtr)
1789 NeedToReconcileExternalVisibleStorage = true;
1792 /// \brief Determine whether the given declaration is stored in the list of
1793 /// declarations lexically within this context.
1794 bool isDeclInLexicalTraversal(const Decl *D) const {
1795 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1799 bool setUseQualifiedLookup(bool use = true) {
1800 bool old_value = UseQualifiedLookup;
1801 UseQualifiedLookup = use;
1805 bool shouldUseQualifiedLookup() const {
1806 return UseQualifiedLookup;
1809 static bool classof(const Decl *D);
1810 static bool classof(const DeclContext *D) { return true; }
1812 void dumpDeclContext() const;
1813 void dumpLookups() const;
1814 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false) const;
1817 void reconcileExternalVisibleStorage() const;
1818 bool LoadLexicalDeclsFromExternalStorage() const;
1820 /// @brief Makes a declaration visible within this context, but
1821 /// suppresses searches for external declarations with the same
1824 /// Analogous to makeDeclVisibleInContext, but for the exclusive
1825 /// use of addDeclInternal().
1826 void makeDeclVisibleInContextInternal(NamedDecl *D);
1828 friend class DependentDiagnostic;
1829 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1831 void buildLookupImpl(DeclContext *DCtx, bool Internal);
1832 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1833 bool Rediscoverable);
1834 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1837 inline bool Decl::isTemplateParameter() const {
1838 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1839 getKind() == TemplateTemplateParm;
1842 // Specialization selected when ToTy is not a known subclass of DeclContext.
1843 template <class ToTy,
1844 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
1845 struct cast_convert_decl_context {
1846 static const ToTy *doit(const DeclContext *Val) {
1847 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1850 static ToTy *doit(DeclContext *Val) {
1851 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1855 // Specialization selected when ToTy is a known subclass of DeclContext.
1856 template <class ToTy>
1857 struct cast_convert_decl_context<ToTy, true> {
1858 static const ToTy *doit(const DeclContext *Val) {
1859 return static_cast<const ToTy*>(Val);
1862 static ToTy *doit(DeclContext *Val) {
1863 return static_cast<ToTy*>(Val);
1872 /// isa<T>(DeclContext*)
1873 template <typename To>
1874 struct isa_impl<To, ::clang::DeclContext> {
1875 static bool doit(const ::clang::DeclContext &Val) {
1876 return To::classofKind(Val.getDeclKind());
1880 /// cast<T>(DeclContext*)
1881 template<class ToTy>
1882 struct cast_convert_val<ToTy,
1883 const ::clang::DeclContext,const ::clang::DeclContext> {
1884 static const ToTy &doit(const ::clang::DeclContext &Val) {
1885 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1888 template<class ToTy>
1889 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
1890 static ToTy &doit(::clang::DeclContext &Val) {
1891 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1894 template<class ToTy>
1895 struct cast_convert_val<ToTy,
1896 const ::clang::DeclContext*, const ::clang::DeclContext*> {
1897 static const ToTy *doit(const ::clang::DeclContext *Val) {
1898 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1901 template<class ToTy>
1902 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
1903 static ToTy *doit(::clang::DeclContext *Val) {
1904 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1908 /// Implement cast_convert_val for Decl -> DeclContext conversions.
1909 template<class FromTy>
1910 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1911 static ::clang::DeclContext &doit(const FromTy &Val) {
1912 return *FromTy::castToDeclContext(&Val);
1916 template<class FromTy>
1917 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1918 static ::clang::DeclContext *doit(const FromTy *Val) {
1919 return FromTy::castToDeclContext(Val);
1923 template<class FromTy>
1924 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1925 static const ::clang::DeclContext &doit(const FromTy &Val) {
1926 return *FromTy::castToDeclContext(&Val);
1930 template<class FromTy>
1931 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1932 static const ::clang::DeclContext *doit(const FromTy *Val) {
1933 return FromTy::castToDeclContext(Val);
1937 } // end namespace llvm