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/Attr.h"
18 #include "clang/AST/Type.h"
19 // FIXME: Layering violation
20 #include "clang/Parse/AccessSpecifier.h"
21 #include "llvm/Support/PrettyStackTrace.h"
22 #include "llvm/ADT/PointerUnion.h"
26 class TranslationUnitDecl;
28 class UsingDirectiveDecl;
34 class ObjCContainerDecl;
35 class ObjCInterfaceDecl;
36 class ObjCCategoryDecl;
37 class ObjCProtocolDecl;
38 class ObjCImplementationDecl;
39 class ObjCCategoryImplDecl;
41 class LinkageSpecDecl;
43 class DeclarationName;
48 // DeclContext* is only 4-byte aligned on 32-bit systems.
50 class PointerLikeTypeTraits<clang::DeclContext*> {
51 typedef clang::DeclContext* PT;
53 static inline void *getAsVoidPointer(PT P) { return P; }
54 static inline PT getFromVoidPointer(void *P) {
55 return static_cast<PT>(P);
57 enum { NumLowBitsAvailable = 2 };
63 /// Decl - This represents one declaration (or definition), e.g. a variable,
64 /// typedef, function, struct, etc.
68 /// \brief Lists the kind of concrete classes of Decl.
70 #define DECL(Derived, Base) Derived,
71 #define DECL_RANGE(CommonBase, Start, End) \
72 CommonBase##First = Start, CommonBase##Last = End,
73 #define LAST_DECL_RANGE(CommonBase, Start, End) \
74 CommonBase##First = Start, CommonBase##Last = End
75 #include "clang/AST/DeclNodes.def"
78 /// IdentifierNamespace - According to C99 6.2.3, there are four
79 /// namespaces, labels, tags, members and ordinary
80 /// identifiers. These are meant as bitmasks, so that searches in
81 /// C++ can look into the "tag" namespace during ordinary lookup. We
82 /// use additional namespaces for Objective-C entities. We also put
83 /// C++ friend declarations (of previously-undeclared entities) in
84 /// shadow namespaces, and 'using' declarations (as opposed to their
85 /// implicit shadow declarations) can be found in their own
87 enum IdentifierNamespace {
92 IDNS_ObjCProtocol = 0x10,
93 IDNS_ObjCImplementation = 0x20,
94 IDNS_ObjCCategoryName = 0x40,
95 IDNS_OrdinaryFriend = 0x80,
96 IDNS_TagFriend = 0x100,
100 /// ObjCDeclQualifier - Qualifier used on types in method declarations
101 /// for remote messaging. They are meant for the arguments though and
102 /// applied to the Decls (ObjCMethodDecl and ParmVarDecl).
103 enum ObjCDeclQualifier {
108 OBJC_TQ_Bycopy = 0x8,
109 OBJC_TQ_Byref = 0x10,
110 OBJC_TQ_Oneway = 0x20
114 /// NextDeclInContext - The next declaration within the same lexical
115 /// DeclContext. These pointers form the linked list that is
116 /// traversed via DeclContext's decls_begin()/decls_end().
117 Decl *NextDeclInContext;
119 friend class DeclContext;
122 DeclContext *SemanticDC;
123 DeclContext *LexicalDC;
127 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
128 /// For declarations that don't contain C++ scope specifiers, it contains
129 /// the DeclContext where the Decl was declared.
130 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
131 /// with the context where it semantically belongs (SemanticDC) and the
132 /// context where it was lexically declared (LexicalDC).
136 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
138 /// void A::f(); // SemanticDC == namespace 'A'
139 /// // LexicalDC == global namespace
140 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
142 inline bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
143 inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
144 inline MultipleDC *getMultipleDC() const {
145 return DeclCtx.get<MultipleDC*>();
147 inline DeclContext *getSemanticDC() const {
148 return DeclCtx.get<DeclContext*>();
151 /// Loc - The location that this decl.
154 /// DeclKind - This indicates which class this is.
157 /// InvalidDecl - This indicates a semantic error occurred.
158 unsigned int InvalidDecl : 1;
160 /// HasAttrs - This indicates whether the decl has attributes or not.
161 unsigned int HasAttrs : 1;
163 /// Implicit - Whether this declaration was implicitly generated by
164 /// the implementation rather than explicitly written by the user.
167 /// \brief Whether this declaration was "used", meaning that a definition is
172 /// Access - Used by C++ decls for the access specifier.
173 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
175 friend class CXXClassMemberWrapper;
177 // PCHLevel - the "level" of precompiled header/AST file from which this
178 // declaration was built.
179 unsigned PCHLevel : 2;
181 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
182 unsigned IdentifierNamespace : 16;
186 void CheckAccessDeclContext() const;
188 void CheckAccessDeclContext() const { }
193 Decl(Kind DK, DeclContext *DC, SourceLocation L)
194 : NextDeclInContext(0), DeclCtx(DC),
195 Loc(L), DeclKind(DK), InvalidDecl(0),
196 HasAttrs(false), Implicit(false), Used(false),
197 Access(AS_none), PCHLevel(0),
198 IdentifierNamespace(getIdentifierNamespaceForKind(DK)) {
199 if (Decl::CollectingStats()) addDeclKind(DK);
206 /// \brief Source range that this declaration covers.
207 virtual SourceRange getSourceRange() const {
208 return SourceRange(getLocation(), getLocation());
210 SourceLocation getLocStart() const { return getSourceRange().getBegin(); }
211 SourceLocation getLocEnd() const { return getSourceRange().getEnd(); }
213 SourceLocation getLocation() const { return Loc; }
214 void setLocation(SourceLocation L) { Loc = L; }
216 Kind getKind() const { return DeclKind; }
217 const char *getDeclKindName() const;
219 Decl *getNextDeclInContext() { return NextDeclInContext; }
220 const Decl *getNextDeclInContext() const { return NextDeclInContext; }
222 DeclContext *getDeclContext() {
224 return getSemanticDC();
225 return getMultipleDC()->SemanticDC;
227 const DeclContext *getDeclContext() const {
228 return const_cast<Decl*>(this)->getDeclContext();
231 TranslationUnitDecl *getTranslationUnitDecl();
232 const TranslationUnitDecl *getTranslationUnitDecl() const {
233 return const_cast<Decl*>(this)->getTranslationUnitDecl();
236 bool isInAnonymousNamespace() const;
238 ASTContext &getASTContext() const;
240 void setAccess(AccessSpecifier AS) {
242 CheckAccessDeclContext();
245 AccessSpecifier getAccess() const {
246 CheckAccessDeclContext();
247 return AccessSpecifier(Access);
250 bool hasAttrs() const { return HasAttrs; }
251 void addAttr(Attr *attr);
252 const Attr *getAttrs() const {
253 if (!HasAttrs) return 0; // common case, no attributes.
254 return getAttrsImpl(); // Uncommon case, out of line hash lookup.
256 void swapAttrs(Decl *D);
257 void invalidateAttrs();
259 template<typename T> const T *getAttr() const {
260 for (const Attr *attr = getAttrs(); attr; attr = attr->getNext())
261 if (const T *V = dyn_cast<T>(attr))
266 template<typename T> bool hasAttr() const {
267 return getAttr<T>() != 0;
270 /// setInvalidDecl - Indicates the Decl had a semantic error. This
271 /// allows for graceful error recovery.
272 void setInvalidDecl(bool Invalid = true) { InvalidDecl = Invalid; }
273 bool isInvalidDecl() const { return (bool) InvalidDecl; }
275 /// isImplicit - Indicates whether the declaration was implicitly
276 /// generated by the implementation. If false, this declaration
277 /// was written explicitly in the source code.
278 bool isImplicit() const { return Implicit; }
279 void setImplicit(bool I = true) { Implicit = I; }
281 /// \brief Whether this declaration was used, meaning that a definition
283 bool isUsed() const { return Used; }
284 void setUsed(bool U = true) { Used = U; }
286 /// \brief Retrieve the level of precompiled header from which this
287 /// declaration was generated.
289 /// The PCH level of a declaration describes where the declaration originated
290 /// from. A PCH level of 0 indicates that the declaration was not from a
291 /// precompiled header. A PCH level of 1 indicates that the declaration was
292 /// from a top-level precompiled header; 2 indicates that the declaration
293 /// comes from a precompiled header on which the top-level precompiled header
294 /// depends, and so on.
295 unsigned getPCHLevel() const { return PCHLevel; }
297 /// \brief The maximum PCH level that any declaration may have.
298 static const unsigned MaxPCHLevel = 3;
300 /// \brief Set the PCH level of this declaration.
301 void setPCHLevel(unsigned Level) {
302 assert(Level < MaxPCHLevel && "PCH level exceeds the maximum");
306 unsigned getIdentifierNamespace() const {
307 return IdentifierNamespace;
309 bool isInIdentifierNamespace(unsigned NS) const {
310 return getIdentifierNamespace() & NS;
312 static unsigned getIdentifierNamespaceForKind(Kind DK);
315 /// getLexicalDeclContext - The declaration context where this Decl was
316 /// lexically declared (LexicalDC). May be different from
317 /// getDeclContext() (SemanticDC).
321 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
323 /// void A::f(); // SemanticDC == namespace 'A'
324 /// // LexicalDC == global namespace
325 DeclContext *getLexicalDeclContext() {
327 return getSemanticDC();
328 return getMultipleDC()->LexicalDC;
330 const DeclContext *getLexicalDeclContext() const {
331 return const_cast<Decl*>(this)->getLexicalDeclContext();
334 bool isOutOfLine() const {
335 return getLexicalDeclContext() != getDeclContext();
338 /// setDeclContext - Set both the semantic and lexical DeclContext
340 void setDeclContext(DeclContext *DC);
342 void setLexicalDeclContext(DeclContext *DC);
344 // isDefinedOutsideFunctionOrMethod - This predicate returns true if this
345 // scoped decl is defined outside the current function or method. This is
346 // roughly global variables and functions, but also handles enums (which could
347 // be defined inside or outside a function etc).
348 bool isDefinedOutsideFunctionOrMethod() const;
350 /// \brief Retrieves the "canonical" declaration of the given declaration.
351 virtual Decl *getCanonicalDecl() { return this; }
352 const Decl *getCanonicalDecl() const {
353 return const_cast<Decl*>(this)->getCanonicalDecl();
356 /// \brief Whether this particular Decl is a canonical one.
357 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
360 /// \brief Returns the next redeclaration or itself if this is the only decl.
362 /// Decl subclasses that can be redeclared should override this method so that
363 /// Decl::redecl_iterator can iterate over them.
364 virtual Decl *getNextRedeclaration() { return this; }
367 /// \brief Iterates through all the redeclarations of the same decl.
368 class redecl_iterator {
369 /// Current - The current declaration.
374 typedef Decl* value_type;
375 typedef Decl* reference;
376 typedef Decl* pointer;
377 typedef std::forward_iterator_tag iterator_category;
378 typedef std::ptrdiff_t difference_type;
380 redecl_iterator() : Current(0) { }
381 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
383 reference operator*() const { return Current; }
384 pointer operator->() const { return Current; }
386 redecl_iterator& operator++() {
387 assert(Current && "Advancing while iterator has reached end");
388 // Get either previous decl or latest decl.
389 Decl *Next = Current->getNextRedeclaration();
390 assert(Next && "Should return next redeclaration or itself, never null!");
391 Current = (Next != Starter ? Next : 0);
395 redecl_iterator operator++(int) {
396 redecl_iterator tmp(*this);
401 friend bool operator==(redecl_iterator x, redecl_iterator y) {
402 return x.Current == y.Current;
404 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
405 return x.Current != y.Current;
409 /// \brief Returns iterator for all the redeclarations of the same decl.
410 /// It will iterate at least once (when this decl is the only one).
411 redecl_iterator redecls_begin() const {
412 return redecl_iterator(const_cast<Decl*>(this));
414 redecl_iterator redecls_end() const { return redecl_iterator(); }
416 /// getBody - If this Decl represents a declaration for a body of code,
417 /// such as a function or method definition, this method returns the
418 /// top-level Stmt* of that body. Otherwise this method returns null.
419 virtual Stmt* getBody() const { return 0; }
421 /// getCompoundBody - Returns getBody(), dyn_casted to a CompoundStmt.
422 CompoundStmt* getCompoundBody() const;
424 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
425 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
426 SourceLocation getBodyRBrace() const;
428 // global temp stats (until we have a per-module visitor)
429 static void addDeclKind(Kind k);
430 static bool CollectingStats(bool Enable = false);
431 static void PrintStats();
433 /// isTemplateParameter - Determines whether this declaration is a
434 /// template parameter.
435 bool isTemplateParameter() const;
437 /// isTemplateParameter - Determines whether this declaration is a
438 /// template parameter pack.
439 bool isTemplateParameterPack() const;
441 /// \brief Whether this declaration is a function or function template.
442 bool isFunctionOrFunctionTemplate() const;
444 /// \brief Changes the namespace of this declaration to reflect that it's
445 /// the object of a friend declaration.
447 /// These declarations appear in the lexical context of the friending
448 /// class, but in the semantic context of the actual entity. This property
449 /// applies only to a specific decl object; other redeclarations of the
450 /// same entity may not (and probably don't) share this property.
451 void setObjectOfFriendDecl(bool PreviouslyDeclared) {
452 unsigned OldNS = IdentifierNamespace;
453 assert((OldNS == IDNS_Tag || OldNS == IDNS_Ordinary ||
454 OldNS == (IDNS_Tag | IDNS_Ordinary))
455 && "unsupported namespace for undeclared friend");
456 if (!PreviouslyDeclared) IdentifierNamespace = 0;
458 if (OldNS == IDNS_Tag)
459 IdentifierNamespace |= IDNS_TagFriend;
461 IdentifierNamespace |= IDNS_OrdinaryFriend;
464 enum FriendObjectKind {
465 FOK_None, // not a friend object
466 FOK_Declared, // a friend of a previously-declared entity
467 FOK_Undeclared // a friend of a previously-undeclared entity
470 /// \brief Determines whether this declaration is the object of a
471 /// friend declaration and, if so, what kind.
473 /// There is currently no direct way to find the associated FriendDecl.
474 FriendObjectKind getFriendObjectKind() const {
476 = (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
477 if (!mask) return FOK_None;
478 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ?
479 FOK_Declared : FOK_Undeclared);
482 // Implement isa/cast/dyncast/etc.
483 static bool classof(const Decl *) { return true; }
484 static DeclContext *castToDeclContext(const Decl *);
485 static Decl *castFromDeclContext(const DeclContext *);
487 /// Destroy - Call destructors and release memory.
488 virtual void Destroy(ASTContext& C);
490 void print(llvm::raw_ostream &Out, unsigned Indentation = 0) const;
491 void print(llvm::raw_ostream &Out, const PrintingPolicy &Policy,
492 unsigned Indentation = 0) const;
493 static void printGroup(Decl** Begin, unsigned NumDecls,
494 llvm::raw_ostream &Out, const PrintingPolicy &Policy,
495 unsigned Indentation = 0);
499 const Attr *getAttrsImpl() const;
503 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
504 /// doing something to a specific decl.
505 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
511 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
512 SourceManager &sm, const char *Msg)
513 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
515 virtual void print(llvm::raw_ostream &OS) const;
519 /// DeclContext - This is used only as base class of specific decl types that
520 /// can act as declaration contexts. These decls are (only the top classes
521 /// that directly derive from DeclContext are mentioned, not their subclasses):
523 /// TranslationUnitDecl
528 /// ObjCContainerDecl
533 /// DeclKind - This indicates which class this is.
534 Decl::Kind DeclKind : 8;
536 /// \brief Whether this declaration context also has some external
537 /// storage that contains additional declarations that are lexically
538 /// part of this context.
539 mutable bool ExternalLexicalStorage : 1;
541 /// \brief Whether this declaration context also has some external
542 /// storage that contains additional declarations that are visible
544 mutable bool ExternalVisibleStorage : 1;
546 /// \brief Pointer to the data structure used to lookup declarations
547 /// within this context, which is a DenseMap<DeclarationName,
548 /// StoredDeclsList>.
549 mutable void* LookupPtr;
551 /// FirstDecl - The first declaration stored within this declaration
553 mutable Decl *FirstDecl;
555 /// LastDecl - The last declaration stored within this declaration
556 /// context. FIXME: We could probably cache this value somewhere
557 /// outside of the DeclContext, to reduce the size of DeclContext by
559 mutable Decl *LastDecl;
562 DeclContext(Decl::Kind K)
563 : DeclKind(K), ExternalLexicalStorage(false),
564 ExternalVisibleStorage(false), LookupPtr(0), FirstDecl(0),
567 void DestroyDecls(ASTContext &C);
572 Decl::Kind getDeclKind() const {
575 const char *getDeclKindName() const;
577 /// getParent - Returns the containing DeclContext.
578 DeclContext *getParent() {
579 return cast<Decl>(this)->getDeclContext();
581 const DeclContext *getParent() const {
582 return const_cast<DeclContext*>(this)->getParent();
585 /// getLexicalParent - Returns the containing lexical DeclContext. May be
586 /// different from getParent, e.g.:
591 /// struct A::S {}; // getParent() == namespace 'A'
592 /// // getLexicalParent() == translation unit
594 DeclContext *getLexicalParent() {
595 return cast<Decl>(this)->getLexicalDeclContext();
597 const DeclContext *getLexicalParent() const {
598 return const_cast<DeclContext*>(this)->getLexicalParent();
601 DeclContext *getLookupParent();
603 const DeclContext *getLookupParent() const {
604 return const_cast<DeclContext*>(this)->getLookupParent();
607 ASTContext &getParentASTContext() const {
608 return cast<Decl>(this)->getASTContext();
611 bool isFunctionOrMethod() const {
614 case Decl::ObjCMethod:
617 return DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast;
621 bool isFileContext() const {
622 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
625 bool isTranslationUnit() const {
626 return DeclKind == Decl::TranslationUnit;
629 bool isRecord() const {
630 return DeclKind >= Decl::RecordFirst && DeclKind <= Decl::RecordLast;
633 bool isNamespace() const {
634 return DeclKind == Decl::Namespace;
637 /// \brief Determines whether this context is dependent on a
638 /// template parameter.
639 bool isDependentContext() const;
641 /// isTransparentContext - Determines whether this context is a
642 /// "transparent" context, meaning that the members declared in this
643 /// context are semantically declared in the nearest enclosing
644 /// non-transparent (opaque) context but are lexically declared in
645 /// this context. For example, consider the enumerators of an
646 /// enumeration type:
652 /// Here, E is a transparent context, so its enumerator (Val1) will
653 /// appear (semantically) that it is in the same context of E.
654 /// Examples of transparent contexts include: enumerations (except for
655 /// C++0x scoped enums), C++ linkage specifications, and C++0x
656 /// inline namespaces.
657 bool isTransparentContext() const;
659 /// \brief Determine whether this declaration context is equivalent
660 /// to the declaration context DC.
661 bool Equals(DeclContext *DC) {
662 return this->getPrimaryContext() == DC->getPrimaryContext();
665 /// \brief Determine whether this declaration context encloses the
666 /// declaration context DC.
667 bool Encloses(DeclContext *DC);
669 /// getPrimaryContext - There may be many different
670 /// declarations of the same entity (including forward declarations
671 /// of classes, multiple definitions of namespaces, etc.), each with
672 /// a different set of declarations. This routine returns the
673 /// "primary" DeclContext structure, which will contain the
674 /// information needed to perform name lookup into this context.
675 DeclContext *getPrimaryContext();
677 /// getLookupContext - Retrieve the innermost non-transparent
678 /// context of this context, which corresponds to the innermost
679 /// location from which name lookup can find the entities in this
681 DeclContext *getLookupContext();
682 const DeclContext *getLookupContext() const {
683 return const_cast<DeclContext *>(this)->getLookupContext();
686 /// \brief Retrieve the nearest enclosing namespace context.
687 DeclContext *getEnclosingNamespaceContext();
688 const DeclContext *getEnclosingNamespaceContext() const {
689 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
692 /// getNextContext - If this is a DeclContext that may have other
693 /// DeclContexts that are semantically connected but syntactically
694 /// different, such as C++ namespaces, this routine retrieves the
695 /// next DeclContext in the link. Iteration through the chain of
696 /// DeclContexts should begin at the primary DeclContext and
697 /// continue until this function returns NULL. For example, given:
706 /// The first occurrence of namespace N will be the primary
707 /// DeclContext. Its getNextContext will return the second
708 /// occurrence of namespace N.
709 DeclContext *getNextContext();
711 /// decl_iterator - Iterates through the declarations stored
712 /// within this context.
713 class decl_iterator {
714 /// Current - The current declaration.
718 typedef Decl* value_type;
719 typedef Decl* reference;
720 typedef Decl* pointer;
721 typedef std::forward_iterator_tag iterator_category;
722 typedef std::ptrdiff_t difference_type;
724 decl_iterator() : Current(0) { }
725 explicit decl_iterator(Decl *C) : Current(C) { }
727 reference operator*() const { return Current; }
728 pointer operator->() const { return Current; }
730 decl_iterator& operator++() {
731 Current = Current->getNextDeclInContext();
735 decl_iterator operator++(int) {
736 decl_iterator tmp(*this);
741 friend bool operator==(decl_iterator x, decl_iterator y) {
742 return x.Current == y.Current;
744 friend bool operator!=(decl_iterator x, decl_iterator y) {
745 return x.Current != y.Current;
749 /// decls_begin/decls_end - Iterate over the declarations stored in
751 decl_iterator decls_begin() const;
752 decl_iterator decls_end() const;
753 bool decls_empty() const;
755 /// specific_decl_iterator - Iterates over a subrange of
756 /// declarations stored in a DeclContext, providing only those that
757 /// are of type SpecificDecl (or a class derived from it). This
758 /// iterator is used, for example, to provide iteration over just
759 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
760 template<typename SpecificDecl>
761 class specific_decl_iterator {
762 /// Current - The current, underlying declaration iterator, which
763 /// will either be NULL or will point to a declaration of
764 /// type SpecificDecl.
765 DeclContext::decl_iterator Current;
767 /// SkipToNextDecl - Advances the current position up to the next
768 /// declaration of type SpecificDecl that also meets the criteria
769 /// required by Acceptable.
770 void SkipToNextDecl() {
771 while (*Current && !isa<SpecificDecl>(*Current))
776 typedef SpecificDecl* value_type;
777 typedef SpecificDecl* reference;
778 typedef SpecificDecl* pointer;
779 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
781 typedef std::forward_iterator_tag iterator_category;
783 specific_decl_iterator() : Current() { }
785 /// specific_decl_iterator - Construct a new iterator over a
786 /// subset of the declarations the range [C,
787 /// end-of-declarations). If A is non-NULL, it is a pointer to a
788 /// member function of SpecificDecl that should return true for
789 /// all of the SpecificDecl instances that will be in the subset
790 /// of iterators. For example, if you want Objective-C instance
791 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
792 /// &ObjCMethodDecl::isInstanceMethod.
793 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
797 reference operator*() const { return cast<SpecificDecl>(*Current); }
798 pointer operator->() const { return cast<SpecificDecl>(*Current); }
800 specific_decl_iterator& operator++() {
806 specific_decl_iterator operator++(int) {
807 specific_decl_iterator tmp(*this);
813 operator==(const specific_decl_iterator& x, const specific_decl_iterator& y) {
814 return x.Current == y.Current;
818 operator!=(const specific_decl_iterator& x, const specific_decl_iterator& y) {
819 return x.Current != y.Current;
823 /// \brief Iterates over a filtered subrange of declarations stored
824 /// in a DeclContext.
826 /// This iterator visits only those declarations that are of type
827 /// SpecificDecl (or a class derived from it) and that meet some
828 /// additional run-time criteria. This iterator is used, for
829 /// example, to provide access to the instance methods within an
830 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
831 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
832 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
833 class filtered_decl_iterator {
834 /// Current - The current, underlying declaration iterator, which
835 /// will either be NULL or will point to a declaration of
836 /// type SpecificDecl.
837 DeclContext::decl_iterator Current;
839 /// SkipToNextDecl - Advances the current position up to the next
840 /// declaration of type SpecificDecl that also meets the criteria
841 /// required by Acceptable.
842 void SkipToNextDecl() {
844 (!isa<SpecificDecl>(*Current) ||
845 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
850 typedef SpecificDecl* value_type;
851 typedef SpecificDecl* reference;
852 typedef SpecificDecl* pointer;
853 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
855 typedef std::forward_iterator_tag iterator_category;
857 filtered_decl_iterator() : Current() { }
859 /// specific_decl_iterator - Construct a new iterator over a
860 /// subset of the declarations the range [C,
861 /// end-of-declarations). If A is non-NULL, it is a pointer to a
862 /// member function of SpecificDecl that should return true for
863 /// all of the SpecificDecl instances that will be in the subset
864 /// of iterators. For example, if you want Objective-C instance
865 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
866 /// &ObjCMethodDecl::isInstanceMethod.
867 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
871 reference operator*() const { return cast<SpecificDecl>(*Current); }
872 pointer operator->() const { return cast<SpecificDecl>(*Current); }
874 filtered_decl_iterator& operator++() {
880 filtered_decl_iterator operator++(int) {
881 filtered_decl_iterator tmp(*this);
887 operator==(const filtered_decl_iterator& x, const filtered_decl_iterator& y) {
888 return x.Current == y.Current;
892 operator!=(const filtered_decl_iterator& x, const filtered_decl_iterator& y) {
893 return x.Current != y.Current;
897 /// @brief Add the declaration D into this context.
899 /// This routine should be invoked when the declaration D has first
900 /// been declared, to place D into the context where it was
901 /// (lexically) defined. Every declaration must be added to one
902 /// (and only one!) context, where it can be visited via
903 /// [decls_begin(), decls_end()). Once a declaration has been added
904 /// to its lexical context, the corresponding DeclContext owns the
907 /// If D is also a NamedDecl, it will be made visible within its
908 /// semantic context via makeDeclVisibleInContext.
909 void addDecl(Decl *D);
911 /// @brief Add the declaration D to this context without modifying
912 /// any lookup tables.
914 /// This is useful for some operations in dependent contexts where
915 /// the semantic context might not be dependent; this basically
916 /// only happens with friends.
917 void addHiddenDecl(Decl *D);
919 /// @brief Removes a declaration from this context.
920 void removeDecl(Decl *D);
922 /// lookup_iterator - An iterator that provides access to the results
923 /// of looking up a name within this context.
924 typedef NamedDecl **lookup_iterator;
926 /// lookup_const_iterator - An iterator that provides non-mutable
927 /// access to the results of lookup up a name within this context.
928 typedef NamedDecl * const * lookup_const_iterator;
930 typedef std::pair<lookup_iterator, lookup_iterator> lookup_result;
931 typedef std::pair<lookup_const_iterator, lookup_const_iterator>
934 /// lookup - Find the declarations (if any) with the given Name in
935 /// this context. Returns a range of iterators that contains all of
936 /// the declarations with this name, with object, function, member,
937 /// and enumerator names preceding any tag name. Note that this
938 /// routine will not look into parent contexts.
939 lookup_result lookup(DeclarationName Name);
940 lookup_const_result lookup(DeclarationName Name) const;
942 /// @brief Makes a declaration visible within this context.
944 /// This routine makes the declaration D visible to name lookup
945 /// within this context and, if this is a transparent context,
946 /// within its parent contexts up to the first enclosing
947 /// non-transparent context. Making a declaration visible within a
948 /// context does not transfer ownership of a declaration, and a
949 /// declaration can be visible in many contexts that aren't its
952 /// If D is a redeclaration of an existing declaration that is
953 /// visible from this context, as determined by
954 /// NamedDecl::declarationReplaces, the previous declaration will be
957 /// @param Recoverable true if it's okay to not add this decl to
958 /// the lookup tables because it can be easily recovered by walking
959 /// the declaration chains.
960 void makeDeclVisibleInContext(NamedDecl *D, bool Recoverable = true);
962 /// udir_iterator - Iterates through the using-directives stored
963 /// within this context.
964 typedef UsingDirectiveDecl * const * udir_iterator;
966 typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
968 udir_iterator_range getUsingDirectives() const;
970 udir_iterator using_directives_begin() const {
971 return getUsingDirectives().first;
974 udir_iterator using_directives_end() const {
975 return getUsingDirectives().second;
978 // Low-level accessors
980 /// \brief Retrieve the internal representation of the lookup structure.
981 void* getLookupPtr() const { return LookupPtr; }
983 /// \brief Whether this DeclContext has external storage containing
984 /// additional declarations that are lexically in this context.
985 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
987 /// \brief State whether this DeclContext has external storage for
988 /// declarations lexically in this context.
989 void setHasExternalLexicalStorage(bool ES = true) {
990 ExternalLexicalStorage = ES;
993 /// \brief Whether this DeclContext has external storage containing
994 /// additional declarations that are visible in this context.
995 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
997 /// \brief State whether this DeclContext has external storage for
998 /// declarations visible in this context.
999 void setHasExternalVisibleStorage(bool ES = true) {
1000 ExternalVisibleStorage = ES;
1003 static bool classof(const Decl *D);
1004 static bool classof(const DeclContext *D) { return true; }
1005 #define DECL_CONTEXT(Name) \
1006 static bool classof(const Name##Decl *D) { return true; }
1007 #include "clang/AST/DeclNodes.def"
1009 void dumpDeclContext() const;
1012 void LoadLexicalDeclsFromExternalStorage() const;
1013 void LoadVisibleDeclsFromExternalStorage() const;
1015 void buildLookup(DeclContext *DCtx);
1016 void makeDeclVisibleInContextImpl(NamedDecl *D);
1019 inline bool Decl::isTemplateParameter() const {
1020 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm;
1023 inline bool Decl::isDefinedOutsideFunctionOrMethod() const {
1024 if (getDeclContext())
1025 return !getDeclContext()->getLookupContext()->isFunctionOrMethod();
1033 /// Implement a isa_impl_wrap specialization to check whether a DeclContext is
1034 /// a specific Decl.
1035 template<class ToTy>
1036 struct isa_impl_wrap<ToTy,
1037 const ::clang::DeclContext,const ::clang::DeclContext> {
1038 static bool doit(const ::clang::DeclContext &Val) {
1039 return ToTy::classof(::clang::Decl::castFromDeclContext(&Val));
1042 template<class ToTy>
1043 struct isa_impl_wrap<ToTy, ::clang::DeclContext, ::clang::DeclContext>
1044 : public isa_impl_wrap<ToTy,
1045 const ::clang::DeclContext,const ::clang::DeclContext> {};
1047 /// Implement cast_convert_val for Decl -> DeclContext conversions.
1048 template<class FromTy>
1049 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1050 static ::clang::DeclContext &doit(const FromTy &Val) {
1051 return *FromTy::castToDeclContext(&Val);
1055 template<class FromTy>
1056 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1057 static ::clang::DeclContext *doit(const FromTy *Val) {
1058 return FromTy::castToDeclContext(Val);
1062 template<class FromTy>
1063 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1064 static const ::clang::DeclContext &doit(const FromTy &Val) {
1065 return *FromTy::castToDeclContext(&Val);
1069 template<class FromTy>
1070 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1071 static const ::clang::DeclContext *doit(const FromTy *Val) {
1072 return FromTy::castToDeclContext(Val);
1076 /// Implement cast_convert_val for DeclContext -> Decl conversions.
1077 template<class ToTy>
1078 struct cast_convert_val<ToTy,
1079 const ::clang::DeclContext,const ::clang::DeclContext> {
1080 static ToTy &doit(const ::clang::DeclContext &Val) {
1081 return *reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(&Val));
1084 template<class ToTy>
1085 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext>
1086 : public cast_convert_val<ToTy,
1087 const ::clang::DeclContext,const ::clang::DeclContext> {};
1089 template<class ToTy>
1090 struct cast_convert_val<ToTy,
1091 const ::clang::DeclContext*, const ::clang::DeclContext*> {
1092 static ToTy *doit(const ::clang::DeclContext *Val) {
1093 return reinterpret_cast<ToTy*>(ToTy::castFromDeclContext(Val));
1096 template<class ToTy>
1097 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*>
1098 : public cast_convert_val<ToTy,
1099 const ::clang::DeclContext*,const ::clang::DeclContext*> {};
1101 } // end namespace llvm