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 Retrieve the version of the target platform in which this
620 /// declaration was introduced.
622 /// \returns An empty version tuple if this declaration has no 'introduced'
623 /// availability attributes, or the version tuple that's specified in the
624 /// attribute otherwise.
625 VersionTuple getVersionIntroduced() const;
627 /// \brief Determine whether this declaration is marked 'deprecated'.
629 /// \param Message If non-NULL and the declaration is deprecated,
630 /// this will be set to the message describing why the declaration
631 /// was deprecated (which may be empty).
632 bool isDeprecated(std::string *Message = nullptr) const {
633 return getAvailability(Message) == AR_Deprecated;
636 /// \brief Determine whether this declaration is marked 'unavailable'.
638 /// \param Message If non-NULL and the declaration is unavailable,
639 /// this will be set to the message describing why the declaration
640 /// was made unavailable (which may be empty).
641 bool isUnavailable(std::string *Message = nullptr) const {
642 return getAvailability(Message) == AR_Unavailable;
645 /// \brief Determine whether this is a weak-imported symbol.
647 /// Weak-imported symbols are typically marked with the
648 /// 'weak_import' attribute, but may also be marked with an
649 /// 'availability' attribute where we're targing a platform prior to
650 /// the introduction of this feature.
651 bool isWeakImported() const;
653 /// \brief Determines whether this symbol can be weak-imported,
654 /// e.g., whether it would be well-formed to add the weak_import
657 /// \param IsDefinition Set to \c true to indicate that this
658 /// declaration cannot be weak-imported because it has a definition.
659 bool canBeWeakImported(bool &IsDefinition) const;
661 /// \brief Determine whether this declaration came from an AST file (such as
662 /// a precompiled header or module) rather than having been parsed.
663 bool isFromASTFile() const { return FromASTFile; }
665 /// \brief Retrieve the global declaration ID associated with this
666 /// declaration, which specifies where this Decl was loaded from.
667 unsigned getGlobalID() const {
669 return *((const unsigned*)this - 1);
673 /// \brief Retrieve the global ID of the module that owns this particular
675 unsigned getOwningModuleID() const {
677 return *((const unsigned*)this - 2);
682 Module *getOwningModuleSlow() const;
684 bool hasLocalOwningModuleStorage() const;
687 /// \brief Get the imported owning module, if this decl is from an imported
688 /// (non-local) module.
689 Module *getImportedOwningModule() const {
690 if (!isFromASTFile())
693 return getOwningModuleSlow();
696 /// \brief Get the local owning module, if known. Returns nullptr if owner is
697 /// not yet known or declaration is not from a module.
698 Module *getLocalOwningModule() const {
699 if (isFromASTFile() || !Hidden)
701 return reinterpret_cast<Module *const *>(this)[-1];
703 void setLocalOwningModule(Module *M) {
704 assert(!isFromASTFile() && Hidden && hasLocalOwningModuleStorage() &&
705 "should not have a cached owning module");
706 reinterpret_cast<Module **>(this)[-1] = M;
709 Module *getOwningModule() const {
710 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
713 /// \brief Determine whether this declaration is hidden from name lookup.
714 bool isHidden() const { return Hidden; }
716 /// \brief Set whether this declaration is hidden from name lookup.
717 void setHidden(bool Hide) {
718 assert((!Hide || isFromASTFile() || hasLocalOwningModuleStorage()) &&
719 "declaration with no owning module can't be hidden");
723 unsigned getIdentifierNamespace() const {
724 return IdentifierNamespace;
726 bool isInIdentifierNamespace(unsigned NS) const {
727 return getIdentifierNamespace() & NS;
729 static unsigned getIdentifierNamespaceForKind(Kind DK);
731 bool hasTagIdentifierNamespace() const {
732 return isTagIdentifierNamespace(getIdentifierNamespace());
734 static bool isTagIdentifierNamespace(unsigned NS) {
735 // TagDecls have Tag and Type set and may also have TagFriend.
736 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
739 /// getLexicalDeclContext - The declaration context where this Decl was
740 /// lexically declared (LexicalDC). May be different from
741 /// getDeclContext() (SemanticDC).
745 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
747 /// void A::f(); // SemanticDC == namespace 'A'
748 /// // LexicalDC == global namespace
749 DeclContext *getLexicalDeclContext() {
751 return getSemanticDC();
752 return getMultipleDC()->LexicalDC;
754 const DeclContext *getLexicalDeclContext() const {
755 return const_cast<Decl*>(this)->getLexicalDeclContext();
758 /// Determine whether this declaration is declared out of line (outside its
759 /// semantic context).
760 virtual bool isOutOfLine() const;
762 /// setDeclContext - Set both the semantic and lexical DeclContext
764 void setDeclContext(DeclContext *DC);
766 void setLexicalDeclContext(DeclContext *DC);
768 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
769 /// scoped decl is defined outside the current function or method. This is
770 /// roughly global variables and functions, but also handles enums (which
771 /// could be defined inside or outside a function etc).
772 bool isDefinedOutsideFunctionOrMethod() const {
773 return getParentFunctionOrMethod() == nullptr;
776 /// \brief Returns true if this declaration lexically is inside a function.
777 /// It recognizes non-defining declarations as well as members of local
780 /// void foo() { void bar(); }
781 /// void foo2() { class ABC { void bar(); }; }
783 bool isLexicallyWithinFunctionOrMethod() const;
785 /// \brief If this decl is defined inside a function/method/block it returns
786 /// the corresponding DeclContext, otherwise it returns null.
787 const DeclContext *getParentFunctionOrMethod() const;
788 DeclContext *getParentFunctionOrMethod() {
789 return const_cast<DeclContext*>(
790 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
793 /// \brief Retrieves the "canonical" declaration of the given declaration.
794 virtual Decl *getCanonicalDecl() { return this; }
795 const Decl *getCanonicalDecl() const {
796 return const_cast<Decl*>(this)->getCanonicalDecl();
799 /// \brief Whether this particular Decl is a canonical one.
800 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
803 /// \brief Returns the next redeclaration or itself if this is the only decl.
805 /// Decl subclasses that can be redeclared should override this method so that
806 /// Decl::redecl_iterator can iterate over them.
807 virtual Decl *getNextRedeclarationImpl() { return this; }
809 /// \brief Implementation of getPreviousDecl(), to be overridden by any
810 /// subclass that has a redeclaration chain.
811 virtual Decl *getPreviousDeclImpl() { return nullptr; }
813 /// \brief Implementation of getMostRecentDecl(), to be overridden by any
814 /// subclass that has a redeclaration chain.
815 virtual Decl *getMostRecentDeclImpl() { return this; }
818 /// \brief Iterates through all the redeclarations of the same decl.
819 class redecl_iterator {
820 /// Current - The current declaration.
825 typedef Decl *value_type;
826 typedef const value_type &reference;
827 typedef const value_type *pointer;
828 typedef std::forward_iterator_tag iterator_category;
829 typedef std::ptrdiff_t difference_type;
831 redecl_iterator() : Current(nullptr) { }
832 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
834 reference operator*() const { return Current; }
835 value_type operator->() const { return Current; }
837 redecl_iterator& operator++() {
838 assert(Current && "Advancing while iterator has reached end");
839 // Get either previous decl or latest decl.
840 Decl *Next = Current->getNextRedeclarationImpl();
841 assert(Next && "Should return next redeclaration or itself, never null!");
842 Current = (Next != Starter) ? Next : nullptr;
846 redecl_iterator operator++(int) {
847 redecl_iterator tmp(*this);
852 friend bool operator==(redecl_iterator x, redecl_iterator y) {
853 return x.Current == y.Current;
855 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
856 return x.Current != y.Current;
860 typedef llvm::iterator_range<redecl_iterator> redecl_range;
862 /// \brief Returns an iterator range for all the redeclarations of the same
863 /// decl. It will iterate at least once (when this decl is the only one).
864 redecl_range redecls() const {
865 return redecl_range(redecls_begin(), redecls_end());
868 redecl_iterator redecls_begin() const {
869 return redecl_iterator(const_cast<Decl *>(this));
871 redecl_iterator redecls_end() const { return redecl_iterator(); }
873 /// \brief Retrieve the previous declaration that declares the same entity
874 /// as this declaration, or NULL if there is no previous declaration.
875 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
877 /// \brief Retrieve the most recent declaration that declares the same entity
878 /// as this declaration, or NULL if there is no previous declaration.
879 const Decl *getPreviousDecl() const {
880 return const_cast<Decl *>(this)->getPreviousDeclImpl();
883 /// \brief True if this is the first declaration in its redeclaration chain.
884 bool isFirstDecl() const {
885 return getPreviousDecl() == nullptr;
888 /// \brief Retrieve the most recent declaration that declares the same entity
889 /// as this declaration (which may be this declaration).
890 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
892 /// \brief Retrieve the most recent declaration that declares the same entity
893 /// as this declaration (which may be this declaration).
894 const Decl *getMostRecentDecl() const {
895 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
898 /// getBody - If this Decl represents a declaration for a body of code,
899 /// such as a function or method definition, this method returns the
900 /// top-level Stmt* of that body. Otherwise this method returns null.
901 virtual Stmt* getBody() const { return nullptr; }
903 /// \brief Returns true if this \c Decl represents a declaration for a body of
904 /// code, such as a function or method definition.
905 /// Note that \c hasBody can also return true if any redeclaration of this
906 /// \c Decl represents a declaration for a body of code.
907 virtual bool hasBody() const { return getBody() != nullptr; }
909 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
910 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
911 SourceLocation getBodyRBrace() const;
913 // global temp stats (until we have a per-module visitor)
914 static void add(Kind k);
915 static void EnableStatistics();
916 static void PrintStats();
918 /// isTemplateParameter - Determines whether this declaration is a
919 /// template parameter.
920 bool isTemplateParameter() const;
922 /// isTemplateParameter - Determines whether this declaration is a
923 /// template parameter pack.
924 bool isTemplateParameterPack() const;
926 /// \brief Whether this declaration is a parameter pack.
927 bool isParameterPack() const;
929 /// \brief returns true if this declaration is a template
930 bool isTemplateDecl() const;
932 /// \brief Whether this declaration is a function or function template.
933 bool isFunctionOrFunctionTemplate() const {
934 return (DeclKind >= Decl::firstFunction &&
935 DeclKind <= Decl::lastFunction) ||
936 DeclKind == FunctionTemplate;
939 /// \brief If this is a declaration that describes some template, this
940 /// method returns that template declaration.
941 TemplateDecl *getDescribedTemplate() const;
943 /// \brief Returns the function itself, or the templated function if this is a
944 /// function template.
945 FunctionDecl *getAsFunction() LLVM_READONLY;
947 const FunctionDecl *getAsFunction() const {
948 return const_cast<Decl *>(this)->getAsFunction();
951 /// \brief Changes the namespace of this declaration to reflect that it's
952 /// a function-local extern declaration.
954 /// These declarations appear in the lexical context of the extern
955 /// declaration, but in the semantic context of the enclosing namespace
957 void setLocalExternDecl() {
958 assert((IdentifierNamespace == IDNS_Ordinary ||
959 IdentifierNamespace == IDNS_OrdinaryFriend) &&
960 "namespace is not ordinary");
962 Decl *Prev = getPreviousDecl();
963 IdentifierNamespace &= ~IDNS_Ordinary;
965 IdentifierNamespace |= IDNS_LocalExtern;
966 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
967 IdentifierNamespace |= IDNS_Ordinary;
970 /// \brief Determine whether this is a block-scope declaration with linkage.
971 /// This will either be a local variable declaration declared 'extern', or a
972 /// local function declaration.
973 bool isLocalExternDecl() {
974 return IdentifierNamespace & IDNS_LocalExtern;
977 /// \brief Changes the namespace of this declaration to reflect that it's
978 /// the object of a friend declaration.
980 /// These declarations appear in the lexical context of the friending
981 /// class, but in the semantic context of the actual entity. This property
982 /// applies only to a specific decl object; other redeclarations of the
983 /// same entity may not (and probably don't) share this property.
984 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
985 unsigned OldNS = IdentifierNamespace;
986 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
987 IDNS_TagFriend | IDNS_OrdinaryFriend |
988 IDNS_LocalExtern)) &&
989 "namespace includes neither ordinary nor tag");
990 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
991 IDNS_TagFriend | IDNS_OrdinaryFriend |
992 IDNS_LocalExtern)) &&
993 "namespace includes other than ordinary or tag");
995 Decl *Prev = getPreviousDecl();
996 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
998 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
999 IdentifierNamespace |= IDNS_TagFriend;
1000 if (PerformFriendInjection ||
1001 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1002 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1005 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | IDNS_LocalExtern)) {
1006 IdentifierNamespace |= IDNS_OrdinaryFriend;
1007 if (PerformFriendInjection ||
1008 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1009 IdentifierNamespace |= IDNS_Ordinary;
1013 enum FriendObjectKind {
1014 FOK_None, ///< Not a friend object.
1015 FOK_Declared, ///< A friend of a previously-declared entity.
1016 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1019 /// \brief Determines whether this declaration is the object of a
1020 /// friend declaration and, if so, what kind.
1022 /// There is currently no direct way to find the associated FriendDecl.
1023 FriendObjectKind getFriendObjectKind() const {
1025 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1026 if (!mask) return FOK_None;
1027 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1031 /// Specifies that this declaration is a C++ overloaded non-member.
1032 void setNonMemberOperator() {
1033 assert(getKind() == Function || getKind() == FunctionTemplate);
1034 assert((IdentifierNamespace & IDNS_Ordinary) &&
1035 "visible non-member operators should be in ordinary namespace");
1036 IdentifierNamespace |= IDNS_NonMemberOperator;
1039 static bool classofKind(Kind K) { return true; }
1040 static DeclContext *castToDeclContext(const Decl *);
1041 static Decl *castFromDeclContext(const DeclContext *);
1043 void print(raw_ostream &Out, unsigned Indentation = 0,
1044 bool PrintInstantiation = false) const;
1045 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1046 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1047 static void printGroup(Decl** Begin, unsigned NumDecls,
1048 raw_ostream &Out, const PrintingPolicy &Policy,
1049 unsigned Indentation = 0);
1050 // Debuggers don't usually respect default arguments.
1052 // Same as dump(), but forces color printing.
1053 void dumpColor() const;
1054 void dump(raw_ostream &Out, bool Deserialize = false) const;
1056 /// \brief Looks through the Decl's underlying type to extract a FunctionType
1057 /// when possible. Will return null if the type underlying the Decl does not
1058 /// have a FunctionType.
1059 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1062 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1063 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1067 ASTMutationListener *getASTMutationListener() const;
1070 /// \brief Determine whether two declarations declare the same entity.
1071 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1078 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1081 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1082 /// doing something to a specific decl.
1083 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1084 const Decl *TheDecl;
1087 const char *Message;
1089 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1090 SourceManager &sm, const char *Msg)
1091 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1093 void print(raw_ostream &OS) const override;
1096 /// \brief The results of name lookup within a DeclContext. This is either a
1097 /// single result (with no stable storage) or a collection of results (with
1098 /// stable storage provided by the lookup table).
1099 class DeclContextLookupResult {
1100 typedef ArrayRef<NamedDecl *> ResultTy;
1102 // If there is only one lookup result, it would be invalidated by
1103 // reallocations of the name table, so store it separately.
1106 static NamedDecl *const SingleElementDummyList;
1109 DeclContextLookupResult() : Result(), Single() {}
1110 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1111 : Result(Result), Single() {}
1112 DeclContextLookupResult(NamedDecl *Single)
1113 : Result(SingleElementDummyList), Single(Single) {}
1116 typedef llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1117 std::random_access_iterator_tag,
1118 NamedDecl *const> IteratorBase;
1119 class iterator : public IteratorBase {
1120 value_type SingleElement;
1123 iterator() : IteratorBase(), SingleElement() {}
1124 explicit iterator(pointer Pos, value_type Single = nullptr)
1125 : IteratorBase(Pos), SingleElement(Single) {}
1127 reference operator*() const {
1128 return SingleElement ? SingleElement : IteratorBase::operator*();
1131 typedef iterator const_iterator;
1132 typedef iterator::pointer pointer;
1133 typedef iterator::reference reference;
1135 iterator begin() const { return iterator(Result.begin(), Single); }
1136 iterator end() const { return iterator(Result.end(), Single); }
1138 bool empty() const { return Result.empty(); }
1139 pointer data() const { return Single ? &Single : Result.data(); }
1140 size_t size() const { return Single ? 1 : Result.size(); }
1141 reference front() const { return Single ? Single : Result.front(); }
1142 reference back() const { return Single ? Single : Result.back(); }
1143 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1145 // FIXME: Remove this from the interface
1146 DeclContextLookupResult slice(size_t N) const {
1147 DeclContextLookupResult Sliced = Result.slice(N);
1148 Sliced.Single = Single;
1153 /// DeclContext - This is used only as base class of specific decl types that
1154 /// can act as declaration contexts. These decls are (only the top classes
1155 /// that directly derive from DeclContext are mentioned, not their subclasses):
1157 /// TranslationUnitDecl
1162 /// ObjCContainerDecl
1166 /// OMPDeclareReductionDecl
1169 /// DeclKind - This indicates which class this is.
1170 unsigned DeclKind : 8;
1172 /// \brief Whether this declaration context also has some external
1173 /// storage that contains additional declarations that are lexically
1174 /// part of this context.
1175 mutable bool ExternalLexicalStorage : 1;
1177 /// \brief Whether this declaration context also has some external
1178 /// storage that contains additional declarations that are visible
1179 /// in this context.
1180 mutable bool ExternalVisibleStorage : 1;
1182 /// \brief Whether this declaration context has had external visible
1183 /// storage added since the last lookup. In this case, \c LookupPtr's
1184 /// invariant may not hold and needs to be fixed before we perform
1186 mutable bool NeedToReconcileExternalVisibleStorage : 1;
1188 /// \brief If \c true, this context may have local lexical declarations
1189 /// that are missing from the lookup table.
1190 mutable bool HasLazyLocalLexicalLookups : 1;
1192 /// \brief If \c true, the external source may have lexical declarations
1193 /// that are missing from the lookup table.
1194 mutable bool HasLazyExternalLexicalLookups : 1;
1196 /// \brief If \c true, lookups should only return identifier from
1197 /// DeclContext scope (for example TranslationUnit). Used in
1198 /// LookupQualifiedName()
1199 mutable bool UseQualifiedLookup : 1;
1201 /// \brief Pointer to the data structure used to lookup declarations
1202 /// within this context (or a DependentStoredDeclsMap if this is a
1203 /// dependent context). We maintain the invariant that, if the map
1204 /// contains an entry for a DeclarationName (and we haven't lazily
1205 /// omitted anything), then it contains all relevant entries for that
1206 /// name (modulo the hasExternalDecls() flag).
1207 mutable StoredDeclsMap *LookupPtr;
1210 /// FirstDecl - The first declaration stored within this declaration
1212 mutable Decl *FirstDecl;
1214 /// LastDecl - The last declaration stored within this declaration
1215 /// context. FIXME: We could probably cache this value somewhere
1216 /// outside of the DeclContext, to reduce the size of DeclContext by
1217 /// another pointer.
1218 mutable Decl *LastDecl;
1220 friend class ExternalASTSource;
1221 friend class ASTDeclReader;
1222 friend class ASTWriter;
1224 /// \brief Build up a chain of declarations.
1226 /// \returns the first/last pair of declarations.
1227 static std::pair<Decl *, Decl *>
1228 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1230 DeclContext(Decl::Kind K)
1231 : DeclKind(K), ExternalLexicalStorage(false),
1232 ExternalVisibleStorage(false),
1233 NeedToReconcileExternalVisibleStorage(false),
1234 HasLazyLocalLexicalLookups(false), HasLazyExternalLexicalLookups(false),
1235 UseQualifiedLookup(false),
1236 LookupPtr(nullptr), FirstDecl(nullptr), LastDecl(nullptr) {}
1241 Decl::Kind getDeclKind() const {
1242 return static_cast<Decl::Kind>(DeclKind);
1244 const char *getDeclKindName() const;
1246 /// getParent - Returns the containing DeclContext.
1247 DeclContext *getParent() {
1248 return cast<Decl>(this)->getDeclContext();
1250 const DeclContext *getParent() const {
1251 return const_cast<DeclContext*>(this)->getParent();
1254 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1255 /// different from getParent, e.g.:
1260 /// struct A::S {}; // getParent() == namespace 'A'
1261 /// // getLexicalParent() == translation unit
1263 DeclContext *getLexicalParent() {
1264 return cast<Decl>(this)->getLexicalDeclContext();
1266 const DeclContext *getLexicalParent() const {
1267 return const_cast<DeclContext*>(this)->getLexicalParent();
1270 DeclContext *getLookupParent();
1272 const DeclContext *getLookupParent() const {
1273 return const_cast<DeclContext*>(this)->getLookupParent();
1276 ASTContext &getParentASTContext() const {
1277 return cast<Decl>(this)->getASTContext();
1280 bool isClosure() const {
1281 return DeclKind == Decl::Block;
1284 bool isObjCContainer() const {
1286 case Decl::ObjCCategory:
1287 case Decl::ObjCCategoryImpl:
1288 case Decl::ObjCImplementation:
1289 case Decl::ObjCInterface:
1290 case Decl::ObjCProtocol:
1296 bool isFunctionOrMethod() const {
1299 case Decl::Captured:
1300 case Decl::ObjCMethod:
1303 return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1307 /// \brief Test whether the context supports looking up names.
1308 bool isLookupContext() const {
1309 return !isFunctionOrMethod() && DeclKind != Decl::LinkageSpec &&
1310 DeclKind != Decl::Export;
1313 bool isFileContext() const {
1314 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1317 bool isTranslationUnit() const {
1318 return DeclKind == Decl::TranslationUnit;
1321 bool isRecord() const {
1322 return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1325 bool isNamespace() const {
1326 return DeclKind == Decl::Namespace;
1329 bool isStdNamespace() const;
1331 bool isInlineNamespace() const;
1333 /// \brief Determines whether this context is dependent on a
1334 /// template parameter.
1335 bool isDependentContext() const;
1337 /// isTransparentContext - Determines whether this context is a
1338 /// "transparent" context, meaning that the members declared in this
1339 /// context are semantically declared in the nearest enclosing
1340 /// non-transparent (opaque) context but are lexically declared in
1341 /// this context. For example, consider the enumerators of an
1342 /// enumeration type:
1348 /// Here, E is a transparent context, so its enumerator (Val1) will
1349 /// appear (semantically) that it is in the same context of E.
1350 /// Examples of transparent contexts include: enumerations (except for
1351 /// C++0x scoped enums), and C++ linkage specifications.
1352 bool isTransparentContext() const;
1354 /// \brief Determines whether this context or some of its ancestors is a
1355 /// linkage specification context that specifies C linkage.
1356 bool isExternCContext() const;
1358 /// \brief Retrieve the nearest enclosing C linkage specification context.
1359 const LinkageSpecDecl *getExternCContext() const;
1361 /// \brief Determines whether this context or some of its ancestors is a
1362 /// linkage specification context that specifies C++ linkage.
1363 bool isExternCXXContext() const;
1365 /// \brief Determine whether this declaration context is equivalent
1366 /// to the declaration context DC.
1367 bool Equals(const DeclContext *DC) const {
1368 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1371 /// \brief Determine whether this declaration context encloses the
1372 /// declaration context DC.
1373 bool Encloses(const DeclContext *DC) const;
1375 /// \brief Find the nearest non-closure ancestor of this context,
1376 /// i.e. the innermost semantic parent of this context which is not
1377 /// a closure. A context may be its own non-closure ancestor.
1378 Decl *getNonClosureAncestor();
1379 const Decl *getNonClosureAncestor() const {
1380 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1383 /// getPrimaryContext - There may be many different
1384 /// declarations of the same entity (including forward declarations
1385 /// of classes, multiple definitions of namespaces, etc.), each with
1386 /// a different set of declarations. This routine returns the
1387 /// "primary" DeclContext structure, which will contain the
1388 /// information needed to perform name lookup into this context.
1389 DeclContext *getPrimaryContext();
1390 const DeclContext *getPrimaryContext() const {
1391 return const_cast<DeclContext*>(this)->getPrimaryContext();
1394 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1395 /// other entities of the same name, or where it is a redeclaration if the
1396 /// two entities are compatible. This skips through transparent contexts.
1397 DeclContext *getRedeclContext();
1398 const DeclContext *getRedeclContext() const {
1399 return const_cast<DeclContext *>(this)->getRedeclContext();
1402 /// \brief Retrieve the nearest enclosing namespace context.
1403 DeclContext *getEnclosingNamespaceContext();
1404 const DeclContext *getEnclosingNamespaceContext() const {
1405 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1408 /// \brief Retrieve the outermost lexically enclosing record context.
1409 RecordDecl *getOuterLexicalRecordContext();
1410 const RecordDecl *getOuterLexicalRecordContext() const {
1411 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1414 /// \brief Test if this context is part of the enclosing namespace set of
1415 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1416 /// isn't a namespace, this is equivalent to Equals().
1418 /// The enclosing namespace set of a namespace is the namespace and, if it is
1419 /// inline, its enclosing namespace, recursively.
1420 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1422 /// \brief Collects all of the declaration contexts that are semantically
1423 /// connected to this declaration context.
1425 /// For declaration contexts that have multiple semantically connected but
1426 /// syntactically distinct contexts, such as C++ namespaces, this routine
1427 /// retrieves the complete set of such declaration contexts in source order.
1428 /// For example, given:
1439 /// The \c Contexts parameter will contain both definitions of N.
1441 /// \param Contexts Will be cleared and set to the set of declaration
1442 /// contexts that are semanticaly connected to this declaration context,
1443 /// in source order, including this context (which may be the only result,
1444 /// for non-namespace contexts).
1445 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1447 /// decl_iterator - Iterates through the declarations stored
1448 /// within this context.
1449 class decl_iterator {
1450 /// Current - The current declaration.
1454 typedef Decl *value_type;
1455 typedef const value_type &reference;
1456 typedef const value_type *pointer;
1457 typedef std::forward_iterator_tag iterator_category;
1458 typedef std::ptrdiff_t difference_type;
1460 decl_iterator() : Current(nullptr) { }
1461 explicit decl_iterator(Decl *C) : Current(C) { }
1463 reference operator*() const { return Current; }
1464 // This doesn't meet the iterator requirements, but it's convenient
1465 value_type operator->() const { return Current; }
1467 decl_iterator& operator++() {
1468 Current = Current->getNextDeclInContext();
1472 decl_iterator operator++(int) {
1473 decl_iterator tmp(*this);
1478 friend bool operator==(decl_iterator x, decl_iterator y) {
1479 return x.Current == y.Current;
1481 friend bool operator!=(decl_iterator x, decl_iterator y) {
1482 return x.Current != y.Current;
1486 typedef llvm::iterator_range<decl_iterator> decl_range;
1488 /// decls_begin/decls_end - Iterate over the declarations stored in
1490 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
1491 decl_iterator decls_begin() const;
1492 decl_iterator decls_end() const { return decl_iterator(); }
1493 bool decls_empty() const;
1495 /// noload_decls_begin/end - Iterate over the declarations stored in this
1496 /// context that are currently loaded; don't attempt to retrieve anything
1497 /// from an external source.
1498 decl_range noload_decls() const {
1499 return decl_range(noload_decls_begin(), noload_decls_end());
1501 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
1502 decl_iterator noload_decls_end() const { return decl_iterator(); }
1504 /// specific_decl_iterator - Iterates over a subrange of
1505 /// declarations stored in a DeclContext, providing only those that
1506 /// are of type SpecificDecl (or a class derived from it). This
1507 /// iterator is used, for example, to provide iteration over just
1508 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1509 template<typename SpecificDecl>
1510 class specific_decl_iterator {
1511 /// Current - The current, underlying declaration iterator, which
1512 /// will either be NULL or will point to a declaration of
1513 /// type SpecificDecl.
1514 DeclContext::decl_iterator Current;
1516 /// SkipToNextDecl - Advances the current position up to the next
1517 /// declaration of type SpecificDecl that also meets the criteria
1518 /// required by Acceptable.
1519 void SkipToNextDecl() {
1520 while (*Current && !isa<SpecificDecl>(*Current))
1525 typedef SpecificDecl *value_type;
1526 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1527 // type) if we ever have a need for them.
1528 typedef void reference;
1529 typedef void pointer;
1530 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1532 typedef std::forward_iterator_tag iterator_category;
1534 specific_decl_iterator() : Current() { }
1536 /// specific_decl_iterator - Construct a new iterator over a
1537 /// subset of the declarations the range [C,
1538 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1539 /// member function of SpecificDecl that should return true for
1540 /// all of the SpecificDecl instances that will be in the subset
1541 /// of iterators. For example, if you want Objective-C instance
1542 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1543 /// &ObjCMethodDecl::isInstanceMethod.
1544 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1548 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1549 // This doesn't meet the iterator requirements, but it's convenient
1550 value_type operator->() const { return **this; }
1552 specific_decl_iterator& operator++() {
1558 specific_decl_iterator operator++(int) {
1559 specific_decl_iterator tmp(*this);
1564 friend bool operator==(const specific_decl_iterator& x,
1565 const specific_decl_iterator& y) {
1566 return x.Current == y.Current;
1569 friend bool operator!=(const specific_decl_iterator& x,
1570 const specific_decl_iterator& y) {
1571 return x.Current != y.Current;
1575 /// \brief Iterates over a filtered subrange of declarations stored
1576 /// in a DeclContext.
1578 /// This iterator visits only those declarations that are of type
1579 /// SpecificDecl (or a class derived from it) and that meet some
1580 /// additional run-time criteria. This iterator is used, for
1581 /// example, to provide access to the instance methods within an
1582 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1583 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1584 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1585 class filtered_decl_iterator {
1586 /// Current - The current, underlying declaration iterator, which
1587 /// will either be NULL or will point to a declaration of
1588 /// type SpecificDecl.
1589 DeclContext::decl_iterator Current;
1591 /// SkipToNextDecl - Advances the current position up to the next
1592 /// declaration of type SpecificDecl that also meets the criteria
1593 /// required by Acceptable.
1594 void SkipToNextDecl() {
1596 (!isa<SpecificDecl>(*Current) ||
1597 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1602 typedef SpecificDecl *value_type;
1603 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1604 // type) if we ever have a need for them.
1605 typedef void reference;
1606 typedef void pointer;
1607 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1609 typedef std::forward_iterator_tag iterator_category;
1611 filtered_decl_iterator() : Current() { }
1613 /// filtered_decl_iterator - Construct a new iterator over a
1614 /// subset of the declarations the range [C,
1615 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1616 /// member function of SpecificDecl that should return true for
1617 /// all of the SpecificDecl instances that will be in the subset
1618 /// of iterators. For example, if you want Objective-C instance
1619 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1620 /// &ObjCMethodDecl::isInstanceMethod.
1621 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1625 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1626 value_type operator->() const { return cast<SpecificDecl>(*Current); }
1628 filtered_decl_iterator& operator++() {
1634 filtered_decl_iterator operator++(int) {
1635 filtered_decl_iterator tmp(*this);
1640 friend bool operator==(const filtered_decl_iterator& x,
1641 const filtered_decl_iterator& y) {
1642 return x.Current == y.Current;
1645 friend bool operator!=(const filtered_decl_iterator& x,
1646 const filtered_decl_iterator& y) {
1647 return x.Current != y.Current;
1651 /// @brief Add the declaration D into this context.
1653 /// This routine should be invoked when the declaration D has first
1654 /// been declared, to place D into the context where it was
1655 /// (lexically) defined. Every declaration must be added to one
1656 /// (and only one!) context, where it can be visited via
1657 /// [decls_begin(), decls_end()). Once a declaration has been added
1658 /// to its lexical context, the corresponding DeclContext owns the
1661 /// If D is also a NamedDecl, it will be made visible within its
1662 /// semantic context via makeDeclVisibleInContext.
1663 void addDecl(Decl *D);
1665 /// @brief Add the declaration D into this context, but suppress
1666 /// searches for external declarations with the same name.
1668 /// Although analogous in function to addDecl, this removes an
1669 /// important check. This is only useful if the Decl is being
1670 /// added in response to an external search; in all other cases,
1671 /// addDecl() is the right function to use.
1672 /// See the ASTImporter for use cases.
1673 void addDeclInternal(Decl *D);
1675 /// @brief Add the declaration D to this context without modifying
1676 /// any lookup tables.
1678 /// This is useful for some operations in dependent contexts where
1679 /// the semantic context might not be dependent; this basically
1680 /// only happens with friends.
1681 void addHiddenDecl(Decl *D);
1683 /// @brief Removes a declaration from this context.
1684 void removeDecl(Decl *D);
1686 /// @brief Checks whether a declaration is in this context.
1687 bool containsDecl(Decl *D) const;
1689 typedef DeclContextLookupResult lookup_result;
1690 typedef lookup_result::iterator lookup_iterator;
1692 /// lookup - Find the declarations (if any) with the given Name in
1693 /// this context. Returns a range of iterators that contains all of
1694 /// the declarations with this name, with object, function, member,
1695 /// and enumerator names preceding any tag name. Note that this
1696 /// routine will not look into parent contexts.
1697 lookup_result lookup(DeclarationName Name) const;
1699 /// \brief Find the declarations with the given name that are visible
1700 /// within this context; don't attempt to retrieve anything from an
1701 /// external source.
1702 lookup_result noload_lookup(DeclarationName Name);
1704 /// \brief A simplistic name lookup mechanism that performs name lookup
1705 /// into this declaration context without consulting the external source.
1707 /// This function should almost never be used, because it subverts the
1708 /// usual relationship between a DeclContext and the external source.
1709 /// See the ASTImporter for the (few, but important) use cases.
1711 /// FIXME: This is very inefficient; replace uses of it with uses of
1713 void localUncachedLookup(DeclarationName Name,
1714 SmallVectorImpl<NamedDecl *> &Results);
1716 /// @brief Makes a declaration visible within this context.
1718 /// This routine makes the declaration D visible to name lookup
1719 /// within this context and, if this is a transparent context,
1720 /// within its parent contexts up to the first enclosing
1721 /// non-transparent context. Making a declaration visible within a
1722 /// context does not transfer ownership of a declaration, and a
1723 /// declaration can be visible in many contexts that aren't its
1724 /// lexical context.
1726 /// If D is a redeclaration of an existing declaration that is
1727 /// visible from this context, as determined by
1728 /// NamedDecl::declarationReplaces, the previous declaration will be
1729 /// replaced with D.
1730 void makeDeclVisibleInContext(NamedDecl *D);
1732 /// all_lookups_iterator - An iterator that provides a view over the results
1733 /// of looking up every possible name.
1734 class all_lookups_iterator;
1736 typedef llvm::iterator_range<all_lookups_iterator> lookups_range;
1738 lookups_range lookups() const;
1739 lookups_range noload_lookups() const;
1741 /// \brief Iterators over all possible lookups within this context.
1742 all_lookups_iterator lookups_begin() const;
1743 all_lookups_iterator lookups_end() const;
1745 /// \brief Iterators over all possible lookups within this context that are
1746 /// currently loaded; don't attempt to retrieve anything from an external
1748 all_lookups_iterator noload_lookups_begin() const;
1749 all_lookups_iterator noload_lookups_end() const;
1751 struct udir_iterator;
1752 typedef llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
1753 std::random_access_iterator_tag,
1754 UsingDirectiveDecl *> udir_iterator_base;
1755 struct udir_iterator : udir_iterator_base {
1756 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
1757 UsingDirectiveDecl *operator*() const;
1760 typedef llvm::iterator_range<udir_iterator> udir_range;
1762 udir_range using_directives() const;
1764 // These are all defined in DependentDiagnostic.h.
1765 class ddiag_iterator;
1766 typedef llvm::iterator_range<DeclContext::ddiag_iterator> ddiag_range;
1768 inline ddiag_range ddiags() const;
1770 // Low-level accessors
1772 /// \brief Mark that there are external lexical declarations that we need
1773 /// to include in our lookup table (and that are not available as external
1774 /// visible lookups). These extra lookup results will be found by walking
1775 /// the lexical declarations of this context. This should be used only if
1776 /// setHasExternalLexicalStorage() has been called on any decl context for
1777 /// which this is the primary context.
1778 void setMustBuildLookupTable() {
1779 assert(this == getPrimaryContext() &&
1780 "should only be called on primary context");
1781 HasLazyExternalLexicalLookups = true;
1784 /// \brief Retrieve the internal representation of the lookup structure.
1785 /// This may omit some names if we are lazily building the structure.
1786 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
1788 /// \brief Ensure the lookup structure is fully-built and return it.
1789 StoredDeclsMap *buildLookup();
1791 /// \brief Whether this DeclContext has external storage containing
1792 /// additional declarations that are lexically in this context.
1793 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1795 /// \brief State whether this DeclContext has external storage for
1796 /// declarations lexically in this context.
1797 void setHasExternalLexicalStorage(bool ES = true) {
1798 ExternalLexicalStorage = ES;
1801 /// \brief Whether this DeclContext has external storage containing
1802 /// additional declarations that are visible in this context.
1803 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1805 /// \brief State whether this DeclContext has external storage for
1806 /// declarations visible in this context.
1807 void setHasExternalVisibleStorage(bool ES = true) {
1808 ExternalVisibleStorage = ES;
1809 if (ES && LookupPtr)
1810 NeedToReconcileExternalVisibleStorage = true;
1813 /// \brief Determine whether the given declaration is stored in the list of
1814 /// declarations lexically within this context.
1815 bool isDeclInLexicalTraversal(const Decl *D) const {
1816 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1820 bool setUseQualifiedLookup(bool use = true) {
1821 bool old_value = UseQualifiedLookup;
1822 UseQualifiedLookup = use;
1826 bool shouldUseQualifiedLookup() const {
1827 return UseQualifiedLookup;
1830 static bool classof(const Decl *D);
1831 static bool classof(const DeclContext *D) { return true; }
1833 void dumpDeclContext() const;
1834 void dumpLookups() const;
1835 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
1836 bool Deserialize = false) const;
1839 void reconcileExternalVisibleStorage() const;
1840 bool LoadLexicalDeclsFromExternalStorage() const;
1842 /// @brief Makes a declaration visible within this context, but
1843 /// suppresses searches for external declarations with the same
1846 /// Analogous to makeDeclVisibleInContext, but for the exclusive
1847 /// use of addDeclInternal().
1848 void makeDeclVisibleInContextInternal(NamedDecl *D);
1850 friend class DependentDiagnostic;
1851 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1853 void buildLookupImpl(DeclContext *DCtx, bool Internal);
1854 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1855 bool Rediscoverable);
1856 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1859 inline bool Decl::isTemplateParameter() const {
1860 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1861 getKind() == TemplateTemplateParm;
1864 // Specialization selected when ToTy is not a known subclass of DeclContext.
1865 template <class ToTy,
1866 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
1867 struct cast_convert_decl_context {
1868 static const ToTy *doit(const DeclContext *Val) {
1869 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1872 static ToTy *doit(DeclContext *Val) {
1873 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1877 // Specialization selected when ToTy is a known subclass of DeclContext.
1878 template <class ToTy>
1879 struct cast_convert_decl_context<ToTy, true> {
1880 static const ToTy *doit(const DeclContext *Val) {
1881 return static_cast<const ToTy*>(Val);
1884 static ToTy *doit(DeclContext *Val) {
1885 return static_cast<ToTy*>(Val);
1894 /// isa<T>(DeclContext*)
1895 template <typename To>
1896 struct isa_impl<To, ::clang::DeclContext> {
1897 static bool doit(const ::clang::DeclContext &Val) {
1898 return To::classofKind(Val.getDeclKind());
1902 /// cast<T>(DeclContext*)
1903 template<class ToTy>
1904 struct cast_convert_val<ToTy,
1905 const ::clang::DeclContext,const ::clang::DeclContext> {
1906 static const ToTy &doit(const ::clang::DeclContext &Val) {
1907 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1910 template<class ToTy>
1911 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
1912 static ToTy &doit(::clang::DeclContext &Val) {
1913 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1916 template<class ToTy>
1917 struct cast_convert_val<ToTy,
1918 const ::clang::DeclContext*, const ::clang::DeclContext*> {
1919 static const ToTy *doit(const ::clang::DeclContext *Val) {
1920 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1923 template<class ToTy>
1924 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
1925 static ToTy *doit(::clang::DeclContext *Val) {
1926 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1930 /// Implement cast_convert_val for Decl -> DeclContext conversions.
1931 template<class FromTy>
1932 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1933 static ::clang::DeclContext &doit(const FromTy &Val) {
1934 return *FromTy::castToDeclContext(&Val);
1938 template<class FromTy>
1939 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1940 static ::clang::DeclContext *doit(const FromTy *Val) {
1941 return FromTy::castToDeclContext(Val);
1945 template<class FromTy>
1946 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1947 static const ::clang::DeclContext &doit(const FromTy &Val) {
1948 return *FromTy::castToDeclContext(&Val);
1952 template<class FromTy>
1953 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1954 static const ::clang::DeclContext *doit(const FromTy *Val) {
1955 return FromTy::castToDeclContext(Val);
1959 } // end namespace llvm