1 //===-- DeclBase.h - Base Classes for representing declarations -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Decl and DeclContext interfaces.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_DECLBASE_H
15 #define LLVM_CLANG_AST_DECLBASE_H
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/DeclarationName.h"
19 #include "clang/Basic/Specifiers.h"
20 #include "llvm/ADT/PointerUnion.h"
21 #include "llvm/ADT/iterator.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/PrettyStackTrace.h"
27 class ASTMutationListener;
32 class DeclarationName;
33 class DependentDiagnostic;
37 enum Linkage : unsigned char;
38 class LinkageComputer;
39 class LinkageSpecDecl;
43 class ObjCCategoryDecl;
44 class ObjCCategoryImplDecl;
45 class ObjCContainerDecl;
47 class ObjCImplementationDecl;
48 class ObjCInterfaceDecl;
50 class ObjCProtocolDecl;
51 struct PrintingPolicy;
55 class TranslationUnitDecl;
56 class UsingDirectiveDecl;
61 /// \brief Captures the result of checking the availability of a
63 enum AvailabilityResult {
70 /// Decl - This represents one declaration (or definition), e.g. a variable,
71 /// typedef, function, struct, etc.
75 /// \brief Lists the kind of concrete classes of Decl.
77 #define DECL(DERIVED, BASE) DERIVED,
78 #define ABSTRACT_DECL(DECL)
79 #define DECL_RANGE(BASE, START, END) \
80 first##BASE = START, last##BASE = END,
81 #define LAST_DECL_RANGE(BASE, START, END) \
82 first##BASE = START, last##BASE = END
83 #include "clang/AST/DeclNodes.inc"
86 /// \brief A placeholder type used to construct an empty shell of a
87 /// decl-derived type that will be filled in later (e.g., by some
88 /// deserialization method).
89 struct EmptyShell { };
91 /// IdentifierNamespace - The different namespaces in which
92 /// declarations may appear. According to C99 6.2.3, there are
93 /// four namespaces, labels, tags, members and ordinary
94 /// identifiers. C++ describes lookup completely differently:
95 /// certain lookups merely "ignore" certain kinds of declarations,
96 /// usually based on whether the declaration is of a type, etc.
98 /// These are meant as bitmasks, so that searches in
99 /// C++ can look into the "tag" namespace during ordinary lookup.
101 /// Decl currently provides 15 bits of IDNS bits.
102 enum IdentifierNamespace {
103 /// Labels, declared with 'x:' and referenced with 'goto x'.
106 /// Tags, declared with 'struct foo;' and referenced with
107 /// 'struct foo'. All tags are also types. This is what
108 /// elaborated-type-specifiers look for in C.
111 /// Types, declared with 'struct foo', typedefs, etc.
112 /// This is what elaborated-type-specifiers look for in C++,
113 /// but note that it's ill-formed to find a non-tag.
116 /// Members, declared with object declarations within tag
117 /// definitions. In C, these can only be found by "qualified"
118 /// lookup in member expressions. In C++, they're found by
120 IDNS_Member = 0x0008,
122 /// Namespaces, declared with 'namespace foo {}'.
123 /// Lookup for nested-name-specifiers find these.
124 IDNS_Namespace = 0x0010,
126 /// Ordinary names. In C, everything that's not a label, tag,
127 /// or member ends up here.
128 IDNS_Ordinary = 0x0020,
130 /// Objective C \@protocol.
131 IDNS_ObjCProtocol = 0x0040,
133 /// This declaration is a friend function. A friend function
134 /// declaration is always in this namespace but may also be in
135 /// IDNS_Ordinary if it was previously declared.
136 IDNS_OrdinaryFriend = 0x0080,
138 /// This declaration is a friend class. A friend class
139 /// declaration is always in this namespace but may also be in
140 /// IDNS_Tag|IDNS_Type if it was previously declared.
141 IDNS_TagFriend = 0x0100,
143 /// This declaration is a using declaration. A using declaration
144 /// *introduces* a number of other declarations into the current
145 /// scope, and those declarations use the IDNS of their targets,
146 /// but the actual using declarations go in this namespace.
149 /// This declaration is a C++ operator declared in a non-class
150 /// context. All such operators are also in IDNS_Ordinary.
151 /// C++ lexical operator lookup looks for these.
152 IDNS_NonMemberOperator = 0x0400,
154 /// This declaration is a function-local extern declaration of a
155 /// variable or function. This may also be IDNS_Ordinary if it
156 /// has been declared outside any function.
157 IDNS_LocalExtern = 0x0800
160 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
161 /// parameter types in method declarations. Other than remembering
162 /// them and mangling them into the method's signature string, these
163 /// are ignored by the compiler; they are consumed by certain
164 /// remote-messaging frameworks.
166 /// in, inout, and out are mutually exclusive and apply only to
167 /// method parameters. bycopy and byref are mutually exclusive and
168 /// apply only to method parameters (?). oneway applies only to
169 /// results. All of these expect their corresponding parameter to
170 /// have a particular type. None of this is currently enforced by
173 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
174 enum ObjCDeclQualifier {
179 OBJC_TQ_Bycopy = 0x8,
180 OBJC_TQ_Byref = 0x10,
181 OBJC_TQ_Oneway = 0x20,
183 /// The nullability qualifier is set when the nullability of the
184 /// result or parameter was expressed via a context-sensitive
186 OBJC_TQ_CSNullability = 0x40
190 // Enumeration values used in the bits stored in NextInContextAndBits.
192 /// \brief Whether this declaration is a top-level declaration (function,
193 /// global variable, etc.) that is lexically inside an objc container
195 TopLevelDeclInObjCContainerFlag = 0x01,
197 /// \brief Whether this declaration is private to the module in which it was
199 ModulePrivateFlag = 0x02
202 /// \brief The next declaration within the same lexical
203 /// DeclContext. These pointers form the linked list that is
204 /// traversed via DeclContext's decls_begin()/decls_end().
206 /// The extra two bits are used for the TopLevelDeclInObjCContainer and
207 /// ModulePrivate bits.
208 llvm::PointerIntPair<Decl *, 2, unsigned> NextInContextAndBits;
211 friend class DeclContext;
214 DeclContext *SemanticDC;
215 DeclContext *LexicalDC;
219 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
220 /// For declarations that don't contain C++ scope specifiers, it contains
221 /// the DeclContext where the Decl was declared.
222 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
223 /// with the context where it semantically belongs (SemanticDC) and the
224 /// context where it was lexically declared (LexicalDC).
228 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
230 /// void A::f(); // SemanticDC == namespace 'A'
231 /// // LexicalDC == global namespace
232 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
234 inline bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
235 inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
236 inline MultipleDC *getMultipleDC() const {
237 return DeclCtx.get<MultipleDC*>();
239 inline DeclContext *getSemanticDC() const {
240 return DeclCtx.get<DeclContext*>();
243 /// Loc - The location of this decl.
246 /// DeclKind - This indicates which class this is.
247 unsigned DeclKind : 8;
249 /// InvalidDecl - This indicates a semantic error occurred.
250 unsigned InvalidDecl : 1;
252 /// HasAttrs - This indicates whether the decl has attributes or not.
253 unsigned HasAttrs : 1;
255 /// Implicit - Whether this declaration was implicitly generated by
256 /// the implementation rather than explicitly written by the user.
257 unsigned Implicit : 1;
259 /// \brief Whether this declaration was "used", meaning that a definition is
263 /// \brief Whether this declaration was "referenced".
264 /// The difference with 'Used' is whether the reference appears in a
265 /// evaluated context or not, e.g. functions used in uninstantiated templates
266 /// are regarded as "referenced" but not "used".
267 unsigned Referenced : 1;
269 /// \brief Whether statistic collection is enabled.
270 static bool StatisticsEnabled;
273 /// Access - Used by C++ decls for the access specifier.
274 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
276 friend class CXXClassMemberWrapper;
278 /// \brief Whether this declaration was loaded from an AST file.
279 unsigned FromASTFile : 1;
281 /// \brief Whether this declaration is hidden from normal name lookup, e.g.,
282 /// because it is was loaded from an AST file is either module-private or
283 /// because its submodule has not been made visible.
286 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
287 unsigned IdentifierNamespace : 12;
289 /// \brief If 0, we have not computed the linkage of this declaration.
290 /// Otherwise, it is the linkage + 1.
291 mutable unsigned CacheValidAndLinkage : 3;
293 friend class ASTDeclWriter;
294 friend class ASTDeclReader;
295 friend class ASTReader;
296 friend class LinkageComputer;
298 template<typename decl_type> friend class Redeclarable;
300 /// \brief Allocate memory for a deserialized declaration.
302 /// This routine must be used to allocate memory for any declaration that is
303 /// deserialized from a module file.
305 /// \param Size The size of the allocated object.
306 /// \param Ctx The context in which we will allocate memory.
307 /// \param ID The global ID of the deserialized declaration.
308 /// \param Extra The amount of extra space to allocate after the object.
309 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
310 std::size_t Extra = 0);
312 /// \brief Allocate memory for a non-deserialized declaration.
313 void *operator new(std::size_t Size, const ASTContext &Ctx,
314 DeclContext *Parent, std::size_t Extra = 0);
317 bool AccessDeclContextSanity() const;
321 Decl(Kind DK, DeclContext *DC, SourceLocation L)
322 : NextInContextAndBits(), DeclCtx(DC),
323 Loc(L), DeclKind(DK), InvalidDecl(0),
324 HasAttrs(false), Implicit(false), Used(false), Referenced(false),
325 Access(AS_none), FromASTFile(0), Hidden(DC && cast<Decl>(DC)->Hidden),
326 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
327 CacheValidAndLinkage(0)
329 if (StatisticsEnabled) add(DK);
332 Decl(Kind DK, EmptyShell Empty)
333 : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0),
334 HasAttrs(false), Implicit(false), Used(false), Referenced(false),
335 Access(AS_none), FromASTFile(0), Hidden(0),
336 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
337 CacheValidAndLinkage(0)
339 if (StatisticsEnabled) add(DK);
344 /// \brief Update a potentially out-of-date declaration.
345 void updateOutOfDate(IdentifierInfo &II) const;
347 Linkage getCachedLinkage() const {
348 return Linkage(CacheValidAndLinkage - 1);
351 void setCachedLinkage(Linkage L) const {
352 CacheValidAndLinkage = L + 1;
355 bool hasCachedLinkage() const {
356 return CacheValidAndLinkage;
361 /// \brief Source range that this declaration covers.
362 virtual SourceRange getSourceRange() const LLVM_READONLY {
363 return SourceRange(getLocation(), getLocation());
365 SourceLocation getLocStart() const LLVM_READONLY {
366 return getSourceRange().getBegin();
368 SourceLocation getLocEnd() const LLVM_READONLY {
369 return getSourceRange().getEnd();
372 SourceLocation getLocation() const { return Loc; }
373 void setLocation(SourceLocation L) { Loc = L; }
375 Kind getKind() const { return static_cast<Kind>(DeclKind); }
376 const char *getDeclKindName() const;
378 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
379 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
381 DeclContext *getDeclContext() {
383 return getSemanticDC();
384 return getMultipleDC()->SemanticDC;
386 const DeclContext *getDeclContext() const {
387 return const_cast<Decl*>(this)->getDeclContext();
390 /// Find the innermost non-closure ancestor of this declaration,
391 /// walking up through blocks, lambdas, etc. If that ancestor is
392 /// not a code context (!isFunctionOrMethod()), returns null.
394 /// A declaration may be its own non-closure context.
395 Decl *getNonClosureContext();
396 const Decl *getNonClosureContext() const {
397 return const_cast<Decl*>(this)->getNonClosureContext();
400 TranslationUnitDecl *getTranslationUnitDecl();
401 const TranslationUnitDecl *getTranslationUnitDecl() const {
402 return const_cast<Decl*>(this)->getTranslationUnitDecl();
405 bool isInAnonymousNamespace() const;
407 bool isInStdNamespace() const;
409 ASTContext &getASTContext() const LLVM_READONLY;
411 void setAccess(AccessSpecifier AS) {
413 assert(AccessDeclContextSanity());
416 AccessSpecifier getAccess() const {
417 assert(AccessDeclContextSanity());
418 return AccessSpecifier(Access);
421 /// \brief Retrieve the access specifier for this declaration, even though
422 /// it may not yet have been properly set.
423 AccessSpecifier getAccessUnsafe() const {
424 return AccessSpecifier(Access);
427 bool hasAttrs() const { return HasAttrs; }
428 void setAttrs(const AttrVec& Attrs) {
429 return setAttrsImpl(Attrs, getASTContext());
431 AttrVec &getAttrs() {
432 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
434 const AttrVec &getAttrs() const;
437 void addAttr(Attr *A) {
439 getAttrs().push_back(A);
441 setAttrs(AttrVec(1, A));
444 typedef AttrVec::const_iterator attr_iterator;
445 typedef llvm::iterator_range<attr_iterator> attr_range;
447 attr_range attrs() const {
448 return attr_range(attr_begin(), attr_end());
451 attr_iterator attr_begin() const {
452 return hasAttrs() ? getAttrs().begin() : nullptr;
454 attr_iterator attr_end() const {
455 return hasAttrs() ? getAttrs().end() : nullptr;
458 template <typename T>
460 if (!HasAttrs) return;
462 AttrVec &Vec = getAttrs();
463 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
469 template <typename T>
470 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
471 return llvm::iterator_range<specific_attr_iterator<T>>(
472 specific_attr_begin<T>(), specific_attr_end<T>());
475 template <typename T>
476 specific_attr_iterator<T> specific_attr_begin() const {
477 return specific_attr_iterator<T>(attr_begin());
479 template <typename T>
480 specific_attr_iterator<T> specific_attr_end() const {
481 return specific_attr_iterator<T>(attr_end());
484 template<typename T> T *getAttr() const {
485 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
487 template<typename T> bool hasAttr() const {
488 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
491 /// getMaxAlignment - return the maximum alignment specified by attributes
492 /// on this decl, 0 if there are none.
493 unsigned getMaxAlignment() const;
495 /// setInvalidDecl - Indicates the Decl had a semantic error. This
496 /// allows for graceful error recovery.
497 void setInvalidDecl(bool Invalid = true);
498 bool isInvalidDecl() const { return (bool) InvalidDecl; }
500 /// isImplicit - Indicates whether the declaration was implicitly
501 /// generated by the implementation. If false, this declaration
502 /// was written explicitly in the source code.
503 bool isImplicit() const { return Implicit; }
504 void setImplicit(bool I = true) { Implicit = I; }
506 /// \brief Whether this declaration was used, meaning that a definition
509 /// \param CheckUsedAttr When true, also consider the "used" attribute
510 /// (in addition to the "used" bit set by \c setUsed()) when determining
511 /// whether the function is used.
512 bool isUsed(bool CheckUsedAttr = true) const;
514 /// \brief Set whether the declaration is used, in the sense of odr-use.
516 /// This should only be used immediately after creating a declaration.
517 void setIsUsed() { Used = true; }
519 /// \brief Mark the declaration used, in the sense of odr-use.
521 /// This notifies any mutation listeners in addition to setting a bit
522 /// indicating the declaration is used.
523 void markUsed(ASTContext &C);
525 /// \brief Whether any declaration of this entity was referenced.
526 bool isReferenced() const;
528 /// \brief Whether this declaration was referenced. This should not be relied
529 /// upon for anything other than debugging.
530 bool isThisDeclarationReferenced() const { return Referenced; }
532 void setReferenced(bool R = true) { Referenced = R; }
534 /// \brief Whether this declaration is a top-level declaration (function,
535 /// global variable, etc.) that is lexically inside an objc container
537 bool isTopLevelDeclInObjCContainer() const {
538 return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag;
541 void setTopLevelDeclInObjCContainer(bool V = true) {
542 unsigned Bits = NextInContextAndBits.getInt();
544 Bits |= TopLevelDeclInObjCContainerFlag;
546 Bits &= ~TopLevelDeclInObjCContainerFlag;
547 NextInContextAndBits.setInt(Bits);
550 /// \brief Whether this declaration was marked as being private to the
551 /// module in which it was defined.
552 bool isModulePrivate() const {
553 return NextInContextAndBits.getInt() & ModulePrivateFlag;
557 /// \brief Specify whether this declaration was marked as being private
558 /// to the module in which it was defined.
559 void setModulePrivate(bool MP = true) {
560 unsigned Bits = NextInContextAndBits.getInt();
562 Bits |= ModulePrivateFlag;
564 Bits &= ~ModulePrivateFlag;
565 NextInContextAndBits.setInt(Bits);
568 /// \brief Set the owning module ID.
569 void setOwningModuleID(unsigned ID) {
570 assert(isFromASTFile() && "Only works on a deserialized declaration");
571 *((unsigned*)this - 2) = ID;
576 /// \brief Determine the availability of the given declaration.
578 /// This routine will determine the most restrictive availability of
579 /// the given declaration (e.g., preferring 'unavailable' to
582 /// \param Message If non-NULL and the result is not \c
583 /// AR_Available, will be set to a (possibly empty) message
584 /// describing why the declaration has not been introduced, is
585 /// deprecated, or is unavailable.
586 AvailabilityResult getAvailability(std::string *Message = nullptr) const;
588 /// \brief Determine whether this declaration is marked 'deprecated'.
590 /// \param Message If non-NULL and the declaration is deprecated,
591 /// this will be set to the message describing why the declaration
592 /// was deprecated (which may be empty).
593 bool isDeprecated(std::string *Message = nullptr) const {
594 return getAvailability(Message) == AR_Deprecated;
597 /// \brief Determine whether this declaration is marked 'unavailable'.
599 /// \param Message If non-NULL and the declaration is unavailable,
600 /// this will be set to the message describing why the declaration
601 /// was made unavailable (which may be empty).
602 bool isUnavailable(std::string *Message = nullptr) const {
603 return getAvailability(Message) == AR_Unavailable;
606 /// \brief Determine whether this is a weak-imported symbol.
608 /// Weak-imported symbols are typically marked with the
609 /// 'weak_import' attribute, but may also be marked with an
610 /// 'availability' attribute where we're targing a platform prior to
611 /// the introduction of this feature.
612 bool isWeakImported() const;
614 /// \brief Determines whether this symbol can be weak-imported,
615 /// e.g., whether it would be well-formed to add the weak_import
618 /// \param IsDefinition Set to \c true to indicate that this
619 /// declaration cannot be weak-imported because it has a definition.
620 bool canBeWeakImported(bool &IsDefinition) const;
622 /// \brief Determine whether this declaration came from an AST file (such as
623 /// a precompiled header or module) rather than having been parsed.
624 bool isFromASTFile() const { return FromASTFile; }
626 /// \brief Retrieve the global declaration ID associated with this
627 /// declaration, which specifies where in the
628 unsigned getGlobalID() const {
630 return *((const unsigned*)this - 1);
634 /// \brief Retrieve the global ID of the module that owns this particular
636 unsigned getOwningModuleID() const {
638 return *((const unsigned*)this - 2);
644 Module *getOwningModuleSlow() const;
646 bool hasLocalOwningModuleStorage() const;
649 /// \brief Get the imported owning module, if this decl is from an imported
650 /// (non-local) module.
651 Module *getImportedOwningModule() const {
652 if (!isFromASTFile())
655 return getOwningModuleSlow();
658 /// \brief Get the local owning module, if known. Returns nullptr if owner is
659 /// not yet known or declaration is not from a module.
660 Module *getLocalOwningModule() const {
661 if (isFromASTFile() || !Hidden)
663 return reinterpret_cast<Module *const *>(this)[-1];
665 void setLocalOwningModule(Module *M) {
666 assert(!isFromASTFile() && Hidden && hasLocalOwningModuleStorage() &&
667 "should not have a cached owning module");
668 reinterpret_cast<Module **>(this)[-1] = M;
671 unsigned getIdentifierNamespace() const {
672 return IdentifierNamespace;
674 bool isInIdentifierNamespace(unsigned NS) const {
675 return getIdentifierNamespace() & NS;
677 static unsigned getIdentifierNamespaceForKind(Kind DK);
679 bool hasTagIdentifierNamespace() const {
680 return isTagIdentifierNamespace(getIdentifierNamespace());
682 static bool isTagIdentifierNamespace(unsigned NS) {
683 // TagDecls have Tag and Type set and may also have TagFriend.
684 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
687 /// getLexicalDeclContext - The declaration context where this Decl was
688 /// lexically declared (LexicalDC). May be different from
689 /// getDeclContext() (SemanticDC).
693 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
695 /// void A::f(); // SemanticDC == namespace 'A'
696 /// // LexicalDC == global namespace
697 DeclContext *getLexicalDeclContext() {
699 return getSemanticDC();
700 return getMultipleDC()->LexicalDC;
702 const DeclContext *getLexicalDeclContext() const {
703 return const_cast<Decl*>(this)->getLexicalDeclContext();
706 /// Determine whether this declaration is declared out of line (outside its
707 /// semantic context).
708 virtual bool isOutOfLine() const;
710 /// setDeclContext - Set both the semantic and lexical DeclContext
712 void setDeclContext(DeclContext *DC);
714 void setLexicalDeclContext(DeclContext *DC);
716 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
717 /// scoped decl is defined outside the current function or method. This is
718 /// roughly global variables and functions, but also handles enums (which
719 /// could be defined inside or outside a function etc).
720 bool isDefinedOutsideFunctionOrMethod() const {
721 return getParentFunctionOrMethod() == nullptr;
724 /// \brief If this decl is defined inside a function/method/block it returns
725 /// the corresponding DeclContext, otherwise it returns null.
726 const DeclContext *getParentFunctionOrMethod() const;
727 DeclContext *getParentFunctionOrMethod() {
728 return const_cast<DeclContext*>(
729 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
732 /// \brief Retrieves the "canonical" declaration of the given declaration.
733 virtual Decl *getCanonicalDecl() { return this; }
734 const Decl *getCanonicalDecl() const {
735 return const_cast<Decl*>(this)->getCanonicalDecl();
738 /// \brief Whether this particular Decl is a canonical one.
739 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
742 /// \brief Returns the next redeclaration or itself if this is the only decl.
744 /// Decl subclasses that can be redeclared should override this method so that
745 /// Decl::redecl_iterator can iterate over them.
746 virtual Decl *getNextRedeclarationImpl() { return this; }
748 /// \brief Implementation of getPreviousDecl(), to be overridden by any
749 /// subclass that has a redeclaration chain.
750 virtual Decl *getPreviousDeclImpl() { return nullptr; }
752 /// \brief Implementation of getMostRecentDecl(), to be overridden by any
753 /// subclass that has a redeclaration chain.
754 virtual Decl *getMostRecentDeclImpl() { return this; }
757 /// \brief Iterates through all the redeclarations of the same decl.
758 class redecl_iterator {
759 /// Current - The current declaration.
764 typedef Decl *value_type;
765 typedef const value_type &reference;
766 typedef const value_type *pointer;
767 typedef std::forward_iterator_tag iterator_category;
768 typedef std::ptrdiff_t difference_type;
770 redecl_iterator() : Current(nullptr) { }
771 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
773 reference operator*() const { return Current; }
774 value_type operator->() const { return Current; }
776 redecl_iterator& operator++() {
777 assert(Current && "Advancing while iterator has reached end");
778 // Get either previous decl or latest decl.
779 Decl *Next = Current->getNextRedeclarationImpl();
780 assert(Next && "Should return next redeclaration or itself, never null!");
781 Current = (Next != Starter) ? Next : nullptr;
785 redecl_iterator operator++(int) {
786 redecl_iterator tmp(*this);
791 friend bool operator==(redecl_iterator x, redecl_iterator y) {
792 return x.Current == y.Current;
794 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
795 return x.Current != y.Current;
799 typedef llvm::iterator_range<redecl_iterator> redecl_range;
801 /// \brief Returns an iterator range for all the redeclarations of the same
802 /// decl. It will iterate at least once (when this decl is the only one).
803 redecl_range redecls() const {
804 return redecl_range(redecls_begin(), redecls_end());
807 redecl_iterator redecls_begin() const {
808 return redecl_iterator(const_cast<Decl *>(this));
810 redecl_iterator redecls_end() const { return redecl_iterator(); }
812 /// \brief Retrieve the previous declaration that declares the same entity
813 /// as this declaration, or NULL if there is no previous declaration.
814 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
816 /// \brief Retrieve the most recent declaration that declares the same entity
817 /// as this declaration, or NULL if there is no previous declaration.
818 const Decl *getPreviousDecl() const {
819 return const_cast<Decl *>(this)->getPreviousDeclImpl();
822 /// \brief True if this is the first declaration in its redeclaration chain.
823 bool isFirstDecl() const {
824 return getPreviousDecl() == nullptr;
827 /// \brief Retrieve the most recent declaration that declares the same entity
828 /// as this declaration (which may be this declaration).
829 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
831 /// \brief Retrieve the most recent declaration that declares the same entity
832 /// as this declaration (which may be this declaration).
833 const Decl *getMostRecentDecl() const {
834 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
837 /// getBody - If this Decl represents a declaration for a body of code,
838 /// such as a function or method definition, this method returns the
839 /// top-level Stmt* of that body. Otherwise this method returns null.
840 virtual Stmt* getBody() const { return nullptr; }
842 /// \brief Returns true if this \c Decl represents a declaration for a body of
843 /// code, such as a function or method definition.
844 /// Note that \c hasBody can also return true if any redeclaration of this
845 /// \c Decl represents a declaration for a body of code.
846 virtual bool hasBody() const { return getBody() != nullptr; }
848 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
849 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
850 SourceLocation getBodyRBrace() const;
852 // global temp stats (until we have a per-module visitor)
853 static void add(Kind k);
854 static void EnableStatistics();
855 static void PrintStats();
857 /// isTemplateParameter - Determines whether this declaration is a
858 /// template parameter.
859 bool isTemplateParameter() const;
861 /// isTemplateParameter - Determines whether this declaration is a
862 /// template parameter pack.
863 bool isTemplateParameterPack() const;
865 /// \brief Whether this declaration is a parameter pack.
866 bool isParameterPack() const;
868 /// \brief returns true if this declaration is a template
869 bool isTemplateDecl() const;
871 /// \brief Whether this declaration is a function or function template.
872 bool isFunctionOrFunctionTemplate() const {
873 return (DeclKind >= Decl::firstFunction &&
874 DeclKind <= Decl::lastFunction) ||
875 DeclKind == FunctionTemplate;
878 /// \brief Returns the function itself, or the templated function if this is a
879 /// function template.
880 FunctionDecl *getAsFunction() LLVM_READONLY;
882 const FunctionDecl *getAsFunction() const {
883 return const_cast<Decl *>(this)->getAsFunction();
886 /// \brief Changes the namespace of this declaration to reflect that it's
887 /// a function-local extern declaration.
889 /// These declarations appear in the lexical context of the extern
890 /// declaration, but in the semantic context of the enclosing namespace
892 void setLocalExternDecl() {
893 assert((IdentifierNamespace == IDNS_Ordinary ||
894 IdentifierNamespace == IDNS_OrdinaryFriend) &&
895 "namespace is not ordinary");
897 Decl *Prev = getPreviousDecl();
898 IdentifierNamespace &= ~IDNS_Ordinary;
900 IdentifierNamespace |= IDNS_LocalExtern;
901 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
902 IdentifierNamespace |= IDNS_Ordinary;
905 /// \brief Determine whether this is a block-scope declaration with linkage.
906 /// This will either be a local variable declaration declared 'extern', or a
907 /// local function declaration.
908 bool isLocalExternDecl() {
909 return IdentifierNamespace & IDNS_LocalExtern;
912 /// \brief Changes the namespace of this declaration to reflect that it's
913 /// the object of a friend declaration.
915 /// These declarations appear in the lexical context of the friending
916 /// class, but in the semantic context of the actual entity. This property
917 /// applies only to a specific decl object; other redeclarations of the
918 /// same entity may not (and probably don't) share this property.
919 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
920 unsigned OldNS = IdentifierNamespace;
921 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
922 IDNS_TagFriend | IDNS_OrdinaryFriend |
923 IDNS_LocalExtern)) &&
924 "namespace includes neither ordinary nor tag");
925 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
926 IDNS_TagFriend | IDNS_OrdinaryFriend |
927 IDNS_LocalExtern)) &&
928 "namespace includes other than ordinary or tag");
930 Decl *Prev = getPreviousDecl();
931 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
933 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
934 IdentifierNamespace |= IDNS_TagFriend;
935 if (PerformFriendInjection ||
936 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
937 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
940 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | IDNS_LocalExtern)) {
941 IdentifierNamespace |= IDNS_OrdinaryFriend;
942 if (PerformFriendInjection ||
943 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
944 IdentifierNamespace |= IDNS_Ordinary;
948 enum FriendObjectKind {
949 FOK_None, ///< Not a friend object.
950 FOK_Declared, ///< A friend of a previously-declared entity.
951 FOK_Undeclared ///< A friend of a previously-undeclared entity.
954 /// \brief Determines whether this declaration is the object of a
955 /// friend declaration and, if so, what kind.
957 /// There is currently no direct way to find the associated FriendDecl.
958 FriendObjectKind getFriendObjectKind() const {
960 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
961 if (!mask) return FOK_None;
962 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
966 /// Specifies that this declaration is a C++ overloaded non-member.
967 void setNonMemberOperator() {
968 assert(getKind() == Function || getKind() == FunctionTemplate);
969 assert((IdentifierNamespace & IDNS_Ordinary) &&
970 "visible non-member operators should be in ordinary namespace");
971 IdentifierNamespace |= IDNS_NonMemberOperator;
974 static bool classofKind(Kind K) { return true; }
975 static DeclContext *castToDeclContext(const Decl *);
976 static Decl *castFromDeclContext(const DeclContext *);
978 void print(raw_ostream &Out, unsigned Indentation = 0,
979 bool PrintInstantiation = false) const;
980 void print(raw_ostream &Out, const PrintingPolicy &Policy,
981 unsigned Indentation = 0, bool PrintInstantiation = false) const;
982 static void printGroup(Decl** Begin, unsigned NumDecls,
983 raw_ostream &Out, const PrintingPolicy &Policy,
984 unsigned Indentation = 0);
985 // Debuggers don't usually respect default arguments.
987 // Same as dump(), but forces color printing.
988 void dumpColor() const;
989 void dump(raw_ostream &Out) const;
991 /// \brief Looks through the Decl's underlying type to extract a FunctionType
992 /// when possible. Will return null if the type underlying the Decl does not
993 /// have a FunctionType.
994 const FunctionType *getFunctionType(bool BlocksToo = true) const;
997 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
998 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1002 ASTMutationListener *getASTMutationListener() const;
1005 /// \brief Determine whether two declarations declare the same entity.
1006 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1013 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1016 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1017 /// doing something to a specific decl.
1018 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1019 const Decl *TheDecl;
1022 const char *Message;
1024 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1025 SourceManager &sm, const char *Msg)
1026 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1028 void print(raw_ostream &OS) const override;
1031 /// \brief The results of name lookup within a DeclContext. This is either a
1032 /// single result (with no stable storage) or a collection of results (with
1033 /// stable storage provided by the lookup table).
1034 class DeclContextLookupResult {
1035 typedef ArrayRef<NamedDecl *> ResultTy;
1037 // If there is only one lookup result, it would be invalidated by
1038 // reallocations of the name table, so store it separately.
1041 static NamedDecl *const SingleElementDummyList;
1044 DeclContextLookupResult() : Result(), Single() {}
1045 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1046 : Result(Result), Single() {}
1047 DeclContextLookupResult(NamedDecl *Single)
1048 : Result(SingleElementDummyList), Single(Single) {}
1051 typedef llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1052 std::random_access_iterator_tag,
1053 NamedDecl *const> IteratorBase;
1054 class iterator : public IteratorBase {
1055 value_type SingleElement;
1058 iterator() : IteratorBase(), SingleElement() {}
1059 explicit iterator(pointer Pos, value_type Single = nullptr)
1060 : IteratorBase(Pos), SingleElement(Single) {}
1062 reference operator*() const {
1063 return SingleElement ? SingleElement : IteratorBase::operator*();
1066 typedef iterator const_iterator;
1067 typedef iterator::pointer pointer;
1068 typedef iterator::reference reference;
1070 iterator begin() const { return iterator(Result.begin(), Single); }
1071 iterator end() const { return iterator(Result.end(), Single); }
1073 bool empty() const { return Result.empty(); }
1074 pointer data() const { return Single ? &Single : Result.data(); }
1075 size_t size() const { return Single ? 1 : Result.size(); }
1076 reference front() const { return Single ? Single : Result.front(); }
1077 reference back() const { return Single ? Single : Result.back(); }
1078 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1080 // FIXME: Remove this from the interface
1081 DeclContextLookupResult slice(size_t N) const {
1082 DeclContextLookupResult Sliced = Result.slice(N);
1083 Sliced.Single = Single;
1088 /// DeclContext - This is used only as base class of specific decl types that
1089 /// can act as declaration contexts. These decls are (only the top classes
1090 /// that directly derive from DeclContext are mentioned, not their subclasses):
1092 /// TranslationUnitDecl
1097 /// ObjCContainerDecl
1102 /// DeclKind - This indicates which class this is.
1103 unsigned DeclKind : 8;
1105 /// \brief Whether this declaration context also has some external
1106 /// storage that contains additional declarations that are lexically
1107 /// part of this context.
1108 mutable bool ExternalLexicalStorage : 1;
1110 /// \brief Whether this declaration context also has some external
1111 /// storage that contains additional declarations that are visible
1112 /// in this context.
1113 mutable bool ExternalVisibleStorage : 1;
1115 /// \brief Whether this declaration context has had external visible
1116 /// storage added since the last lookup. In this case, \c LookupPtr's
1117 /// invariant may not hold and needs to be fixed before we perform
1119 mutable bool NeedToReconcileExternalVisibleStorage : 1;
1121 /// \brief If \c true, this context may have local lexical declarations
1122 /// that are missing from the lookup table.
1123 mutable bool HasLazyLocalLexicalLookups : 1;
1125 /// \brief If \c true, the external source may have lexical declarations
1126 /// that are missing from the lookup table.
1127 mutable bool HasLazyExternalLexicalLookups : 1;
1129 /// \brief Pointer to the data structure used to lookup declarations
1130 /// within this context (or a DependentStoredDeclsMap if this is a
1131 /// dependent context). We maintain the invariant that, if the map
1132 /// contains an entry for a DeclarationName (and we haven't lazily
1133 /// omitted anything), then it contains all relevant entries for that
1134 /// name (modulo the hasExternalDecls() flag).
1135 mutable StoredDeclsMap *LookupPtr;
1138 /// FirstDecl - The first declaration stored within this declaration
1140 mutable Decl *FirstDecl;
1142 /// LastDecl - The last declaration stored within this declaration
1143 /// context. FIXME: We could probably cache this value somewhere
1144 /// outside of the DeclContext, to reduce the size of DeclContext by
1145 /// another pointer.
1146 mutable Decl *LastDecl;
1148 friend class ExternalASTSource;
1149 friend class ASTDeclReader;
1150 friend class ASTWriter;
1152 /// \brief Build up a chain of declarations.
1154 /// \returns the first/last pair of declarations.
1155 static std::pair<Decl *, Decl *>
1156 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1158 DeclContext(Decl::Kind K)
1159 : DeclKind(K), ExternalLexicalStorage(false),
1160 ExternalVisibleStorage(false),
1161 NeedToReconcileExternalVisibleStorage(false),
1162 HasLazyLocalLexicalLookups(false), HasLazyExternalLexicalLookups(false),
1163 LookupPtr(nullptr), FirstDecl(nullptr), LastDecl(nullptr) {}
1168 Decl::Kind getDeclKind() const {
1169 return static_cast<Decl::Kind>(DeclKind);
1171 const char *getDeclKindName() const;
1173 /// getParent - Returns the containing DeclContext.
1174 DeclContext *getParent() {
1175 return cast<Decl>(this)->getDeclContext();
1177 const DeclContext *getParent() const {
1178 return const_cast<DeclContext*>(this)->getParent();
1181 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1182 /// different from getParent, e.g.:
1187 /// struct A::S {}; // getParent() == namespace 'A'
1188 /// // getLexicalParent() == translation unit
1190 DeclContext *getLexicalParent() {
1191 return cast<Decl>(this)->getLexicalDeclContext();
1193 const DeclContext *getLexicalParent() const {
1194 return const_cast<DeclContext*>(this)->getLexicalParent();
1197 DeclContext *getLookupParent();
1199 const DeclContext *getLookupParent() const {
1200 return const_cast<DeclContext*>(this)->getLookupParent();
1203 ASTContext &getParentASTContext() const {
1204 return cast<Decl>(this)->getASTContext();
1207 bool isClosure() const {
1208 return DeclKind == Decl::Block;
1211 bool isObjCContainer() const {
1213 case Decl::ObjCCategory:
1214 case Decl::ObjCCategoryImpl:
1215 case Decl::ObjCImplementation:
1216 case Decl::ObjCInterface:
1217 case Decl::ObjCProtocol:
1223 bool isFunctionOrMethod() const {
1226 case Decl::Captured:
1227 case Decl::ObjCMethod:
1230 return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1234 /// \brief Test whether the context supports looking up names.
1235 bool isLookupContext() const {
1236 return !isFunctionOrMethod() && DeclKind != Decl::LinkageSpec;
1239 bool isFileContext() const {
1240 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1243 bool isTranslationUnit() const {
1244 return DeclKind == Decl::TranslationUnit;
1247 bool isRecord() const {
1248 return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1251 bool isNamespace() const {
1252 return DeclKind == Decl::Namespace;
1255 bool isStdNamespace() const;
1257 bool isInlineNamespace() const;
1259 /// \brief Determines whether this context is dependent on a
1260 /// template parameter.
1261 bool isDependentContext() const;
1263 /// isTransparentContext - Determines whether this context is a
1264 /// "transparent" context, meaning that the members declared in this
1265 /// context are semantically declared in the nearest enclosing
1266 /// non-transparent (opaque) context but are lexically declared in
1267 /// this context. For example, consider the enumerators of an
1268 /// enumeration type:
1274 /// Here, E is a transparent context, so its enumerator (Val1) will
1275 /// appear (semantically) that it is in the same context of E.
1276 /// Examples of transparent contexts include: enumerations (except for
1277 /// C++0x scoped enums), and C++ linkage specifications.
1278 bool isTransparentContext() const;
1280 /// \brief Determines whether this context or some of its ancestors is a
1281 /// linkage specification context that specifies C linkage.
1282 bool isExternCContext() const;
1284 /// \brief Determines whether this context or some of its ancestors is a
1285 /// linkage specification context that specifies C++ linkage.
1286 bool isExternCXXContext() const;
1288 /// \brief Determine whether this declaration context is equivalent
1289 /// to the declaration context DC.
1290 bool Equals(const DeclContext *DC) const {
1291 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1294 /// \brief Determine whether this declaration context encloses the
1295 /// declaration context DC.
1296 bool Encloses(const DeclContext *DC) const;
1298 /// \brief Find the nearest non-closure ancestor of this context,
1299 /// i.e. the innermost semantic parent of this context which is not
1300 /// a closure. A context may be its own non-closure ancestor.
1301 Decl *getNonClosureAncestor();
1302 const Decl *getNonClosureAncestor() const {
1303 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1306 /// getPrimaryContext - There may be many different
1307 /// declarations of the same entity (including forward declarations
1308 /// of classes, multiple definitions of namespaces, etc.), each with
1309 /// a different set of declarations. This routine returns the
1310 /// "primary" DeclContext structure, which will contain the
1311 /// information needed to perform name lookup into this context.
1312 DeclContext *getPrimaryContext();
1313 const DeclContext *getPrimaryContext() const {
1314 return const_cast<DeclContext*>(this)->getPrimaryContext();
1317 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1318 /// other entities of the same name, or where it is a redeclaration if the
1319 /// two entities are compatible. This skips through transparent contexts.
1320 DeclContext *getRedeclContext();
1321 const DeclContext *getRedeclContext() const {
1322 return const_cast<DeclContext *>(this)->getRedeclContext();
1325 /// \brief Retrieve the nearest enclosing namespace context.
1326 DeclContext *getEnclosingNamespaceContext();
1327 const DeclContext *getEnclosingNamespaceContext() const {
1328 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1331 /// \brief Retrieve the outermost lexically enclosing record context.
1332 RecordDecl *getOuterLexicalRecordContext();
1333 const RecordDecl *getOuterLexicalRecordContext() const {
1334 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1337 /// \brief Test if this context is part of the enclosing namespace set of
1338 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1339 /// isn't a namespace, this is equivalent to Equals().
1341 /// The enclosing namespace set of a namespace is the namespace and, if it is
1342 /// inline, its enclosing namespace, recursively.
1343 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1345 /// \brief Collects all of the declaration contexts that are semantically
1346 /// connected to this declaration context.
1348 /// For declaration contexts that have multiple semantically connected but
1349 /// syntactically distinct contexts, such as C++ namespaces, this routine
1350 /// retrieves the complete set of such declaration contexts in source order.
1351 /// For example, given:
1362 /// The \c Contexts parameter will contain both definitions of N.
1364 /// \param Contexts Will be cleared and set to the set of declaration
1365 /// contexts that are semanticaly connected to this declaration context,
1366 /// in source order, including this context (which may be the only result,
1367 /// for non-namespace contexts).
1368 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1370 /// decl_iterator - Iterates through the declarations stored
1371 /// within this context.
1372 class decl_iterator {
1373 /// Current - The current declaration.
1377 typedef Decl *value_type;
1378 typedef const value_type &reference;
1379 typedef const value_type *pointer;
1380 typedef std::forward_iterator_tag iterator_category;
1381 typedef std::ptrdiff_t difference_type;
1383 decl_iterator() : Current(nullptr) { }
1384 explicit decl_iterator(Decl *C) : Current(C) { }
1386 reference operator*() const { return Current; }
1387 // This doesn't meet the iterator requirements, but it's convenient
1388 value_type operator->() const { return Current; }
1390 decl_iterator& operator++() {
1391 Current = Current->getNextDeclInContext();
1395 decl_iterator operator++(int) {
1396 decl_iterator tmp(*this);
1401 friend bool operator==(decl_iterator x, decl_iterator y) {
1402 return x.Current == y.Current;
1404 friend bool operator!=(decl_iterator x, decl_iterator y) {
1405 return x.Current != y.Current;
1409 typedef llvm::iterator_range<decl_iterator> decl_range;
1411 /// decls_begin/decls_end - Iterate over the declarations stored in
1413 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
1414 decl_iterator decls_begin() const;
1415 decl_iterator decls_end() const { return decl_iterator(); }
1416 bool decls_empty() const;
1418 /// noload_decls_begin/end - Iterate over the declarations stored in this
1419 /// context that are currently loaded; don't attempt to retrieve anything
1420 /// from an external source.
1421 decl_range noload_decls() const {
1422 return decl_range(noload_decls_begin(), noload_decls_end());
1424 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
1425 decl_iterator noload_decls_end() const { return decl_iterator(); }
1427 /// specific_decl_iterator - Iterates over a subrange of
1428 /// declarations stored in a DeclContext, providing only those that
1429 /// are of type SpecificDecl (or a class derived from it). This
1430 /// iterator is used, for example, to provide iteration over just
1431 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1432 template<typename SpecificDecl>
1433 class specific_decl_iterator {
1434 /// Current - The current, underlying declaration iterator, which
1435 /// will either be NULL or will point to a declaration of
1436 /// type SpecificDecl.
1437 DeclContext::decl_iterator Current;
1439 /// SkipToNextDecl - Advances the current position up to the next
1440 /// declaration of type SpecificDecl that also meets the criteria
1441 /// required by Acceptable.
1442 void SkipToNextDecl() {
1443 while (*Current && !isa<SpecificDecl>(*Current))
1448 typedef SpecificDecl *value_type;
1449 // TODO: Add reference and pointer typedefs (with some appropriate proxy
1450 // type) if we ever have a need for them.
1451 typedef void reference;
1452 typedef void pointer;
1453 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1455 typedef std::forward_iterator_tag iterator_category;
1457 specific_decl_iterator() : Current() { }
1459 /// specific_decl_iterator - Construct a new iterator over a
1460 /// subset of the declarations the range [C,
1461 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1462 /// member function of SpecificDecl that should return true for
1463 /// all of the SpecificDecl instances that will be in the subset
1464 /// of iterators. For example, if you want Objective-C instance
1465 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1466 /// &ObjCMethodDecl::isInstanceMethod.
1467 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1471 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1472 // This doesn't meet the iterator requirements, but it's convenient
1473 value_type operator->() const { return **this; }
1475 specific_decl_iterator& operator++() {
1481 specific_decl_iterator operator++(int) {
1482 specific_decl_iterator tmp(*this);
1487 friend bool operator==(const specific_decl_iterator& x,
1488 const specific_decl_iterator& y) {
1489 return x.Current == y.Current;
1492 friend bool operator!=(const specific_decl_iterator& x,
1493 const specific_decl_iterator& y) {
1494 return x.Current != y.Current;
1498 /// \brief Iterates over a filtered subrange of declarations stored
1499 /// in a DeclContext.
1501 /// This iterator visits only those declarations that are of type
1502 /// SpecificDecl (or a class derived from it) and that meet some
1503 /// additional run-time criteria. This iterator is used, for
1504 /// example, to provide access to the instance methods within an
1505 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1506 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1507 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1508 class filtered_decl_iterator {
1509 /// Current - The current, underlying declaration iterator, which
1510 /// will either be NULL or will point to a declaration of
1511 /// type SpecificDecl.
1512 DeclContext::decl_iterator Current;
1514 /// SkipToNextDecl - Advances the current position up to the next
1515 /// declaration of type SpecificDecl that also meets the criteria
1516 /// required by Acceptable.
1517 void SkipToNextDecl() {
1519 (!isa<SpecificDecl>(*Current) ||
1520 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
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 filtered_decl_iterator() : Current() { }
1536 /// filtered_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 filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1548 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1549 value_type operator->() const { return cast<SpecificDecl>(*Current); }
1551 filtered_decl_iterator& operator++() {
1557 filtered_decl_iterator operator++(int) {
1558 filtered_decl_iterator tmp(*this);
1563 friend bool operator==(const filtered_decl_iterator& x,
1564 const filtered_decl_iterator& y) {
1565 return x.Current == y.Current;
1568 friend bool operator!=(const filtered_decl_iterator& x,
1569 const filtered_decl_iterator& y) {
1570 return x.Current != y.Current;
1574 /// @brief Add the declaration D into this context.
1576 /// This routine should be invoked when the declaration D has first
1577 /// been declared, to place D into the context where it was
1578 /// (lexically) defined. Every declaration must be added to one
1579 /// (and only one!) context, where it can be visited via
1580 /// [decls_begin(), decls_end()). Once a declaration has been added
1581 /// to its lexical context, the corresponding DeclContext owns the
1584 /// If D is also a NamedDecl, it will be made visible within its
1585 /// semantic context via makeDeclVisibleInContext.
1586 void addDecl(Decl *D);
1588 /// @brief Add the declaration D into this context, but suppress
1589 /// searches for external declarations with the same name.
1591 /// Although analogous in function to addDecl, this removes an
1592 /// important check. This is only useful if the Decl is being
1593 /// added in response to an external search; in all other cases,
1594 /// addDecl() is the right function to use.
1595 /// See the ASTImporter for use cases.
1596 void addDeclInternal(Decl *D);
1598 /// @brief Add the declaration D to this context without modifying
1599 /// any lookup tables.
1601 /// This is useful for some operations in dependent contexts where
1602 /// the semantic context might not be dependent; this basically
1603 /// only happens with friends.
1604 void addHiddenDecl(Decl *D);
1606 /// @brief Removes a declaration from this context.
1607 void removeDecl(Decl *D);
1609 /// @brief Checks whether a declaration is in this context.
1610 bool containsDecl(Decl *D) const;
1612 typedef DeclContextLookupResult lookup_result;
1613 typedef lookup_result::iterator lookup_iterator;
1615 /// lookup - Find the declarations (if any) with the given Name in
1616 /// this context. Returns a range of iterators that contains all of
1617 /// the declarations with this name, with object, function, member,
1618 /// and enumerator names preceding any tag name. Note that this
1619 /// routine will not look into parent contexts.
1620 lookup_result lookup(DeclarationName Name) const;
1622 /// \brief Find the declarations with the given name that are visible
1623 /// within this context; don't attempt to retrieve anything from an
1624 /// external source.
1625 lookup_result noload_lookup(DeclarationName Name);
1627 /// \brief A simplistic name lookup mechanism that performs name lookup
1628 /// into this declaration context without consulting the external source.
1630 /// This function should almost never be used, because it subverts the
1631 /// usual relationship between a DeclContext and the external source.
1632 /// See the ASTImporter for the (few, but important) use cases.
1634 /// FIXME: This is very inefficient; replace uses of it with uses of
1636 void localUncachedLookup(DeclarationName Name,
1637 SmallVectorImpl<NamedDecl *> &Results);
1639 /// @brief Makes a declaration visible within this context.
1641 /// This routine makes the declaration D visible to name lookup
1642 /// within this context and, if this is a transparent context,
1643 /// within its parent contexts up to the first enclosing
1644 /// non-transparent context. Making a declaration visible within a
1645 /// context does not transfer ownership of a declaration, and a
1646 /// declaration can be visible in many contexts that aren't its
1647 /// lexical context.
1649 /// If D is a redeclaration of an existing declaration that is
1650 /// visible from this context, as determined by
1651 /// NamedDecl::declarationReplaces, the previous declaration will be
1652 /// replaced with D.
1653 void makeDeclVisibleInContext(NamedDecl *D);
1655 /// all_lookups_iterator - An iterator that provides a view over the results
1656 /// of looking up every possible name.
1657 class all_lookups_iterator;
1659 typedef llvm::iterator_range<all_lookups_iterator> lookups_range;
1661 lookups_range lookups() const;
1662 lookups_range noload_lookups() const;
1664 /// \brief Iterators over all possible lookups within this context.
1665 all_lookups_iterator lookups_begin() const;
1666 all_lookups_iterator lookups_end() const;
1668 /// \brief Iterators over all possible lookups within this context that are
1669 /// currently loaded; don't attempt to retrieve anything from an external
1671 all_lookups_iterator noload_lookups_begin() const;
1672 all_lookups_iterator noload_lookups_end() const;
1674 struct udir_iterator;
1675 typedef llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
1676 std::random_access_iterator_tag,
1677 UsingDirectiveDecl *> udir_iterator_base;
1678 struct udir_iterator : udir_iterator_base {
1679 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
1680 UsingDirectiveDecl *operator*() const;
1683 typedef llvm::iterator_range<udir_iterator> udir_range;
1685 udir_range using_directives() const;
1687 // These are all defined in DependentDiagnostic.h.
1688 class ddiag_iterator;
1689 typedef llvm::iterator_range<DeclContext::ddiag_iterator> ddiag_range;
1691 inline ddiag_range ddiags() const;
1693 // Low-level accessors
1695 /// \brief Mark that there are external lexical declarations that we need
1696 /// to include in our lookup table (and that are not available as external
1697 /// visible lookups). These extra lookup results will be found by walking
1698 /// the lexical declarations of this context. This should be used only if
1699 /// setHasExternalLexicalStorage() has been called on any decl context for
1700 /// which this is the primary context.
1701 void setMustBuildLookupTable() {
1702 assert(this == getPrimaryContext() &&
1703 "should only be called on primary context");
1704 HasLazyExternalLexicalLookups = true;
1707 /// \brief Retrieve the internal representation of the lookup structure.
1708 /// This may omit some names if we are lazily building the structure.
1709 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
1711 /// \brief Ensure the lookup structure is fully-built and return it.
1712 StoredDeclsMap *buildLookup();
1714 /// \brief Whether this DeclContext has external storage containing
1715 /// additional declarations that are lexically in this context.
1716 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1718 /// \brief State whether this DeclContext has external storage for
1719 /// declarations lexically in this context.
1720 void setHasExternalLexicalStorage(bool ES = true) {
1721 ExternalLexicalStorage = ES;
1724 /// \brief Whether this DeclContext has external storage containing
1725 /// additional declarations that are visible in this context.
1726 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1728 /// \brief State whether this DeclContext has external storage for
1729 /// declarations visible in this context.
1730 void setHasExternalVisibleStorage(bool ES = true) {
1731 ExternalVisibleStorage = ES;
1732 if (ES && LookupPtr)
1733 NeedToReconcileExternalVisibleStorage = true;
1736 /// \brief Determine whether the given declaration is stored in the list of
1737 /// declarations lexically within this context.
1738 bool isDeclInLexicalTraversal(const Decl *D) const {
1739 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1743 static bool classof(const Decl *D);
1744 static bool classof(const DeclContext *D) { return true; }
1746 void dumpDeclContext() const;
1747 void dumpLookups() const;
1748 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false) const;
1751 void reconcileExternalVisibleStorage() const;
1752 bool LoadLexicalDeclsFromExternalStorage() const;
1754 /// @brief Makes a declaration visible within this context, but
1755 /// suppresses searches for external declarations with the same
1758 /// Analogous to makeDeclVisibleInContext, but for the exclusive
1759 /// use of addDeclInternal().
1760 void makeDeclVisibleInContextInternal(NamedDecl *D);
1762 friend class DependentDiagnostic;
1763 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1765 void buildLookupImpl(DeclContext *DCtx, bool Internal);
1766 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1767 bool Rediscoverable);
1768 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1771 inline bool Decl::isTemplateParameter() const {
1772 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1773 getKind() == TemplateTemplateParm;
1776 // Specialization selected when ToTy is not a known subclass of DeclContext.
1777 template <class ToTy,
1778 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
1779 struct cast_convert_decl_context {
1780 static const ToTy *doit(const DeclContext *Val) {
1781 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1784 static ToTy *doit(DeclContext *Val) {
1785 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1789 // Specialization selected when ToTy is a known subclass of DeclContext.
1790 template <class ToTy>
1791 struct cast_convert_decl_context<ToTy, true> {
1792 static const ToTy *doit(const DeclContext *Val) {
1793 return static_cast<const ToTy*>(Val);
1796 static ToTy *doit(DeclContext *Val) {
1797 return static_cast<ToTy*>(Val);
1806 /// isa<T>(DeclContext*)
1807 template <typename To>
1808 struct isa_impl<To, ::clang::DeclContext> {
1809 static bool doit(const ::clang::DeclContext &Val) {
1810 return To::classofKind(Val.getDeclKind());
1814 /// cast<T>(DeclContext*)
1815 template<class ToTy>
1816 struct cast_convert_val<ToTy,
1817 const ::clang::DeclContext,const ::clang::DeclContext> {
1818 static const ToTy &doit(const ::clang::DeclContext &Val) {
1819 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1822 template<class ToTy>
1823 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
1824 static ToTy &doit(::clang::DeclContext &Val) {
1825 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1828 template<class ToTy>
1829 struct cast_convert_val<ToTy,
1830 const ::clang::DeclContext*, const ::clang::DeclContext*> {
1831 static const ToTy *doit(const ::clang::DeclContext *Val) {
1832 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1835 template<class ToTy>
1836 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
1837 static ToTy *doit(::clang::DeclContext *Val) {
1838 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1842 /// Implement cast_convert_val for Decl -> DeclContext conversions.
1843 template<class FromTy>
1844 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1845 static ::clang::DeclContext &doit(const FromTy &Val) {
1846 return *FromTy::castToDeclContext(&Val);
1850 template<class FromTy>
1851 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1852 static ::clang::DeclContext *doit(const FromTy *Val) {
1853 return FromTy::castToDeclContext(Val);
1857 template<class FromTy>
1858 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1859 static const ::clang::DeclContext &doit(const FromTy &Val) {
1860 return *FromTy::castToDeclContext(&Val);
1864 template<class FromTy>
1865 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1866 static const ::clang::DeclContext *doit(const FromTy *Val) {
1867 return FromTy::castToDeclContext(Val);
1871 } // end namespace llvm