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/LLVM.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Basic/Specifiers.h"
22 #include "clang/Basic/VersionTuple.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/PointerIntPair.h"
25 #include "llvm/ADT/PointerUnion.h"
26 #include "llvm/ADT/iterator.h"
27 #include "llvm/ADT/iterator_range.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/PrettyStackTrace.h"
36 #include <type_traits>
42 class ASTMutationListener;
45 class ExternalSourceSymbolAttr;
49 enum Linkage : unsigned char;
50 class LinkageSpecDecl;
53 class ObjCCategoryDecl;
54 class ObjCCategoryImplDecl;
55 class ObjCContainerDecl;
57 class ObjCImplementationDecl;
58 class ObjCInterfaceDecl;
60 class ObjCProtocolDecl;
61 struct PrintingPolicy;
67 class TranslationUnitDecl;
68 class UsingDirectiveDecl;
70 /// \brief Captures the result of checking the availability of a
72 enum AvailabilityResult {
79 /// Decl - This represents one declaration (or definition), e.g. a variable,
80 /// typedef, function, struct, etc.
82 /// Note: There are objects tacked on before the *beginning* of Decl
83 /// (and its subclasses) in its Decl::operator new(). Proper alignment
84 /// of all subclasses (not requiring more than the alignment of Decl) is
85 /// asserted in DeclBase.cpp.
86 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) Decl {
88 /// \brief Lists the kind of concrete classes of Decl.
90 #define DECL(DERIVED, BASE) DERIVED,
91 #define ABSTRACT_DECL(DECL)
92 #define DECL_RANGE(BASE, START, END) \
93 first##BASE = START, last##BASE = END,
94 #define LAST_DECL_RANGE(BASE, START, END) \
95 first##BASE = START, last##BASE = END
96 #include "clang/AST/DeclNodes.inc"
99 /// \brief A placeholder type used to construct an empty shell of a
100 /// decl-derived type that will be filled in later (e.g., by some
101 /// deserialization method).
102 struct EmptyShell {};
104 /// IdentifierNamespace - The different namespaces in which
105 /// declarations may appear. According to C99 6.2.3, there are
106 /// four namespaces, labels, tags, members and ordinary
107 /// identifiers. C++ describes lookup completely differently:
108 /// certain lookups merely "ignore" certain kinds of declarations,
109 /// usually based on whether the declaration is of a type, etc.
111 /// These are meant as bitmasks, so that searches in
112 /// C++ can look into the "tag" namespace during ordinary lookup.
114 /// Decl currently provides 15 bits of IDNS bits.
115 enum IdentifierNamespace {
116 /// Labels, declared with 'x:' and referenced with 'goto x'.
119 /// Tags, declared with 'struct foo;' and referenced with
120 /// 'struct foo'. All tags are also types. This is what
121 /// elaborated-type-specifiers look for in C.
122 /// This also contains names that conflict with tags in the
123 /// same scope but that are otherwise ordinary names (non-type
124 /// template parameters and indirect field declarations).
127 /// Types, declared with 'struct foo', typedefs, etc.
128 /// This is what elaborated-type-specifiers look for in C++,
129 /// but note that it's ill-formed to find a non-tag.
132 /// Members, declared with object declarations within tag
133 /// definitions. In C, these can only be found by "qualified"
134 /// lookup in member expressions. In C++, they're found by
136 IDNS_Member = 0x0008,
138 /// Namespaces, declared with 'namespace foo {}'.
139 /// Lookup for nested-name-specifiers find these.
140 IDNS_Namespace = 0x0010,
142 /// Ordinary names. In C, everything that's not a label, tag,
143 /// member, or function-local extern ends up here.
144 IDNS_Ordinary = 0x0020,
146 /// Objective C \@protocol.
147 IDNS_ObjCProtocol = 0x0040,
149 /// This declaration is a friend function. A friend function
150 /// declaration is always in this namespace but may also be in
151 /// IDNS_Ordinary if it was previously declared.
152 IDNS_OrdinaryFriend = 0x0080,
154 /// This declaration is a friend class. A friend class
155 /// declaration is always in this namespace but may also be in
156 /// IDNS_Tag|IDNS_Type if it was previously declared.
157 IDNS_TagFriend = 0x0100,
159 /// This declaration is a using declaration. A using declaration
160 /// *introduces* a number of other declarations into the current
161 /// scope, and those declarations use the IDNS of their targets,
162 /// but the actual using declarations go in this namespace.
165 /// This declaration is a C++ operator declared in a non-class
166 /// context. All such operators are also in IDNS_Ordinary.
167 /// C++ lexical operator lookup looks for these.
168 IDNS_NonMemberOperator = 0x0400,
170 /// This declaration is a function-local extern declaration of a
171 /// variable or function. This may also be IDNS_Ordinary if it
172 /// has been declared outside any function. These act mostly like
173 /// invisible friend declarations, but are also visible to unqualified
174 /// lookup within the scope of the declaring function.
175 IDNS_LocalExtern = 0x0800,
177 /// This declaration is an OpenMP user defined reduction construction.
178 IDNS_OMPReduction = 0x1000
181 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
182 /// parameter types in method declarations. Other than remembering
183 /// them and mangling them into the method's signature string, these
184 /// are ignored by the compiler; they are consumed by certain
185 /// remote-messaging frameworks.
187 /// in, inout, and out are mutually exclusive and apply only to
188 /// method parameters. bycopy and byref are mutually exclusive and
189 /// apply only to method parameters (?). oneway applies only to
190 /// results. All of these expect their corresponding parameter to
191 /// have a particular type. None of this is currently enforced by
194 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
195 enum ObjCDeclQualifier {
200 OBJC_TQ_Bycopy = 0x8,
201 OBJC_TQ_Byref = 0x10,
202 OBJC_TQ_Oneway = 0x20,
204 /// The nullability qualifier is set when the nullability of the
205 /// result or parameter was expressed via a context-sensitive
207 OBJC_TQ_CSNullability = 0x40
210 /// The kind of ownership a declaration has, for visibility purposes.
211 /// This enumeration is designed such that higher values represent higher
212 /// levels of name hiding.
213 enum class ModuleOwnershipKind : unsigned {
214 /// This declaration is not owned by a module.
217 /// This declaration has an owning module, but is globally visible
218 /// (typically because its owning module is visible and we know that
219 /// modules cannot later become hidden in this compilation).
220 /// After serialization and deserialization, this will be converted
221 /// to VisibleWhenImported.
224 /// This declaration has an owning module, and is visible when that
225 /// module is imported.
228 /// This declaration has an owning module, but is only visible to
229 /// lookups that occur within that module.
234 /// \brief The next declaration within the same lexical
235 /// DeclContext. These pointers form the linked list that is
236 /// traversed via DeclContext's decls_begin()/decls_end().
238 /// The extra two bits are used for the ModuleOwnershipKind.
239 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
242 friend class DeclContext;
245 DeclContext *SemanticDC;
246 DeclContext *LexicalDC;
249 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
250 /// For declarations that don't contain C++ scope specifiers, it contains
251 /// the DeclContext where the Decl was declared.
252 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
253 /// with the context where it semantically belongs (SemanticDC) and the
254 /// context where it was lexically declared (LexicalDC).
258 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
260 /// void A::f(); // SemanticDC == namespace 'A'
261 /// // LexicalDC == global namespace
262 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
264 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
265 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
267 MultipleDC *getMultipleDC() const {
268 return DeclCtx.get<MultipleDC*>();
271 DeclContext *getSemanticDC() const {
272 return DeclCtx.get<DeclContext*>();
275 /// Loc - The location of this decl.
278 /// DeclKind - This indicates which class this is.
279 unsigned DeclKind : 7;
281 /// InvalidDecl - This indicates a semantic error occurred.
282 unsigned InvalidDecl : 1;
284 /// HasAttrs - This indicates whether the decl has attributes or not.
285 unsigned HasAttrs : 1;
287 /// Implicit - Whether this declaration was implicitly generated by
288 /// the implementation rather than explicitly written by the user.
289 unsigned Implicit : 1;
291 /// \brief Whether this declaration was "used", meaning that a definition is
295 /// \brief Whether this declaration was "referenced".
296 /// The difference with 'Used' is whether the reference appears in a
297 /// evaluated context or not, e.g. functions used in uninstantiated templates
298 /// are regarded as "referenced" but not "used".
299 unsigned Referenced : 1;
301 /// \brief Whether this declaration is a top-level declaration (function,
302 /// global variable, etc.) that is lexically inside an objc container
304 unsigned TopLevelDeclInObjCContainer : 1;
306 /// \brief Whether statistic collection is enabled.
307 static bool StatisticsEnabled;
310 friend class ASTDeclReader;
311 friend class ASTDeclWriter;
312 friend class ASTReader;
313 friend class CXXClassMemberWrapper;
314 friend class LinkageComputer;
315 template<typename decl_type> friend class Redeclarable;
317 /// Access - Used by C++ decls for the access specifier.
318 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
321 /// \brief Whether this declaration was loaded from an AST file.
322 unsigned FromASTFile : 1;
324 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
325 unsigned IdentifierNamespace : 13;
327 /// \brief If 0, we have not computed the linkage of this declaration.
328 /// Otherwise, it is the linkage + 1.
329 mutable unsigned CacheValidAndLinkage : 3;
331 /// \brief Allocate memory for a deserialized declaration.
333 /// This routine must be used to allocate memory for any declaration that is
334 /// deserialized from a module file.
336 /// \param Size The size of the allocated object.
337 /// \param Ctx The context in which we will allocate memory.
338 /// \param ID The global ID of the deserialized declaration.
339 /// \param Extra The amount of extra space to allocate after the object.
340 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
341 std::size_t Extra = 0);
343 /// \brief Allocate memory for a non-deserialized declaration.
344 void *operator new(std::size_t Size, const ASTContext &Ctx,
345 DeclContext *Parent, std::size_t Extra = 0);
348 bool AccessDeclContextSanity() const;
350 /// Get the module ownership kind to use for a local lexical child of \p DC,
351 /// which may be either a local or (rarely) an imported declaration.
352 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
354 auto *D = cast<Decl>(DC);
355 auto MOK = D->getModuleOwnershipKind();
356 if (MOK != ModuleOwnershipKind::Unowned &&
357 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
359 // If D is not local and we have no local module storage, then we don't
360 // need to track module ownership at all.
362 return ModuleOwnershipKind::Unowned;
366 Decl(Kind DK, DeclContext *DC, SourceLocation L)
367 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
368 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
369 Implicit(false), Used(false), Referenced(false),
370 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
371 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
372 CacheValidAndLinkage(0) {
373 if (StatisticsEnabled) add(DK);
376 Decl(Kind DK, EmptyShell Empty)
377 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
378 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
379 Access(AS_none), FromASTFile(0),
380 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
381 CacheValidAndLinkage(0) {
382 if (StatisticsEnabled) add(DK);
387 /// \brief Update a potentially out-of-date declaration.
388 void updateOutOfDate(IdentifierInfo &II) const;
390 Linkage getCachedLinkage() const {
391 return Linkage(CacheValidAndLinkage - 1);
394 void setCachedLinkage(Linkage L) const {
395 CacheValidAndLinkage = L + 1;
398 bool hasCachedLinkage() const {
399 return CacheValidAndLinkage;
403 /// \brief Source range that this declaration covers.
404 virtual SourceRange getSourceRange() const LLVM_READONLY {
405 return SourceRange(getLocation(), getLocation());
408 SourceLocation getLocStart() const LLVM_READONLY {
409 return getSourceRange().getBegin();
412 SourceLocation getLocEnd() const LLVM_READONLY {
413 return getSourceRange().getEnd();
416 SourceLocation getLocation() const { return Loc; }
417 void setLocation(SourceLocation L) { Loc = L; }
419 Kind getKind() const { return static_cast<Kind>(DeclKind); }
420 const char *getDeclKindName() const;
422 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
423 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
425 DeclContext *getDeclContext() {
427 return getSemanticDC();
428 return getMultipleDC()->SemanticDC;
430 const DeclContext *getDeclContext() const {
431 return const_cast<Decl*>(this)->getDeclContext();
434 /// Find the innermost non-closure ancestor of this declaration,
435 /// walking up through blocks, lambdas, etc. If that ancestor is
436 /// not a code context (!isFunctionOrMethod()), returns null.
438 /// A declaration may be its own non-closure context.
439 Decl *getNonClosureContext();
440 const Decl *getNonClosureContext() const {
441 return const_cast<Decl*>(this)->getNonClosureContext();
444 TranslationUnitDecl *getTranslationUnitDecl();
445 const TranslationUnitDecl *getTranslationUnitDecl() const {
446 return const_cast<Decl*>(this)->getTranslationUnitDecl();
449 bool isInAnonymousNamespace() const;
451 bool isInStdNamespace() const;
453 ASTContext &getASTContext() const LLVM_READONLY;
455 void setAccess(AccessSpecifier AS) {
457 assert(AccessDeclContextSanity());
460 AccessSpecifier getAccess() const {
461 assert(AccessDeclContextSanity());
462 return AccessSpecifier(Access);
465 /// \brief Retrieve the access specifier for this declaration, even though
466 /// it may not yet have been properly set.
467 AccessSpecifier getAccessUnsafe() const {
468 return AccessSpecifier(Access);
471 bool hasAttrs() const { return HasAttrs; }
473 void setAttrs(const AttrVec& Attrs) {
474 return setAttrsImpl(Attrs, getASTContext());
477 AttrVec &getAttrs() {
478 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
481 const AttrVec &getAttrs() const;
484 void addAttr(Attr *A) {
486 getAttrs().push_back(A);
488 setAttrs(AttrVec(1, A));
491 using attr_iterator = AttrVec::const_iterator;
492 using attr_range = llvm::iterator_range<attr_iterator>;
494 attr_range attrs() const {
495 return attr_range(attr_begin(), attr_end());
498 attr_iterator attr_begin() const {
499 return hasAttrs() ? getAttrs().begin() : nullptr;
501 attr_iterator attr_end() const {
502 return hasAttrs() ? getAttrs().end() : nullptr;
505 template <typename T>
507 if (!HasAttrs) return;
509 AttrVec &Vec = getAttrs();
510 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
516 template <typename T>
517 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
518 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
521 template <typename T>
522 specific_attr_iterator<T> specific_attr_begin() const {
523 return specific_attr_iterator<T>(attr_begin());
526 template <typename T>
527 specific_attr_iterator<T> specific_attr_end() const {
528 return specific_attr_iterator<T>(attr_end());
531 template<typename T> T *getAttr() const {
532 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
535 template<typename T> bool hasAttr() const {
536 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
539 /// getMaxAlignment - return the maximum alignment specified by attributes
540 /// on this decl, 0 if there are none.
541 unsigned getMaxAlignment() const;
543 /// setInvalidDecl - Indicates the Decl had a semantic error. This
544 /// allows for graceful error recovery.
545 void setInvalidDecl(bool Invalid = true);
546 bool isInvalidDecl() const { return (bool) InvalidDecl; }
548 /// isImplicit - Indicates whether the declaration was implicitly
549 /// generated by the implementation. If false, this declaration
550 /// was written explicitly in the source code.
551 bool isImplicit() const { return Implicit; }
552 void setImplicit(bool I = true) { Implicit = I; }
554 /// \brief Whether *any* (re-)declaration of the entity was used, meaning that
555 /// a definition is required.
557 /// \param CheckUsedAttr When true, also consider the "used" attribute
558 /// (in addition to the "used" bit set by \c setUsed()) when determining
559 /// whether the function is used.
560 bool isUsed(bool CheckUsedAttr = true) const;
562 /// \brief Set whether the declaration is used, in the sense of odr-use.
564 /// This should only be used immediately after creating a declaration.
565 /// It intentionally doesn't notify any listeners.
566 void setIsUsed() { getCanonicalDecl()->Used = true; }
568 /// \brief Mark the declaration used, in the sense of odr-use.
570 /// This notifies any mutation listeners in addition to setting a bit
571 /// indicating the declaration is used.
572 void markUsed(ASTContext &C);
574 /// \brief Whether any declaration of this entity was referenced.
575 bool isReferenced() const;
577 /// \brief Whether this declaration was referenced. This should not be relied
578 /// upon for anything other than debugging.
579 bool isThisDeclarationReferenced() const { return Referenced; }
581 void setReferenced(bool R = true) { Referenced = R; }
583 /// \brief Whether this declaration is a top-level declaration (function,
584 /// global variable, etc.) that is lexically inside an objc container
586 bool isTopLevelDeclInObjCContainer() const {
587 return TopLevelDeclInObjCContainer;
590 void setTopLevelDeclInObjCContainer(bool V = true) {
591 TopLevelDeclInObjCContainer = V;
594 /// \brief Looks on this and related declarations for an applicable
595 /// external source symbol attribute.
596 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
598 /// \brief Whether this declaration was marked as being private to the
599 /// module in which it was defined.
600 bool isModulePrivate() const {
601 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
604 /// \brief Whether this declaration is exported (by virtue of being lexically
605 /// within an ExportDecl or by being a NamespaceDecl).
606 bool isExported() const;
608 /// Return true if this declaration has an attribute which acts as
609 /// definition of the entity, such as 'alias' or 'ifunc'.
610 bool hasDefiningAttr() const;
612 /// Return this declaration's defining attribute if it has one.
613 const Attr *getDefiningAttr() const;
616 /// \brief Specify that this declaration was marked as being private
617 /// to the module in which it was defined.
618 void setModulePrivate() {
619 // The module-private specifier has no effect on unowned declarations.
620 // FIXME: We should track this in some way for source fidelity.
621 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
623 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
626 /// \brief Set the owning module ID.
627 void setOwningModuleID(unsigned ID) {
628 assert(isFromASTFile() && "Only works on a deserialized declaration");
629 *((unsigned*)this - 2) = ID;
633 /// \brief Determine the availability of the given declaration.
635 /// This routine will determine the most restrictive availability of
636 /// the given declaration (e.g., preferring 'unavailable' to
639 /// \param Message If non-NULL and the result is not \c
640 /// AR_Available, will be set to a (possibly empty) message
641 /// describing why the declaration has not been introduced, is
642 /// deprecated, or is unavailable.
644 /// \param EnclosingVersion The version to compare with. If empty, assume the
645 /// deployment target version.
647 getAvailability(std::string *Message = nullptr,
648 VersionTuple EnclosingVersion = VersionTuple()) const;
650 /// \brief Retrieve the version of the target platform in which this
651 /// declaration was introduced.
653 /// \returns An empty version tuple if this declaration has no 'introduced'
654 /// availability attributes, or the version tuple that's specified in the
655 /// attribute otherwise.
656 VersionTuple getVersionIntroduced() const;
658 /// \brief Determine whether this declaration is marked 'deprecated'.
660 /// \param Message If non-NULL and the declaration is deprecated,
661 /// this will be set to the message describing why the declaration
662 /// was deprecated (which may be empty).
663 bool isDeprecated(std::string *Message = nullptr) const {
664 return getAvailability(Message) == AR_Deprecated;
667 /// \brief Determine whether this declaration is marked 'unavailable'.
669 /// \param Message If non-NULL and the declaration is unavailable,
670 /// this will be set to the message describing why the declaration
671 /// was made unavailable (which may be empty).
672 bool isUnavailable(std::string *Message = nullptr) const {
673 return getAvailability(Message) == AR_Unavailable;
676 /// \brief Determine whether this is a weak-imported symbol.
678 /// Weak-imported symbols are typically marked with the
679 /// 'weak_import' attribute, but may also be marked with an
680 /// 'availability' attribute where we're targing a platform prior to
681 /// the introduction of this feature.
682 bool isWeakImported() const;
684 /// \brief Determines whether this symbol can be weak-imported,
685 /// e.g., whether it would be well-formed to add the weak_import
688 /// \param IsDefinition Set to \c true to indicate that this
689 /// declaration cannot be weak-imported because it has a definition.
690 bool canBeWeakImported(bool &IsDefinition) const;
692 /// \brief Determine whether this declaration came from an AST file (such as
693 /// a precompiled header or module) rather than having been parsed.
694 bool isFromASTFile() const { return FromASTFile; }
696 /// \brief Retrieve the global declaration ID associated with this
697 /// declaration, which specifies where this Decl was loaded from.
698 unsigned getGlobalID() const {
700 return *((const unsigned*)this - 1);
704 /// \brief Retrieve the global ID of the module that owns this particular
706 unsigned getOwningModuleID() const {
708 return *((const unsigned*)this - 2);
713 Module *getOwningModuleSlow() const;
716 bool hasLocalOwningModuleStorage() const;
719 /// \brief Get the imported owning module, if this decl is from an imported
720 /// (non-local) module.
721 Module *getImportedOwningModule() const {
722 if (!isFromASTFile() || !hasOwningModule())
725 return getOwningModuleSlow();
728 /// \brief Get the local owning module, if known. Returns nullptr if owner is
729 /// not yet known or declaration is not from a module.
730 Module *getLocalOwningModule() const {
731 if (isFromASTFile() || !hasOwningModule())
734 assert(hasLocalOwningModuleStorage() &&
735 "owned local decl but no local module storage");
736 return reinterpret_cast<Module *const *>(this)[-1];
738 void setLocalOwningModule(Module *M) {
739 assert(!isFromASTFile() && hasOwningModule() &&
740 hasLocalOwningModuleStorage() &&
741 "should not have a cached owning module");
742 reinterpret_cast<Module **>(this)[-1] = M;
745 /// Is this declaration owned by some module?
746 bool hasOwningModule() const {
747 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
750 /// Get the module that owns this declaration (for visibility purposes).
751 Module *getOwningModule() const {
752 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
755 /// Get the module that owns this declaration for linkage purposes.
756 /// There only ever is such a module under the C++ Modules TS.
758 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
759 /// all declarations in a global module fragment are unowned.
760 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
762 /// \brief Determine whether this declaration might be hidden from name
763 /// lookup. Note that the declaration might be visible even if this returns
764 /// \c false, if the owning module is visible within the query context.
765 // FIXME: Rename this to make it clearer what it does.
766 bool isHidden() const {
767 return (int)getModuleOwnershipKind() > (int)ModuleOwnershipKind::Visible;
770 /// Set that this declaration is globally visible, even if it came from a
771 /// module that is not visible.
772 void setVisibleDespiteOwningModule() {
774 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
777 /// \brief Get the kind of module ownership for this declaration.
778 ModuleOwnershipKind getModuleOwnershipKind() const {
779 return NextInContextAndBits.getInt();
782 /// \brief Set whether this declaration is hidden from name lookup.
783 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
784 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
785 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&
786 !hasLocalOwningModuleStorage()) &&
787 "no storage available for owning module for this declaration");
788 NextInContextAndBits.setInt(MOK);
791 unsigned getIdentifierNamespace() const {
792 return IdentifierNamespace;
795 bool isInIdentifierNamespace(unsigned NS) const {
796 return getIdentifierNamespace() & NS;
799 static unsigned getIdentifierNamespaceForKind(Kind DK);
801 bool hasTagIdentifierNamespace() const {
802 return isTagIdentifierNamespace(getIdentifierNamespace());
805 static bool isTagIdentifierNamespace(unsigned NS) {
806 // TagDecls have Tag and Type set and may also have TagFriend.
807 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
810 /// getLexicalDeclContext - The declaration context where this Decl was
811 /// lexically declared (LexicalDC). May be different from
812 /// getDeclContext() (SemanticDC).
816 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
818 /// void A::f(); // SemanticDC == namespace 'A'
819 /// // LexicalDC == global namespace
820 DeclContext *getLexicalDeclContext() {
822 return getSemanticDC();
823 return getMultipleDC()->LexicalDC;
825 const DeclContext *getLexicalDeclContext() const {
826 return const_cast<Decl*>(this)->getLexicalDeclContext();
829 /// Determine whether this declaration is declared out of line (outside its
830 /// semantic context).
831 virtual bool isOutOfLine() const;
833 /// setDeclContext - Set both the semantic and lexical DeclContext
835 void setDeclContext(DeclContext *DC);
837 void setLexicalDeclContext(DeclContext *DC);
839 /// Determine whether this declaration is a templated entity (whether it is
840 // within the scope of a template parameter).
841 bool isTemplated() const;
843 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
844 /// scoped decl is defined outside the current function or method. This is
845 /// roughly global variables and functions, but also handles enums (which
846 /// could be defined inside or outside a function etc).
847 bool isDefinedOutsideFunctionOrMethod() const {
848 return getParentFunctionOrMethod() == nullptr;
851 /// \brief Returns true if this declaration lexically is inside a function.
852 /// It recognizes non-defining declarations as well as members of local
855 /// void foo() { void bar(); }
856 /// void foo2() { class ABC { void bar(); }; }
858 bool isLexicallyWithinFunctionOrMethod() const;
860 /// \brief If this decl is defined inside a function/method/block it returns
861 /// the corresponding DeclContext, otherwise it returns null.
862 const DeclContext *getParentFunctionOrMethod() const;
863 DeclContext *getParentFunctionOrMethod() {
864 return const_cast<DeclContext*>(
865 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
868 /// \brief Retrieves the "canonical" declaration of the given declaration.
869 virtual Decl *getCanonicalDecl() { return this; }
870 const Decl *getCanonicalDecl() const {
871 return const_cast<Decl*>(this)->getCanonicalDecl();
874 /// \brief Whether this particular Decl is a canonical one.
875 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
878 /// \brief Returns the next redeclaration or itself if this is the only decl.
880 /// Decl subclasses that can be redeclared should override this method so that
881 /// Decl::redecl_iterator can iterate over them.
882 virtual Decl *getNextRedeclarationImpl() { return this; }
884 /// \brief Implementation of getPreviousDecl(), to be overridden by any
885 /// subclass that has a redeclaration chain.
886 virtual Decl *getPreviousDeclImpl() { return nullptr; }
888 /// \brief Implementation of getMostRecentDecl(), to be overridden by any
889 /// subclass that has a redeclaration chain.
890 virtual Decl *getMostRecentDeclImpl() { return this; }
893 /// \brief Iterates through all the redeclarations of the same decl.
894 class redecl_iterator {
895 /// Current - The current declaration.
896 Decl *Current = nullptr;
900 using value_type = Decl *;
901 using reference = const value_type &;
902 using pointer = const value_type *;
903 using iterator_category = std::forward_iterator_tag;
904 using difference_type = std::ptrdiff_t;
906 redecl_iterator() = default;
907 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
909 reference operator*() const { return Current; }
910 value_type operator->() const { return Current; }
912 redecl_iterator& operator++() {
913 assert(Current && "Advancing while iterator has reached end");
914 // Get either previous decl or latest decl.
915 Decl *Next = Current->getNextRedeclarationImpl();
916 assert(Next && "Should return next redeclaration or itself, never null!");
917 Current = (Next != Starter) ? Next : nullptr;
921 redecl_iterator operator++(int) {
922 redecl_iterator tmp(*this);
927 friend bool operator==(redecl_iterator x, redecl_iterator y) {
928 return x.Current == y.Current;
931 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
932 return x.Current != y.Current;
936 using redecl_range = llvm::iterator_range<redecl_iterator>;
938 /// \brief Returns an iterator range for all the redeclarations of the same
939 /// decl. It will iterate at least once (when this decl is the only one).
940 redecl_range redecls() const {
941 return redecl_range(redecls_begin(), redecls_end());
944 redecl_iterator redecls_begin() const {
945 return redecl_iterator(const_cast<Decl *>(this));
948 redecl_iterator redecls_end() const { return redecl_iterator(); }
950 /// \brief Retrieve the previous declaration that declares the same entity
951 /// as this declaration, or NULL if there is no previous declaration.
952 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
954 /// \brief Retrieve the most recent declaration that declares the same entity
955 /// as this declaration, or NULL if there is no previous declaration.
956 const Decl *getPreviousDecl() const {
957 return const_cast<Decl *>(this)->getPreviousDeclImpl();
960 /// \brief True if this is the first declaration in its redeclaration chain.
961 bool isFirstDecl() const {
962 return getPreviousDecl() == nullptr;
965 /// \brief Retrieve the most recent declaration that declares the same entity
966 /// as this declaration (which may be this declaration).
967 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
969 /// \brief Retrieve the most recent declaration that declares the same entity
970 /// as this declaration (which may be this declaration).
971 const Decl *getMostRecentDecl() const {
972 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
975 /// getBody - If this Decl represents a declaration for a body of code,
976 /// such as a function or method definition, this method returns the
977 /// top-level Stmt* of that body. Otherwise this method returns null.
978 virtual Stmt* getBody() const { return nullptr; }
980 /// \brief Returns true if this \c Decl represents a declaration for a body of
981 /// code, such as a function or method definition.
982 /// Note that \c hasBody can also return true if any redeclaration of this
983 /// \c Decl represents a declaration for a body of code.
984 virtual bool hasBody() const { return getBody() != nullptr; }
986 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
987 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
988 SourceLocation getBodyRBrace() const;
990 // global temp stats (until we have a per-module visitor)
991 static void add(Kind k);
992 static void EnableStatistics();
993 static void PrintStats();
995 /// isTemplateParameter - Determines whether this declaration is a
996 /// template parameter.
997 bool isTemplateParameter() const;
999 /// isTemplateParameter - Determines whether this declaration is a
1000 /// template parameter pack.
1001 bool isTemplateParameterPack() const;
1003 /// \brief Whether this declaration is a parameter pack.
1004 bool isParameterPack() const;
1006 /// \brief returns true if this declaration is a template
1007 bool isTemplateDecl() const;
1009 /// \brief Whether this declaration is a function or function template.
1010 bool isFunctionOrFunctionTemplate() const {
1011 return (DeclKind >= Decl::firstFunction &&
1012 DeclKind <= Decl::lastFunction) ||
1013 DeclKind == FunctionTemplate;
1016 /// \brief If this is a declaration that describes some template, this
1017 /// method returns that template declaration.
1018 TemplateDecl *getDescribedTemplate() const;
1020 /// \brief Returns the function itself, or the templated function if this is a
1021 /// function template.
1022 FunctionDecl *getAsFunction() LLVM_READONLY;
1024 const FunctionDecl *getAsFunction() const {
1025 return const_cast<Decl *>(this)->getAsFunction();
1028 /// \brief Changes the namespace of this declaration to reflect that it's
1029 /// a function-local extern declaration.
1031 /// These declarations appear in the lexical context of the extern
1032 /// declaration, but in the semantic context of the enclosing namespace
1034 void setLocalExternDecl() {
1035 Decl *Prev = getPreviousDecl();
1036 IdentifierNamespace &= ~IDNS_Ordinary;
1038 // It's OK for the declaration to still have the "invisible friend" flag or
1039 // the "conflicts with tag declarations in this scope" flag for the outer
1041 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&
1042 "namespace is not ordinary");
1044 IdentifierNamespace |= IDNS_LocalExtern;
1045 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1046 IdentifierNamespace |= IDNS_Ordinary;
1049 /// \brief Determine whether this is a block-scope declaration with linkage.
1050 /// This will either be a local variable declaration declared 'extern', or a
1051 /// local function declaration.
1052 bool isLocalExternDecl() {
1053 return IdentifierNamespace & IDNS_LocalExtern;
1056 /// \brief Changes the namespace of this declaration to reflect that it's
1057 /// the object of a friend declaration.
1059 /// These declarations appear in the lexical context of the friending
1060 /// class, but in the semantic context of the actual entity. This property
1061 /// applies only to a specific decl object; other redeclarations of the
1062 /// same entity may not (and probably don't) share this property.
1063 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1064 unsigned OldNS = IdentifierNamespace;
1065 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
1066 IDNS_TagFriend | IDNS_OrdinaryFriend |
1067 IDNS_LocalExtern)) &&
1068 "namespace includes neither ordinary nor tag");
1069 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
1070 IDNS_TagFriend | IDNS_OrdinaryFriend |
1071 IDNS_LocalExtern)) &&
1072 "namespace includes other than ordinary or tag");
1074 Decl *Prev = getPreviousDecl();
1075 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1077 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1078 IdentifierNamespace |= IDNS_TagFriend;
1079 if (PerformFriendInjection ||
1080 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1081 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1084 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | IDNS_LocalExtern)) {
1085 IdentifierNamespace |= IDNS_OrdinaryFriend;
1086 if (PerformFriendInjection ||
1087 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1088 IdentifierNamespace |= IDNS_Ordinary;
1092 enum FriendObjectKind {
1093 FOK_None, ///< Not a friend object.
1094 FOK_Declared, ///< A friend of a previously-declared entity.
1095 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1098 /// \brief Determines whether this declaration is the object of a
1099 /// friend declaration and, if so, what kind.
1101 /// There is currently no direct way to find the associated FriendDecl.
1102 FriendObjectKind getFriendObjectKind() const {
1104 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1105 if (!mask) return FOK_None;
1106 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1110 /// Specifies that this declaration is a C++ overloaded non-member.
1111 void setNonMemberOperator() {
1112 assert(getKind() == Function || getKind() == FunctionTemplate);
1113 assert((IdentifierNamespace & IDNS_Ordinary) &&
1114 "visible non-member operators should be in ordinary namespace");
1115 IdentifierNamespace |= IDNS_NonMemberOperator;
1118 static bool classofKind(Kind K) { return true; }
1119 static DeclContext *castToDeclContext(const Decl *);
1120 static Decl *castFromDeclContext(const DeclContext *);
1122 void print(raw_ostream &Out, unsigned Indentation = 0,
1123 bool PrintInstantiation = false) const;
1124 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1125 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1126 static void printGroup(Decl** Begin, unsigned NumDecls,
1127 raw_ostream &Out, const PrintingPolicy &Policy,
1128 unsigned Indentation = 0);
1130 // Debuggers don't usually respect default arguments.
1133 // Same as dump(), but forces color printing.
1134 void dumpColor() const;
1136 void dump(raw_ostream &Out, bool Deserialize = false) const;
1138 /// \brief Looks through the Decl's underlying type to extract a FunctionType
1139 /// when possible. Will return null if the type underlying the Decl does not
1140 /// have a FunctionType.
1141 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1144 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1145 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1149 ASTMutationListener *getASTMutationListener() const;
1152 /// \brief Determine whether two declarations declare the same entity.
1153 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1160 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1163 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1164 /// doing something to a specific decl.
1165 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1166 const Decl *TheDecl;
1169 const char *Message;
1172 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1173 SourceManager &sm, const char *Msg)
1174 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1176 void print(raw_ostream &OS) const override;
1179 /// \brief The results of name lookup within a DeclContext. This is either a
1180 /// single result (with no stable storage) or a collection of results (with
1181 /// stable storage provided by the lookup table).
1182 class DeclContextLookupResult {
1183 using ResultTy = ArrayRef<NamedDecl *>;
1187 // If there is only one lookup result, it would be invalidated by
1188 // reallocations of the name table, so store it separately.
1189 NamedDecl *Single = nullptr;
1191 static NamedDecl *const SingleElementDummyList;
1194 DeclContextLookupResult() = default;
1195 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1197 DeclContextLookupResult(NamedDecl *Single)
1198 : Result(SingleElementDummyList), Single(Single) {}
1202 using IteratorBase =
1203 llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1204 std::random_access_iterator_tag,
1207 class iterator : public IteratorBase {
1208 value_type SingleElement;
1211 iterator() = default;
1212 explicit iterator(pointer Pos, value_type Single = nullptr)
1213 : IteratorBase(Pos), SingleElement(Single) {}
1215 reference operator*() const {
1216 return SingleElement ? SingleElement : IteratorBase::operator*();
1220 using const_iterator = iterator;
1221 using pointer = iterator::pointer;
1222 using reference = iterator::reference;
1224 iterator begin() const { return iterator(Result.begin(), Single); }
1225 iterator end() const { return iterator(Result.end(), Single); }
1227 bool empty() const { return Result.empty(); }
1228 pointer data() const { return Single ? &Single : Result.data(); }
1229 size_t size() const { return Single ? 1 : Result.size(); }
1230 reference front() const { return Single ? Single : Result.front(); }
1231 reference back() const { return Single ? Single : Result.back(); }
1232 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1234 // FIXME: Remove this from the interface
1235 DeclContextLookupResult slice(size_t N) const {
1236 DeclContextLookupResult Sliced = Result.slice(N);
1237 Sliced.Single = Single;
1242 /// DeclContext - This is used only as base class of specific decl types that
1243 /// can act as declaration contexts. These decls are (only the top classes
1244 /// that directly derive from DeclContext are mentioned, not their subclasses):
1246 /// TranslationUnitDecl
1251 /// ObjCContainerDecl
1255 /// OMPDeclareReductionDecl
1257 /// DeclKind - This indicates which class this is.
1258 unsigned DeclKind : 8;
1260 /// \brief Whether this declaration context also has some external
1261 /// storage that contains additional declarations that are lexically
1262 /// part of this context.
1263 mutable bool ExternalLexicalStorage : 1;
1265 /// \brief Whether this declaration context also has some external
1266 /// storage that contains additional declarations that are visible
1267 /// in this context.
1268 mutable bool ExternalVisibleStorage : 1;
1270 /// \brief Whether this declaration context has had external visible
1271 /// storage added since the last lookup. In this case, \c LookupPtr's
1272 /// invariant may not hold and needs to be fixed before we perform
1274 mutable bool NeedToReconcileExternalVisibleStorage : 1;
1276 /// \brief If \c true, this context may have local lexical declarations
1277 /// that are missing from the lookup table.
1278 mutable bool HasLazyLocalLexicalLookups : 1;
1280 /// \brief If \c true, the external source may have lexical declarations
1281 /// that are missing from the lookup table.
1282 mutable bool HasLazyExternalLexicalLookups : 1;
1284 /// \brief If \c true, lookups should only return identifier from
1285 /// DeclContext scope (for example TranslationUnit). Used in
1286 /// LookupQualifiedName()
1287 mutable bool UseQualifiedLookup : 1;
1289 /// \brief Pointer to the data structure used to lookup declarations
1290 /// within this context (or a DependentStoredDeclsMap if this is a
1291 /// dependent context). We maintain the invariant that, if the map
1292 /// contains an entry for a DeclarationName (and we haven't lazily
1293 /// omitted anything), then it contains all relevant entries for that
1294 /// name (modulo the hasExternalDecls() flag).
1295 mutable StoredDeclsMap *LookupPtr = nullptr;
1298 friend class ASTDeclReader;
1299 friend class ASTWriter;
1300 friend class ExternalASTSource;
1302 /// FirstDecl - The first declaration stored within this declaration
1304 mutable Decl *FirstDecl = nullptr;
1306 /// LastDecl - The last declaration stored within this declaration
1307 /// context. FIXME: We could probably cache this value somewhere
1308 /// outside of the DeclContext, to reduce the size of DeclContext by
1309 /// another pointer.
1310 mutable Decl *LastDecl = nullptr;
1312 /// \brief Build up a chain of declarations.
1314 /// \returns the first/last pair of declarations.
1315 static std::pair<Decl *, Decl *>
1316 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1318 DeclContext(Decl::Kind K)
1319 : DeclKind(K), ExternalLexicalStorage(false),
1320 ExternalVisibleStorage(false),
1321 NeedToReconcileExternalVisibleStorage(false),
1322 HasLazyLocalLexicalLookups(false), HasLazyExternalLexicalLookups(false),
1323 UseQualifiedLookup(false) {}
1328 Decl::Kind getDeclKind() const {
1329 return static_cast<Decl::Kind>(DeclKind);
1332 const char *getDeclKindName() const;
1334 /// getParent - Returns the containing DeclContext.
1335 DeclContext *getParent() {
1336 return cast<Decl>(this)->getDeclContext();
1338 const DeclContext *getParent() const {
1339 return const_cast<DeclContext*>(this)->getParent();
1342 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1343 /// different from getParent, e.g.:
1348 /// struct A::S {}; // getParent() == namespace 'A'
1349 /// // getLexicalParent() == translation unit
1351 DeclContext *getLexicalParent() {
1352 return cast<Decl>(this)->getLexicalDeclContext();
1354 const DeclContext *getLexicalParent() const {
1355 return const_cast<DeclContext*>(this)->getLexicalParent();
1358 DeclContext *getLookupParent();
1360 const DeclContext *getLookupParent() const {
1361 return const_cast<DeclContext*>(this)->getLookupParent();
1364 ASTContext &getParentASTContext() const {
1365 return cast<Decl>(this)->getASTContext();
1368 bool isClosure() const {
1369 return DeclKind == Decl::Block;
1372 bool isObjCContainer() const {
1374 case Decl::ObjCCategory:
1375 case Decl::ObjCCategoryImpl:
1376 case Decl::ObjCImplementation:
1377 case Decl::ObjCInterface:
1378 case Decl::ObjCProtocol:
1384 bool isFunctionOrMethod() const {
1387 case Decl::Captured:
1388 case Decl::ObjCMethod:
1391 return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1395 /// \brief Test whether the context supports looking up names.
1396 bool isLookupContext() const {
1397 return !isFunctionOrMethod() && DeclKind != Decl::LinkageSpec &&
1398 DeclKind != Decl::Export;
1401 bool isFileContext() const {
1402 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1405 bool isTranslationUnit() const {
1406 return DeclKind == Decl::TranslationUnit;
1409 bool isRecord() const {
1410 return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1413 bool isNamespace() const {
1414 return DeclKind == Decl::Namespace;
1417 bool isStdNamespace() const;
1419 bool isInlineNamespace() const;
1421 /// \brief Determines whether this context is dependent on a
1422 /// template parameter.
1423 bool isDependentContext() const;
1425 /// isTransparentContext - Determines whether this context is a
1426 /// "transparent" context, meaning that the members declared in this
1427 /// context are semantically declared in the nearest enclosing
1428 /// non-transparent (opaque) context but are lexically declared in
1429 /// this context. For example, consider the enumerators of an
1430 /// enumeration type:
1436 /// Here, E is a transparent context, so its enumerator (Val1) will
1437 /// appear (semantically) that it is in the same context of E.
1438 /// Examples of transparent contexts include: enumerations (except for
1439 /// C++0x scoped enums), and C++ linkage specifications.
1440 bool isTransparentContext() const;
1442 /// \brief Determines whether this context or some of its ancestors is a
1443 /// linkage specification context that specifies C linkage.
1444 bool isExternCContext() const;
1446 /// \brief Retrieve the nearest enclosing C linkage specification context.
1447 const LinkageSpecDecl *getExternCContext() const;
1449 /// \brief Determines whether this context or some of its ancestors is a
1450 /// linkage specification context that specifies C++ linkage.
1451 bool isExternCXXContext() const;
1453 /// \brief Determine whether this declaration context is equivalent
1454 /// to the declaration context DC.
1455 bool Equals(const DeclContext *DC) const {
1456 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1459 /// \brief Determine whether this declaration context encloses the
1460 /// declaration context DC.
1461 bool Encloses(const DeclContext *DC) const;
1463 /// \brief Find the nearest non-closure ancestor of this context,
1464 /// i.e. the innermost semantic parent of this context which is not
1465 /// a closure. A context may be its own non-closure ancestor.
1466 Decl *getNonClosureAncestor();
1467 const Decl *getNonClosureAncestor() const {
1468 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1471 /// getPrimaryContext - There may be many different
1472 /// declarations of the same entity (including forward declarations
1473 /// of classes, multiple definitions of namespaces, etc.), each with
1474 /// a different set of declarations. This routine returns the
1475 /// "primary" DeclContext structure, which will contain the
1476 /// information needed to perform name lookup into this context.
1477 DeclContext *getPrimaryContext();
1478 const DeclContext *getPrimaryContext() const {
1479 return const_cast<DeclContext*>(this)->getPrimaryContext();
1482 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1483 /// other entities of the same name, or where it is a redeclaration if the
1484 /// two entities are compatible. This skips through transparent contexts.
1485 DeclContext *getRedeclContext();
1486 const DeclContext *getRedeclContext() const {
1487 return const_cast<DeclContext *>(this)->getRedeclContext();
1490 /// \brief Retrieve the nearest enclosing namespace context.
1491 DeclContext *getEnclosingNamespaceContext();
1492 const DeclContext *getEnclosingNamespaceContext() const {
1493 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1496 /// \brief Retrieve the outermost lexically enclosing record context.
1497 RecordDecl *getOuterLexicalRecordContext();
1498 const RecordDecl *getOuterLexicalRecordContext() const {
1499 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1502 /// \brief Test if this context is part of the enclosing namespace set of
1503 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1504 /// isn't a namespace, this is equivalent to Equals().
1506 /// The enclosing namespace set of a namespace is the namespace and, if it is
1507 /// inline, its enclosing namespace, recursively.
1508 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1510 /// \brief Collects all of the declaration contexts that are semantically
1511 /// connected to this declaration context.
1513 /// For declaration contexts that have multiple semantically connected but
1514 /// syntactically distinct contexts, such as C++ namespaces, this routine
1515 /// retrieves the complete set of such declaration contexts in source order.
1516 /// For example, given:
1527 /// The \c Contexts parameter will contain both definitions of N.
1529 /// \param Contexts Will be cleared and set to the set of declaration
1530 /// contexts that are semanticaly connected to this declaration context,
1531 /// in source order, including this context (which may be the only result,
1532 /// for non-namespace contexts).
1533 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1535 /// decl_iterator - Iterates through the declarations stored
1536 /// within this context.
1537 class decl_iterator {
1538 /// Current - The current declaration.
1539 Decl *Current = nullptr;
1542 using value_type = Decl *;
1543 using reference = const value_type &;
1544 using pointer = const value_type *;
1545 using iterator_category = std::forward_iterator_tag;
1546 using difference_type = std::ptrdiff_t;
1548 decl_iterator() = default;
1549 explicit decl_iterator(Decl *C) : Current(C) {}
1551 reference operator*() const { return Current; }
1553 // This doesn't meet the iterator requirements, but it's convenient
1554 value_type operator->() const { return Current; }
1556 decl_iterator& operator++() {
1557 Current = Current->getNextDeclInContext();
1561 decl_iterator operator++(int) {
1562 decl_iterator tmp(*this);
1567 friend bool operator==(decl_iterator x, decl_iterator y) {
1568 return x.Current == y.Current;
1571 friend bool operator!=(decl_iterator x, decl_iterator y) {
1572 return x.Current != y.Current;
1576 using decl_range = llvm::iterator_range<decl_iterator>;
1578 /// decls_begin/decls_end - Iterate over the declarations stored in
1580 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
1581 decl_iterator decls_begin() const;
1582 decl_iterator decls_end() const { return decl_iterator(); }
1583 bool decls_empty() const;
1585 /// noload_decls_begin/end - Iterate over the declarations stored in this
1586 /// context that are currently loaded; don't attempt to retrieve anything
1587 /// from an external source.
1588 decl_range noload_decls() const {
1589 return decl_range(noload_decls_begin(), noload_decls_end());
1591 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
1592 decl_iterator noload_decls_end() const { return decl_iterator(); }
1594 /// specific_decl_iterator - Iterates over a subrange of
1595 /// declarations stored in a DeclContext, providing only those that
1596 /// are of type SpecificDecl (or a class derived from it). This
1597 /// iterator is used, for example, to provide iteration over just
1598 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1599 template<typename SpecificDecl>
1600 class specific_decl_iterator {
1601 /// Current - The current, underlying declaration iterator, which
1602 /// will either be NULL or will point to a declaration of
1603 /// type SpecificDecl.
1604 DeclContext::decl_iterator Current;
1606 /// SkipToNextDecl - Advances the current position up to the next
1607 /// declaration of type SpecificDecl that also meets the criteria
1608 /// required by Acceptable.
1609 void SkipToNextDecl() {
1610 while (*Current && !isa<SpecificDecl>(*Current))
1615 using value_type = SpecificDecl *;
1616 // TODO: Add reference and pointer types (with some appropriate proxy type)
1617 // if we ever have a need for them.
1618 using reference = void;
1619 using pointer = void;
1620 using difference_type =
1621 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
1622 using iterator_category = std::forward_iterator_tag;
1624 specific_decl_iterator() = default;
1626 /// specific_decl_iterator - Construct a new iterator over a
1627 /// subset of the declarations the range [C,
1628 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1629 /// member function of SpecificDecl that should return true for
1630 /// all of the SpecificDecl instances that will be in the subset
1631 /// of iterators. For example, if you want Objective-C instance
1632 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1633 /// &ObjCMethodDecl::isInstanceMethod.
1634 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1638 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1640 // This doesn't meet the iterator requirements, but it's convenient
1641 value_type operator->() const { return **this; }
1643 specific_decl_iterator& operator++() {
1649 specific_decl_iterator operator++(int) {
1650 specific_decl_iterator tmp(*this);
1655 friend bool operator==(const specific_decl_iterator& x,
1656 const specific_decl_iterator& y) {
1657 return x.Current == y.Current;
1660 friend bool operator!=(const specific_decl_iterator& x,
1661 const specific_decl_iterator& y) {
1662 return x.Current != y.Current;
1666 /// \brief Iterates over a filtered subrange of declarations stored
1667 /// in a DeclContext.
1669 /// This iterator visits only those declarations that are of type
1670 /// SpecificDecl (or a class derived from it) and that meet some
1671 /// additional run-time criteria. This iterator is used, for
1672 /// example, to provide access to the instance methods within an
1673 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1674 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1675 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1676 class filtered_decl_iterator {
1677 /// Current - The current, underlying declaration iterator, which
1678 /// will either be NULL or will point to a declaration of
1679 /// type SpecificDecl.
1680 DeclContext::decl_iterator Current;
1682 /// SkipToNextDecl - Advances the current position up to the next
1683 /// declaration of type SpecificDecl that also meets the criteria
1684 /// required by Acceptable.
1685 void SkipToNextDecl() {
1687 (!isa<SpecificDecl>(*Current) ||
1688 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1693 using value_type = SpecificDecl *;
1694 // TODO: Add reference and pointer types (with some appropriate proxy type)
1695 // if we ever have a need for them.
1696 using reference = void;
1697 using pointer = void;
1698 using difference_type =
1699 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
1700 using iterator_category = std::forward_iterator_tag;
1702 filtered_decl_iterator() = default;
1704 /// filtered_decl_iterator - Construct a new iterator over a
1705 /// subset of the declarations the range [C,
1706 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1707 /// member function of SpecificDecl that should return true for
1708 /// all of the SpecificDecl instances that will be in the subset
1709 /// of iterators. For example, if you want Objective-C instance
1710 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1711 /// &ObjCMethodDecl::isInstanceMethod.
1712 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1716 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1717 value_type operator->() const { return cast<SpecificDecl>(*Current); }
1719 filtered_decl_iterator& operator++() {
1725 filtered_decl_iterator operator++(int) {
1726 filtered_decl_iterator tmp(*this);
1731 friend bool operator==(const filtered_decl_iterator& x,
1732 const filtered_decl_iterator& y) {
1733 return x.Current == y.Current;
1736 friend bool operator!=(const filtered_decl_iterator& x,
1737 const filtered_decl_iterator& y) {
1738 return x.Current != y.Current;
1742 /// @brief Add the declaration D into this context.
1744 /// This routine should be invoked when the declaration D has first
1745 /// been declared, to place D into the context where it was
1746 /// (lexically) defined. Every declaration must be added to one
1747 /// (and only one!) context, where it can be visited via
1748 /// [decls_begin(), decls_end()). Once a declaration has been added
1749 /// to its lexical context, the corresponding DeclContext owns the
1752 /// If D is also a NamedDecl, it will be made visible within its
1753 /// semantic context via makeDeclVisibleInContext.
1754 void addDecl(Decl *D);
1756 /// @brief Add the declaration D into this context, but suppress
1757 /// searches for external declarations with the same name.
1759 /// Although analogous in function to addDecl, this removes an
1760 /// important check. This is only useful if the Decl is being
1761 /// added in response to an external search; in all other cases,
1762 /// addDecl() is the right function to use.
1763 /// See the ASTImporter for use cases.
1764 void addDeclInternal(Decl *D);
1766 /// @brief Add the declaration D to this context without modifying
1767 /// any lookup tables.
1769 /// This is useful for some operations in dependent contexts where
1770 /// the semantic context might not be dependent; this basically
1771 /// only happens with friends.
1772 void addHiddenDecl(Decl *D);
1774 /// @brief Removes a declaration from this context.
1775 void removeDecl(Decl *D);
1777 /// @brief Checks whether a declaration is in this context.
1778 bool containsDecl(Decl *D) const;
1780 using lookup_result = DeclContextLookupResult;
1781 using lookup_iterator = lookup_result::iterator;
1783 /// lookup - Find the declarations (if any) with the given Name in
1784 /// this context. Returns a range of iterators that contains all of
1785 /// the declarations with this name, with object, function, member,
1786 /// and enumerator names preceding any tag name. Note that this
1787 /// routine will not look into parent contexts.
1788 lookup_result lookup(DeclarationName Name) const;
1790 /// \brief Find the declarations with the given name that are visible
1791 /// within this context; don't attempt to retrieve anything from an
1792 /// external source.
1793 lookup_result noload_lookup(DeclarationName Name);
1795 /// \brief A simplistic name lookup mechanism that performs name lookup
1796 /// into this declaration context without consulting the external source.
1798 /// This function should almost never be used, because it subverts the
1799 /// usual relationship between a DeclContext and the external source.
1800 /// See the ASTImporter for the (few, but important) use cases.
1802 /// FIXME: This is very inefficient; replace uses of it with uses of
1804 void localUncachedLookup(DeclarationName Name,
1805 SmallVectorImpl<NamedDecl *> &Results);
1807 /// @brief Makes a declaration visible within this context.
1809 /// This routine makes the declaration D visible to name lookup
1810 /// within this context and, if this is a transparent context,
1811 /// within its parent contexts up to the first enclosing
1812 /// non-transparent context. Making a declaration visible within a
1813 /// context does not transfer ownership of a declaration, and a
1814 /// declaration can be visible in many contexts that aren't its
1815 /// lexical context.
1817 /// If D is a redeclaration of an existing declaration that is
1818 /// visible from this context, as determined by
1819 /// NamedDecl::declarationReplaces, the previous declaration will be
1820 /// replaced with D.
1821 void makeDeclVisibleInContext(NamedDecl *D);
1823 /// all_lookups_iterator - An iterator that provides a view over the results
1824 /// of looking up every possible name.
1825 class all_lookups_iterator;
1827 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
1829 lookups_range lookups() const;
1830 lookups_range noload_lookups() const;
1832 /// \brief Iterators over all possible lookups within this context.
1833 all_lookups_iterator lookups_begin() const;
1834 all_lookups_iterator lookups_end() const;
1836 /// \brief Iterators over all possible lookups within this context that are
1837 /// currently loaded; don't attempt to retrieve anything from an external
1839 all_lookups_iterator noload_lookups_begin() const;
1840 all_lookups_iterator noload_lookups_end() const;
1842 struct udir_iterator;
1844 using udir_iterator_base =
1845 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
1846 std::random_access_iterator_tag,
1847 UsingDirectiveDecl *>;
1849 struct udir_iterator : udir_iterator_base {
1850 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
1852 UsingDirectiveDecl *operator*() const;
1855 using udir_range = llvm::iterator_range<udir_iterator>;
1857 udir_range using_directives() const;
1859 // These are all defined in DependentDiagnostic.h.
1860 class ddiag_iterator;
1862 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
1864 inline ddiag_range ddiags() const;
1866 // Low-level accessors
1868 /// \brief Mark that there are external lexical declarations that we need
1869 /// to include in our lookup table (and that are not available as external
1870 /// visible lookups). These extra lookup results will be found by walking
1871 /// the lexical declarations of this context. This should be used only if
1872 /// setHasExternalLexicalStorage() has been called on any decl context for
1873 /// which this is the primary context.
1874 void setMustBuildLookupTable() {
1875 assert(this == getPrimaryContext() &&
1876 "should only be called on primary context");
1877 HasLazyExternalLexicalLookups = true;
1880 /// \brief Retrieve the internal representation of the lookup structure.
1881 /// This may omit some names if we are lazily building the structure.
1882 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
1884 /// \brief Ensure the lookup structure is fully-built and return it.
1885 StoredDeclsMap *buildLookup();
1887 /// \brief Whether this DeclContext has external storage containing
1888 /// additional declarations that are lexically in this context.
1889 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1891 /// \brief State whether this DeclContext has external storage for
1892 /// declarations lexically in this context.
1893 void setHasExternalLexicalStorage(bool ES = true) {
1894 ExternalLexicalStorage = ES;
1897 /// \brief Whether this DeclContext has external storage containing
1898 /// additional declarations that are visible in this context.
1899 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1901 /// \brief State whether this DeclContext has external storage for
1902 /// declarations visible in this context.
1903 void setHasExternalVisibleStorage(bool ES = true) {
1904 ExternalVisibleStorage = ES;
1905 if (ES && LookupPtr)
1906 NeedToReconcileExternalVisibleStorage = true;
1909 /// \brief Determine whether the given declaration is stored in the list of
1910 /// declarations lexically within this context.
1911 bool isDeclInLexicalTraversal(const Decl *D) const {
1912 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1916 bool setUseQualifiedLookup(bool use = true) {
1917 bool old_value = UseQualifiedLookup;
1918 UseQualifiedLookup = use;
1922 bool shouldUseQualifiedLookup() const {
1923 return UseQualifiedLookup;
1926 static bool classof(const Decl *D);
1927 static bool classof(const DeclContext *D) { return true; }
1929 void dumpDeclContext() const;
1930 void dumpLookups() const;
1931 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
1932 bool Deserialize = false) const;
1935 friend class DependentDiagnostic;
1937 void reconcileExternalVisibleStorage() const;
1938 bool LoadLexicalDeclsFromExternalStorage() const;
1940 /// @brief Makes a declaration visible within this context, but
1941 /// suppresses searches for external declarations with the same
1944 /// Analogous to makeDeclVisibleInContext, but for the exclusive
1945 /// use of addDeclInternal().
1946 void makeDeclVisibleInContextInternal(NamedDecl *D);
1948 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1950 void buildLookupImpl(DeclContext *DCtx, bool Internal);
1951 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1952 bool Rediscoverable);
1953 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1956 inline bool Decl::isTemplateParameter() const {
1957 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1958 getKind() == TemplateTemplateParm;
1961 // Specialization selected when ToTy is not a known subclass of DeclContext.
1962 template <class ToTy,
1963 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
1964 struct cast_convert_decl_context {
1965 static const ToTy *doit(const DeclContext *Val) {
1966 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1969 static ToTy *doit(DeclContext *Val) {
1970 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1974 // Specialization selected when ToTy is a known subclass of DeclContext.
1975 template <class ToTy>
1976 struct cast_convert_decl_context<ToTy, true> {
1977 static const ToTy *doit(const DeclContext *Val) {
1978 return static_cast<const ToTy*>(Val);
1981 static ToTy *doit(DeclContext *Val) {
1982 return static_cast<ToTy*>(Val);
1986 } // namespace clang
1990 /// isa<T>(DeclContext*)
1991 template <typename To>
1992 struct isa_impl<To, ::clang::DeclContext> {
1993 static bool doit(const ::clang::DeclContext &Val) {
1994 return To::classofKind(Val.getDeclKind());
1998 /// cast<T>(DeclContext*)
1999 template<class ToTy>
2000 struct cast_convert_val<ToTy,
2001 const ::clang::DeclContext,const ::clang::DeclContext> {
2002 static const ToTy &doit(const ::clang::DeclContext &Val) {
2003 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2007 template<class ToTy>
2008 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2009 static ToTy &doit(::clang::DeclContext &Val) {
2010 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2014 template<class ToTy>
2015 struct cast_convert_val<ToTy,
2016 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2017 static const ToTy *doit(const ::clang::DeclContext *Val) {
2018 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2022 template<class ToTy>
2023 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2024 static ToTy *doit(::clang::DeclContext *Val) {
2025 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2029 /// Implement cast_convert_val for Decl -> DeclContext conversions.
2030 template<class FromTy>
2031 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2032 static ::clang::DeclContext &doit(const FromTy &Val) {
2033 return *FromTy::castToDeclContext(&Val);
2037 template<class FromTy>
2038 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2039 static ::clang::DeclContext *doit(const FromTy *Val) {
2040 return FromTy::castToDeclContext(Val);
2044 template<class FromTy>
2045 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2046 static const ::clang::DeclContext &doit(const FromTy &Val) {
2047 return *FromTy::castToDeclContext(&Val);
2051 template<class FromTy>
2052 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2053 static const ::clang::DeclContext *doit(const FromTy *Val) {
2054 return FromTy::castToDeclContext(Val);
2060 #endif // LLVM_CLANG_AST_DECLBASE_H