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 #include "clang/Basic/Specifiers.h"
20 #include "llvm/Support/PrettyStackTrace.h"
21 #include "llvm/ADT/PointerUnion.h"
25 class TranslationUnitDecl;
27 class UsingDirectiveDecl;
33 class ObjCContainerDecl;
34 class ObjCInterfaceDecl;
35 class ObjCCategoryDecl;
36 class ObjCProtocolDecl;
37 class ObjCImplementationDecl;
38 class ObjCCategoryImplDecl;
40 class LinkageSpecDecl;
42 class DeclarationName;
45 class DependentDiagnostic;
49 // DeclContext* is only 4-byte aligned on 32-bit systems.
51 class PointerLikeTypeTraits<clang::DeclContext*> {
52 typedef clang::DeclContext* PT;
54 static inline void *getAsVoidPointer(PT P) { return P; }
55 static inline PT getFromVoidPointer(void *P) {
56 return static_cast<PT>(P);
58 enum { NumLowBitsAvailable = 2 };
64 /// Decl - This represents one declaration (or definition), e.g. a variable,
65 /// typedef, function, struct, etc.
69 /// \brief Lists the kind of concrete classes of Decl.
71 #define DECL(DERIVED, BASE) DERIVED,
72 #define ABSTRACT_DECL(DECL)
73 #define DECL_RANGE(BASE, START, END) \
74 first##BASE = START, last##BASE = END,
75 #define LAST_DECL_RANGE(BASE, START, END) \
76 first##BASE = START, last##BASE = END
77 #include "clang/AST/DeclNodes.inc"
80 /// \brief A placeholder type used to construct an empty shell of a
81 /// decl-derived type that will be filled in later (e.g., by some
82 /// deserialization method).
83 struct EmptyShell { };
85 /// IdentifierNamespace - The different namespaces in which
86 /// declarations may appear. According to C99 6.2.3, there are
87 /// four namespaces, labels, tags, members and ordinary
88 /// identifiers. C++ describes lookup completely differently:
89 /// certain lookups merely "ignore" certain kinds of declarations,
90 /// usually based on whether the declaration is of a type, etc.
92 /// These are meant as bitmasks, so that searches in
93 /// C++ can look into the "tag" namespace during ordinary lookup.
95 /// Decl currently provides 15 bits of IDNS bits.
96 enum IdentifierNamespace {
97 /// Labels, declared with 'x:' and referenced with 'goto x'.
100 /// Tags, declared with 'struct foo;' and referenced with
101 /// 'struct foo'. All tags are also types. This is what
102 /// elaborated-type-specifiers look for in C.
105 /// Types, declared with 'struct foo', typedefs, etc.
106 /// This is what elaborated-type-specifiers look for in C++,
107 /// but note that it's ill-formed to find a non-tag.
110 /// Members, declared with object declarations within tag
111 /// definitions. In C, these can only be found by "qualified"
112 /// lookup in member expressions. In C++, they're found by
114 IDNS_Member = 0x0008,
116 /// Namespaces, declared with 'namespace foo {}'.
117 /// Lookup for nested-name-specifiers find these.
118 IDNS_Namespace = 0x0010,
120 /// Ordinary names. In C, everything that's not a label, tag,
121 /// or member ends up here.
122 IDNS_Ordinary = 0x0020,
124 /// Objective C @protocol.
125 IDNS_ObjCProtocol = 0x0040,
127 /// This declaration is a friend function. A friend function
128 /// declaration is always in this namespace but may also be in
129 /// IDNS_Ordinary if it was previously declared.
130 IDNS_OrdinaryFriend = 0x0080,
132 /// This declaration is a friend class. A friend class
133 /// declaration is always in this namespace but may also be in
134 /// IDNS_Tag|IDNS_Type if it was previously declared.
135 IDNS_TagFriend = 0x0100,
137 /// This declaration is a using declaration. A using declaration
138 /// *introduces* a number of other declarations into the current
139 /// scope, and those declarations use the IDNS of their targets,
140 /// but the actual using declarations go in this namespace.
143 /// This declaration is a C++ operator declared in a non-class
144 /// context. All such operators are also in IDNS_Ordinary.
145 /// C++ lexical operator lookup looks for these.
146 IDNS_NonMemberOperator = 0x0400
149 /// ObjCDeclQualifier - Qualifier used on types in method declarations
150 /// for remote messaging. They are meant for the arguments though and
151 /// applied to the Decls (ObjCMethodDecl and ParmVarDecl).
152 enum ObjCDeclQualifier {
157 OBJC_TQ_Bycopy = 0x8,
158 OBJC_TQ_Byref = 0x10,
159 OBJC_TQ_Oneway = 0x20
163 /// NextDeclInContext - The next declaration within the same lexical
164 /// DeclContext. These pointers form the linked list that is
165 /// traversed via DeclContext's decls_begin()/decls_end().
166 Decl *NextDeclInContext;
168 friend class DeclContext;
171 DeclContext *SemanticDC;
172 DeclContext *LexicalDC;
176 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
177 /// For declarations that don't contain C++ scope specifiers, it contains
178 /// the DeclContext where the Decl was declared.
179 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
180 /// with the context where it semantically belongs (SemanticDC) and the
181 /// context where it was lexically declared (LexicalDC).
185 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
187 /// void A::f(); // SemanticDC == namespace 'A'
188 /// // LexicalDC == global namespace
189 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
191 inline bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
192 inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
193 inline MultipleDC *getMultipleDC() const {
194 return DeclCtx.get<MultipleDC*>();
196 inline DeclContext *getSemanticDC() const {
197 return DeclCtx.get<DeclContext*>();
200 /// Loc - The location that this decl.
203 /// DeclKind - This indicates which class this is.
206 /// InvalidDecl - This indicates a semantic error occurred.
207 unsigned int InvalidDecl : 1;
209 /// HasAttrs - This indicates whether the decl has attributes or not.
210 unsigned int HasAttrs : 1;
212 /// Implicit - Whether this declaration was implicitly generated by
213 /// the implementation rather than explicitly written by the user.
216 /// \brief Whether this declaration was "used", meaning that a definition is
221 /// Access - Used by C++ decls for the access specifier.
222 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
224 friend class CXXClassMemberWrapper;
226 /// PCHLevel - the "level" of AST file from which this declaration was built.
227 unsigned PCHLevel : 2;
229 /// ChangedAfterLoad - if this declaration has changed since being loaded
230 bool ChangedAfterLoad : 1;
232 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
233 unsigned IdentifierNamespace : 15;
237 void CheckAccessDeclContext() const;
239 void CheckAccessDeclContext() const { }
244 Decl(Kind DK, DeclContext *DC, SourceLocation L)
245 : NextDeclInContext(0), DeclCtx(DC),
246 Loc(L), DeclKind(DK), InvalidDecl(0),
247 HasAttrs(false), Implicit(false), Used(false),
248 Access(AS_none), PCHLevel(0), ChangedAfterLoad(false),
249 IdentifierNamespace(getIdentifierNamespaceForKind(DK)) {
250 if (Decl::CollectingStats()) add(DK);
253 Decl(Kind DK, EmptyShell Empty)
254 : NextDeclInContext(0), DeclKind(DK), InvalidDecl(0),
255 HasAttrs(false), Implicit(false), Used(false),
256 Access(AS_none), PCHLevel(0), ChangedAfterLoad(false),
257 IdentifierNamespace(getIdentifierNamespaceForKind(DK)) {
258 if (Decl::CollectingStats()) add(DK);
265 /// \brief Source range that this declaration covers.
266 virtual SourceRange getSourceRange() const {
267 return SourceRange(getLocation(), getLocation());
269 SourceLocation getLocStart() const { return getSourceRange().getBegin(); }
270 SourceLocation getLocEnd() const { return getSourceRange().getEnd(); }
272 SourceLocation getLocation() const { return Loc; }
273 void setLocation(SourceLocation L) { Loc = L; }
275 Kind getKind() const { return DeclKind; }
276 const char *getDeclKindName() const;
278 Decl *getNextDeclInContext() { return NextDeclInContext; }
279 const Decl *getNextDeclInContext() const { return NextDeclInContext; }
281 DeclContext *getDeclContext() {
283 return getSemanticDC();
284 return getMultipleDC()->SemanticDC;
286 const DeclContext *getDeclContext() const {
287 return const_cast<Decl*>(this)->getDeclContext();
290 TranslationUnitDecl *getTranslationUnitDecl();
291 const TranslationUnitDecl *getTranslationUnitDecl() const {
292 return const_cast<Decl*>(this)->getTranslationUnitDecl();
295 bool isInAnonymousNamespace() const;
297 ASTContext &getASTContext() const;
299 void setAccess(AccessSpecifier AS) {
301 CheckAccessDeclContext();
304 AccessSpecifier getAccess() const {
305 CheckAccessDeclContext();
306 return AccessSpecifier(Access);
309 bool hasAttrs() const { return HasAttrs; }
310 void setAttrs(const AttrVec& Attrs);
311 AttrVec& getAttrs() {
312 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
314 const AttrVec &getAttrs() const;
315 void swapAttrs(Decl *D);
318 void addAttr(Attr *A) {
320 getAttrs().push_back(A);
322 setAttrs(AttrVec(1, A));
325 typedef AttrVec::const_iterator attr_iterator;
327 // FIXME: Do not rely on iterators having comparable singular values.
328 // Note that this should error out if they do not.
329 attr_iterator attr_begin() const {
330 return hasAttrs() ? getAttrs().begin() : 0;
332 attr_iterator attr_end() const {
333 return hasAttrs() ? getAttrs().end() : 0;
336 template <typename T>
337 specific_attr_iterator<T> specific_attr_begin() const {
338 return specific_attr_iterator<T>(attr_begin());
340 template <typename T>
341 specific_attr_iterator<T> specific_attr_end() const {
342 return specific_attr_iterator<T>(attr_end());
345 template<typename T> T *getAttr() const {
346 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : 0;
348 template<typename T> bool hasAttr() const {
349 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
352 /// getMaxAlignment - return the maximum alignment specified by attributes
353 /// on this decl, 0 if there are none.
354 unsigned getMaxAlignment() const {
355 return hasAttrs() ? getMaxAttrAlignment(getAttrs(), getASTContext()) : 0;
358 /// setInvalidDecl - Indicates the Decl had a semantic error. This
359 /// allows for graceful error recovery.
360 void setInvalidDecl(bool Invalid = true);
361 bool isInvalidDecl() const { return (bool) InvalidDecl; }
363 /// isImplicit - Indicates whether the declaration was implicitly
364 /// generated by the implementation. If false, this declaration
365 /// was written explicitly in the source code.
366 bool isImplicit() const { return Implicit; }
367 void setImplicit(bool I = true) { Implicit = I; }
369 /// \brief Whether this declaration was used, meaning that a definition
372 /// \param CheckUsedAttr When true, also consider the "used" attribute
373 /// (in addition to the "used" bit set by \c setUsed()) when determining
374 /// whether the function is used.
375 bool isUsed(bool CheckUsedAttr = true) const;
377 void setUsed(bool U = true) { Used = U; }
379 /// \brief Retrieve the level of precompiled header from which this
380 /// declaration was generated.
382 /// The PCH level of a declaration describes where the declaration originated
383 /// from. A PCH level of 0 indicates that the declaration was parsed from
384 /// source. A PCH level of 1 indicates that the declaration was loaded from
385 /// a top-level AST file. A PCH level 2 indicates that the declaration was
386 /// loaded from a PCH file the AST file depends on, and so on.
387 unsigned getPCHLevel() const { return PCHLevel; }
389 /// \brief The maximum PCH level that any declaration may have.
390 static const unsigned MaxPCHLevel = 3;
392 /// \brief Set the PCH level of this declaration.
393 void setPCHLevel(unsigned Level) {
394 assert(Level <= MaxPCHLevel && "PCH level exceeds the maximum");
398 /// \brief Query whether this declaration was changed in a significant way
399 /// since being loaded from an AST file.
401 /// In an epic violation of layering, what is "significant" is entirely
402 /// up to the serialization system, but implemented in AST and Sema.
403 bool isChangedSinceDeserialization() const { return ChangedAfterLoad; }
405 /// \brief Mark this declaration as having changed since deserialization, or
407 void setChangedSinceDeserialization(bool Changed) {
408 ChangedAfterLoad = Changed;
411 unsigned getIdentifierNamespace() const {
412 return IdentifierNamespace;
414 bool isInIdentifierNamespace(unsigned NS) const {
415 return getIdentifierNamespace() & NS;
417 static unsigned getIdentifierNamespaceForKind(Kind DK);
419 bool hasTagIdentifierNamespace() const {
420 return isTagIdentifierNamespace(getIdentifierNamespace());
422 static bool isTagIdentifierNamespace(unsigned NS) {
423 // TagDecls have Tag and Type set and may also have TagFriend.
424 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
427 /// getLexicalDeclContext - The declaration context where this Decl was
428 /// lexically declared (LexicalDC). May be different from
429 /// getDeclContext() (SemanticDC).
433 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
435 /// void A::f(); // SemanticDC == namespace 'A'
436 /// // LexicalDC == global namespace
437 DeclContext *getLexicalDeclContext() {
439 return getSemanticDC();
440 return getMultipleDC()->LexicalDC;
442 const DeclContext *getLexicalDeclContext() const {
443 return const_cast<Decl*>(this)->getLexicalDeclContext();
446 virtual bool isOutOfLine() const {
447 return getLexicalDeclContext() != getDeclContext();
450 /// setDeclContext - Set both the semantic and lexical DeclContext
452 void setDeclContext(DeclContext *DC);
454 void setLexicalDeclContext(DeclContext *DC);
456 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
457 /// scoped decl is defined outside the current function or method. This is
458 /// roughly global variables and functions, but also handles enums (which
459 /// could be defined inside or outside a function etc).
460 bool isDefinedOutsideFunctionOrMethod() const;
462 /// \brief Retrieves the "canonical" declaration of the given declaration.
463 virtual Decl *getCanonicalDecl() { return this; }
464 const Decl *getCanonicalDecl() const {
465 return const_cast<Decl*>(this)->getCanonicalDecl();
468 /// \brief Whether this particular Decl is a canonical one.
469 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
472 /// \brief Returns the next redeclaration or itself if this is the only decl.
474 /// Decl subclasses that can be redeclared should override this method so that
475 /// Decl::redecl_iterator can iterate over them.
476 virtual Decl *getNextRedeclaration() { return this; }
479 /// \brief Iterates through all the redeclarations of the same decl.
480 class redecl_iterator {
481 /// Current - The current declaration.
486 typedef Decl* value_type;
487 typedef Decl* reference;
488 typedef Decl* pointer;
489 typedef std::forward_iterator_tag iterator_category;
490 typedef std::ptrdiff_t difference_type;
492 redecl_iterator() : Current(0) { }
493 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
495 reference operator*() const { return Current; }
496 pointer operator->() const { return Current; }
498 redecl_iterator& operator++() {
499 assert(Current && "Advancing while iterator has reached end");
500 // Get either previous decl or latest decl.
501 Decl *Next = Current->getNextRedeclaration();
502 assert(Next && "Should return next redeclaration or itself, never null!");
503 Current = (Next != Starter ? Next : 0);
507 redecl_iterator operator++(int) {
508 redecl_iterator tmp(*this);
513 friend bool operator==(redecl_iterator x, redecl_iterator y) {
514 return x.Current == y.Current;
516 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
517 return x.Current != y.Current;
521 /// \brief Returns iterator for all the redeclarations of the same decl.
522 /// It will iterate at least once (when this decl is the only one).
523 redecl_iterator redecls_begin() const {
524 return redecl_iterator(const_cast<Decl*>(this));
526 redecl_iterator redecls_end() const { return redecl_iterator(); }
528 /// getBody - If this Decl represents a declaration for a body of code,
529 /// such as a function or method definition, this method returns the
530 /// top-level Stmt* of that body. Otherwise this method returns null.
531 virtual Stmt* getBody() const { return 0; }
533 /// \brief Returns true if this Decl represents a declaration for a body of
534 /// code, such as a function or method definition.
535 virtual bool hasBody() const { return getBody() != 0; }
537 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
538 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
539 SourceLocation getBodyRBrace() const;
541 // global temp stats (until we have a per-module visitor)
542 static void add(Kind k);
543 static bool CollectingStats(bool Enable = false);
544 static void PrintStats();
546 /// isTemplateParameter - Determines whether this declaration is a
547 /// template parameter.
548 bool isTemplateParameter() const;
550 /// isTemplateParameter - Determines whether this declaration is a
551 /// template parameter pack.
552 bool isTemplateParameterPack() const;
554 /// \brief Whether this declaration is a function or function template.
555 bool isFunctionOrFunctionTemplate() const;
557 /// \brief Changes the namespace of this declaration to reflect that it's
558 /// the object of a friend declaration.
560 /// These declarations appear in the lexical context of the friending
561 /// class, but in the semantic context of the actual entity. This property
562 /// applies only to a specific decl object; other redeclarations of the
563 /// same entity may not (and probably don't) share this property.
564 void setObjectOfFriendDecl(bool PreviouslyDeclared) {
565 unsigned OldNS = IdentifierNamespace;
566 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
567 IDNS_TagFriend | IDNS_OrdinaryFriend)) &&
568 "namespace includes neither ordinary nor tag");
569 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
570 IDNS_TagFriend | IDNS_OrdinaryFriend)) &&
571 "namespace includes other than ordinary or tag");
573 IdentifierNamespace = 0;
574 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
575 IdentifierNamespace |= IDNS_TagFriend;
576 if (PreviouslyDeclared) IdentifierNamespace |= IDNS_Tag | IDNS_Type;
579 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend)) {
580 IdentifierNamespace |= IDNS_OrdinaryFriend;
581 if (PreviouslyDeclared) IdentifierNamespace |= IDNS_Ordinary;
585 enum FriendObjectKind {
586 FOK_None, // not a friend object
587 FOK_Declared, // a friend of a previously-declared entity
588 FOK_Undeclared // a friend of a previously-undeclared entity
591 /// \brief Determines whether this declaration is the object of a
592 /// friend declaration and, if so, what kind.
594 /// There is currently no direct way to find the associated FriendDecl.
595 FriendObjectKind getFriendObjectKind() const {
597 = (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
598 if (!mask) return FOK_None;
599 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ?
600 FOK_Declared : FOK_Undeclared);
603 /// Specifies that this declaration is a C++ overloaded non-member.
604 void setNonMemberOperator() {
605 assert(getKind() == Function || getKind() == FunctionTemplate);
606 assert((IdentifierNamespace & IDNS_Ordinary) &&
607 "visible non-member operators should be in ordinary namespace");
608 IdentifierNamespace |= IDNS_NonMemberOperator;
611 // Implement isa/cast/dyncast/etc.
612 static bool classof(const Decl *) { return true; }
613 static bool classofKind(Kind K) { return true; }
614 static DeclContext *castToDeclContext(const Decl *);
615 static Decl *castFromDeclContext(const DeclContext *);
617 void print(llvm::raw_ostream &Out, unsigned Indentation = 0) const;
618 void print(llvm::raw_ostream &Out, const PrintingPolicy &Policy,
619 unsigned Indentation = 0) const;
620 static void printGroup(Decl** Begin, unsigned NumDecls,
621 llvm::raw_ostream &Out, const PrintingPolicy &Policy,
622 unsigned Indentation = 0);
626 const Attr *getAttrsImpl() const;
630 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
631 /// doing something to a specific decl.
632 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
638 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
639 SourceManager &sm, const char *Msg)
640 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
642 virtual void print(llvm::raw_ostream &OS) const;
645 class DeclContextLookupResult
646 : public std::pair<NamedDecl**,NamedDecl**> {
648 DeclContextLookupResult(NamedDecl **I, NamedDecl **E)
649 : std::pair<NamedDecl**,NamedDecl**>(I, E) {}
650 DeclContextLookupResult()
651 : std::pair<NamedDecl**,NamedDecl**>() {}
653 using std::pair<NamedDecl**,NamedDecl**>::operator=;
656 class DeclContextLookupConstResult
657 : public std::pair<NamedDecl*const*, NamedDecl*const*> {
659 DeclContextLookupConstResult(std::pair<NamedDecl**,NamedDecl**> R)
660 : std::pair<NamedDecl*const*, NamedDecl*const*>(R) {}
661 DeclContextLookupConstResult(NamedDecl * const *I, NamedDecl * const *E)
662 : std::pair<NamedDecl*const*, NamedDecl*const*>(I, E) {}
663 DeclContextLookupConstResult()
664 : std::pair<NamedDecl*const*, NamedDecl*const*>() {}
666 using std::pair<NamedDecl*const*,NamedDecl*const*>::operator=;
669 /// DeclContext - This is used only as base class of specific decl types that
670 /// can act as declaration contexts. These decls are (only the top classes
671 /// that directly derive from DeclContext are mentioned, not their subclasses):
673 /// TranslationUnitDecl
678 /// ObjCContainerDecl
683 /// DeclKind - This indicates which class this is.
684 Decl::Kind DeclKind : 8;
686 /// \brief Whether this declaration context also has some external
687 /// storage that contains additional declarations that are lexically
688 /// part of this context.
689 mutable bool ExternalLexicalStorage : 1;
691 /// \brief Whether this declaration context also has some external
692 /// storage that contains additional declarations that are visible
694 mutable bool ExternalVisibleStorage : 1;
696 /// \brief Pointer to the data structure used to lookup declarations
697 /// within this context (or a DependentStoredDeclsMap if this is a
698 /// dependent context).
699 mutable StoredDeclsMap *LookupPtr;
701 /// FirstDecl - The first declaration stored within this declaration
703 mutable Decl *FirstDecl;
705 /// LastDecl - The last declaration stored within this declaration
706 /// context. FIXME: We could probably cache this value somewhere
707 /// outside of the DeclContext, to reduce the size of DeclContext by
709 mutable Decl *LastDecl;
711 friend class ExternalASTSource;
714 DeclContext(Decl::Kind K)
715 : DeclKind(K), ExternalLexicalStorage(false),
716 ExternalVisibleStorage(false), LookupPtr(0), FirstDecl(0),
722 Decl::Kind getDeclKind() const {
725 const char *getDeclKindName() const;
727 /// getParent - Returns the containing DeclContext.
728 DeclContext *getParent() {
729 return cast<Decl>(this)->getDeclContext();
731 const DeclContext *getParent() const {
732 return const_cast<DeclContext*>(this)->getParent();
735 /// getLexicalParent - Returns the containing lexical DeclContext. May be
736 /// different from getParent, e.g.:
741 /// struct A::S {}; // getParent() == namespace 'A'
742 /// // getLexicalParent() == translation unit
744 DeclContext *getLexicalParent() {
745 return cast<Decl>(this)->getLexicalDeclContext();
747 const DeclContext *getLexicalParent() const {
748 return const_cast<DeclContext*>(this)->getLexicalParent();
751 DeclContext *getLookupParent();
753 const DeclContext *getLookupParent() const {
754 return const_cast<DeclContext*>(this)->getLookupParent();
757 ASTContext &getParentASTContext() const {
758 return cast<Decl>(this)->getASTContext();
761 bool isFunctionOrMethod() const {
764 case Decl::ObjCMethod:
767 return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
771 bool isFileContext() const {
772 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
775 bool isTranslationUnit() const {
776 return DeclKind == Decl::TranslationUnit;
779 bool isRecord() const {
780 return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
783 bool isNamespace() const {
784 return DeclKind == Decl::Namespace;
787 bool isInlineNamespace() const;
789 /// \brief Determines whether this context is dependent on a
790 /// template parameter.
791 bool isDependentContext() const;
793 /// isTransparentContext - Determines whether this context is a
794 /// "transparent" context, meaning that the members declared in this
795 /// context are semantically declared in the nearest enclosing
796 /// non-transparent (opaque) context but are lexically declared in
797 /// this context. For example, consider the enumerators of an
798 /// enumeration type:
804 /// Here, E is a transparent context, so its enumerator (Val1) will
805 /// appear (semantically) that it is in the same context of E.
806 /// Examples of transparent contexts include: enumerations (except for
807 /// C++0x scoped enums), and C++ linkage specifications.
808 bool isTransparentContext() const;
810 /// \brief Determine whether this declaration context is equivalent
811 /// to the declaration context DC.
812 bool Equals(const DeclContext *DC) const {
813 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
816 /// \brief Determine whether this declaration context encloses the
817 /// declaration context DC.
818 bool Encloses(const DeclContext *DC) const;
820 /// getPrimaryContext - There may be many different
821 /// declarations of the same entity (including forward declarations
822 /// of classes, multiple definitions of namespaces, etc.), each with
823 /// a different set of declarations. This routine returns the
824 /// "primary" DeclContext structure, which will contain the
825 /// information needed to perform name lookup into this context.
826 DeclContext *getPrimaryContext();
827 const DeclContext *getPrimaryContext() const {
828 return const_cast<DeclContext*>(this)->getPrimaryContext();
831 /// getRedeclContext - Retrieve the context in which an entity conflicts with
832 /// other entities of the same name, or where it is a redeclaration if the
833 /// two entities are compatible. This skips through transparent contexts.
834 DeclContext *getRedeclContext();
835 const DeclContext *getRedeclContext() const {
836 return const_cast<DeclContext *>(this)->getRedeclContext();
839 /// \brief Retrieve the nearest enclosing namespace context.
840 DeclContext *getEnclosingNamespaceContext();
841 const DeclContext *getEnclosingNamespaceContext() const {
842 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
845 /// \brief Test if this context is part of the enclosing namespace set of
846 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
847 /// isn't a namespace, this is equivalent to Equals().
849 /// The enclosing namespace set of a namespace is the namespace and, if it is
850 /// inline, its enclosing namespace, recursively.
851 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
853 /// getNextContext - If this is a DeclContext that may have other
854 /// DeclContexts that are semantically connected but syntactically
855 /// different, such as C++ namespaces, this routine retrieves the
856 /// next DeclContext in the link. Iteration through the chain of
857 /// DeclContexts should begin at the primary DeclContext and
858 /// continue until this function returns NULL. For example, given:
867 /// The first occurrence of namespace N will be the primary
868 /// DeclContext. Its getNextContext will return the second
869 /// occurrence of namespace N.
870 DeclContext *getNextContext();
872 /// decl_iterator - Iterates through the declarations stored
873 /// within this context.
874 class decl_iterator {
875 /// Current - The current declaration.
879 typedef Decl* value_type;
880 typedef Decl* reference;
881 typedef Decl* pointer;
882 typedef std::forward_iterator_tag iterator_category;
883 typedef std::ptrdiff_t difference_type;
885 decl_iterator() : Current(0) { }
886 explicit decl_iterator(Decl *C) : Current(C) { }
888 reference operator*() const { return Current; }
889 pointer operator->() const { return Current; }
891 decl_iterator& operator++() {
892 Current = Current->getNextDeclInContext();
896 decl_iterator operator++(int) {
897 decl_iterator tmp(*this);
902 friend bool operator==(decl_iterator x, decl_iterator y) {
903 return x.Current == y.Current;
905 friend bool operator!=(decl_iterator x, decl_iterator y) {
906 return x.Current != y.Current;
910 /// decls_begin/decls_end - Iterate over the declarations stored in
912 decl_iterator decls_begin() const;
913 decl_iterator decls_end() const;
914 bool decls_empty() const;
916 /// noload_decls_begin/end - Iterate over the declarations stored in this
917 /// context that are currently loaded; don't attempt to retrieve anything
918 /// from an external source.
919 decl_iterator noload_decls_begin() const;
920 decl_iterator noload_decls_end() const;
922 /// specific_decl_iterator - Iterates over a subrange of
923 /// declarations stored in a DeclContext, providing only those that
924 /// are of type SpecificDecl (or a class derived from it). This
925 /// iterator is used, for example, to provide iteration over just
926 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
927 template<typename SpecificDecl>
928 class specific_decl_iterator {
929 /// Current - The current, underlying declaration iterator, which
930 /// will either be NULL or will point to a declaration of
931 /// type SpecificDecl.
932 DeclContext::decl_iterator Current;
934 /// SkipToNextDecl - Advances the current position up to the next
935 /// declaration of type SpecificDecl that also meets the criteria
936 /// required by Acceptable.
937 void SkipToNextDecl() {
938 while (*Current && !isa<SpecificDecl>(*Current))
943 typedef SpecificDecl* value_type;
944 typedef SpecificDecl* reference;
945 typedef SpecificDecl* pointer;
946 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
948 typedef std::forward_iterator_tag iterator_category;
950 specific_decl_iterator() : Current() { }
952 /// specific_decl_iterator - Construct a new iterator over a
953 /// subset of the declarations the range [C,
954 /// end-of-declarations). If A is non-NULL, it is a pointer to a
955 /// member function of SpecificDecl that should return true for
956 /// all of the SpecificDecl instances that will be in the subset
957 /// of iterators. For example, if you want Objective-C instance
958 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
959 /// &ObjCMethodDecl::isInstanceMethod.
960 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
964 reference operator*() const { return cast<SpecificDecl>(*Current); }
965 pointer operator->() const { return cast<SpecificDecl>(*Current); }
967 specific_decl_iterator& operator++() {
973 specific_decl_iterator operator++(int) {
974 specific_decl_iterator tmp(*this);
980 operator==(const specific_decl_iterator& x, const specific_decl_iterator& y) {
981 return x.Current == y.Current;
985 operator!=(const specific_decl_iterator& x, const specific_decl_iterator& y) {
986 return x.Current != y.Current;
990 /// \brief Iterates over a filtered subrange of declarations stored
991 /// in a DeclContext.
993 /// This iterator visits only those declarations that are of type
994 /// SpecificDecl (or a class derived from it) and that meet some
995 /// additional run-time criteria. This iterator is used, for
996 /// example, to provide access to the instance methods within an
997 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
998 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
999 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1000 class filtered_decl_iterator {
1001 /// Current - The current, underlying declaration iterator, which
1002 /// will either be NULL or will point to a declaration of
1003 /// type SpecificDecl.
1004 DeclContext::decl_iterator Current;
1006 /// SkipToNextDecl - Advances the current position up to the next
1007 /// declaration of type SpecificDecl that also meets the criteria
1008 /// required by Acceptable.
1009 void SkipToNextDecl() {
1011 (!isa<SpecificDecl>(*Current) ||
1012 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1017 typedef SpecificDecl* value_type;
1018 typedef SpecificDecl* reference;
1019 typedef SpecificDecl* pointer;
1020 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
1022 typedef std::forward_iterator_tag iterator_category;
1024 filtered_decl_iterator() : Current() { }
1026 /// specific_decl_iterator - Construct a new iterator over a
1027 /// subset of the declarations the range [C,
1028 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1029 /// member function of SpecificDecl that should return true for
1030 /// all of the SpecificDecl instances that will be in the subset
1031 /// of iterators. For example, if you want Objective-C instance
1032 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1033 /// &ObjCMethodDecl::isInstanceMethod.
1034 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1038 reference operator*() const { return cast<SpecificDecl>(*Current); }
1039 pointer operator->() const { return cast<SpecificDecl>(*Current); }
1041 filtered_decl_iterator& operator++() {
1047 filtered_decl_iterator operator++(int) {
1048 filtered_decl_iterator tmp(*this);
1054 operator==(const filtered_decl_iterator& x, const filtered_decl_iterator& y) {
1055 return x.Current == y.Current;
1059 operator!=(const filtered_decl_iterator& x, const filtered_decl_iterator& y) {
1060 return x.Current != y.Current;
1064 /// @brief Add the declaration D into this context.
1066 /// This routine should be invoked when the declaration D has first
1067 /// been declared, to place D into the context where it was
1068 /// (lexically) defined. Every declaration must be added to one
1069 /// (and only one!) context, where it can be visited via
1070 /// [decls_begin(), decls_end()). Once a declaration has been added
1071 /// to its lexical context, the corresponding DeclContext owns the
1074 /// If D is also a NamedDecl, it will be made visible within its
1075 /// semantic context via makeDeclVisibleInContext.
1076 void addDecl(Decl *D);
1078 /// @brief Add the declaration D to this context without modifying
1079 /// any lookup tables.
1081 /// This is useful for some operations in dependent contexts where
1082 /// the semantic context might not be dependent; this basically
1083 /// only happens with friends.
1084 void addHiddenDecl(Decl *D);
1086 /// @brief Removes a declaration from this context.
1087 void removeDecl(Decl *D);
1089 /// lookup_iterator - An iterator that provides access to the results
1090 /// of looking up a name within this context.
1091 typedef NamedDecl **lookup_iterator;
1093 /// lookup_const_iterator - An iterator that provides non-mutable
1094 /// access to the results of lookup up a name within this context.
1095 typedef NamedDecl * const * lookup_const_iterator;
1097 typedef DeclContextLookupResult lookup_result;
1098 typedef DeclContextLookupConstResult lookup_const_result;
1100 /// lookup - Find the declarations (if any) with the given Name in
1101 /// this context. Returns a range of iterators that contains all of
1102 /// the declarations with this name, with object, function, member,
1103 /// and enumerator names preceding any tag name. Note that this
1104 /// routine will not look into parent contexts.
1105 lookup_result lookup(DeclarationName Name);
1106 lookup_const_result lookup(DeclarationName Name) const;
1108 /// @brief Makes a declaration visible within this context.
1110 /// This routine makes the declaration D visible to name lookup
1111 /// within this context and, if this is a transparent context,
1112 /// within its parent contexts up to the first enclosing
1113 /// non-transparent context. Making a declaration visible within a
1114 /// context does not transfer ownership of a declaration, and a
1115 /// declaration can be visible in many contexts that aren't its
1116 /// lexical context.
1118 /// If D is a redeclaration of an existing declaration that is
1119 /// visible from this context, as determined by
1120 /// NamedDecl::declarationReplaces, the previous declaration will be
1121 /// replaced with D.
1123 /// @param Recoverable true if it's okay to not add this decl to
1124 /// the lookup tables because it can be easily recovered by walking
1125 /// the declaration chains.
1126 void makeDeclVisibleInContext(NamedDecl *D, bool Recoverable = true);
1128 /// \brief Deserialize all the visible declarations from external storage.
1130 /// Name lookup deserializes visible declarations lazily, thus a DeclContext
1131 /// may not have a complete name lookup table. This function deserializes
1132 /// the rest of visible declarations from the external storage and completes
1133 /// the name lookup table.
1134 void MaterializeVisibleDeclsFromExternalStorage();
1136 /// udir_iterator - Iterates through the using-directives stored
1137 /// within this context.
1138 typedef UsingDirectiveDecl * const * udir_iterator;
1140 typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range;
1142 udir_iterator_range getUsingDirectives() const;
1144 udir_iterator using_directives_begin() const {
1145 return getUsingDirectives().first;
1148 udir_iterator using_directives_end() const {
1149 return getUsingDirectives().second;
1152 // These are all defined in DependentDiagnostic.h.
1153 class ddiag_iterator;
1154 inline ddiag_iterator ddiag_begin() const;
1155 inline ddiag_iterator ddiag_end() const;
1157 // Low-level accessors
1159 /// \brief Retrieve the internal representation of the lookup structure.
1160 StoredDeclsMap* getLookupPtr() const { return LookupPtr; }
1162 /// \brief Whether this DeclContext has external storage containing
1163 /// additional declarations that are lexically in this context.
1164 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1166 /// \brief State whether this DeclContext has external storage for
1167 /// declarations lexically in this context.
1168 void setHasExternalLexicalStorage(bool ES = true) {
1169 ExternalLexicalStorage = ES;
1172 /// \brief Whether this DeclContext has external storage containing
1173 /// additional declarations that are visible in this context.
1174 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1176 /// \brief State whether this DeclContext has external storage for
1177 /// declarations visible in this context.
1178 void setHasExternalVisibleStorage(bool ES = true) {
1179 ExternalVisibleStorage = ES;
1182 static bool classof(const Decl *D);
1183 static bool classof(const DeclContext *D) { return true; }
1184 #define DECL(NAME, BASE)
1185 #define DECL_CONTEXT(NAME) \
1186 static bool classof(const NAME##Decl *D) { return true; }
1187 #include "clang/AST/DeclNodes.inc"
1189 void dumpDeclContext() const;
1192 void LoadLexicalDeclsFromExternalStorage() const;
1194 friend class DependentDiagnostic;
1195 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1197 void buildLookup(DeclContext *DCtx);
1198 void makeDeclVisibleInContextImpl(NamedDecl *D);
1201 inline bool Decl::isTemplateParameter() const {
1202 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1203 getKind() == TemplateTemplateParm;
1206 // Specialization selected when ToTy is not a known subclass of DeclContext.
1207 template <class ToTy,
1208 bool IsKnownSubtype = ::llvm::is_base_of< DeclContext, ToTy>::value>
1209 struct cast_convert_decl_context {
1210 static const ToTy *doit(const DeclContext *Val) {
1211 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1214 static ToTy *doit(DeclContext *Val) {
1215 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1219 // Specialization selected when ToTy is a known subclass of DeclContext.
1220 template <class ToTy>
1221 struct cast_convert_decl_context<ToTy, true> {
1222 static const ToTy *doit(const DeclContext *Val) {
1223 return static_cast<const ToTy*>(Val);
1226 static ToTy *doit(DeclContext *Val) {
1227 return static_cast<ToTy*>(Val);
1236 /// isa<T>(DeclContext*)
1237 template<class ToTy>
1238 struct isa_impl_wrap<ToTy,
1239 const ::clang::DeclContext,const ::clang::DeclContext> {
1240 static bool doit(const ::clang::DeclContext &Val) {
1241 return ToTy::classofKind(Val.getDeclKind());
1244 template<class ToTy>
1245 struct isa_impl_wrap<ToTy, ::clang::DeclContext, ::clang::DeclContext>
1246 : public isa_impl_wrap<ToTy,
1247 const ::clang::DeclContext,const ::clang::DeclContext> {};
1249 /// cast<T>(DeclContext*)
1250 template<class ToTy>
1251 struct cast_convert_val<ToTy,
1252 const ::clang::DeclContext,const ::clang::DeclContext> {
1253 static const ToTy &doit(const ::clang::DeclContext &Val) {
1254 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1257 template<class ToTy>
1258 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
1259 static ToTy &doit(::clang::DeclContext &Val) {
1260 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
1263 template<class ToTy>
1264 struct cast_convert_val<ToTy,
1265 const ::clang::DeclContext*, const ::clang::DeclContext*> {
1266 static const ToTy *doit(const ::clang::DeclContext *Val) {
1267 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1270 template<class ToTy>
1271 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
1272 static ToTy *doit(::clang::DeclContext *Val) {
1273 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
1277 /// Implement cast_convert_val for Decl -> DeclContext conversions.
1278 template<class FromTy>
1279 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
1280 static ::clang::DeclContext &doit(const FromTy &Val) {
1281 return *FromTy::castToDeclContext(&Val);
1285 template<class FromTy>
1286 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
1287 static ::clang::DeclContext *doit(const FromTy *Val) {
1288 return FromTy::castToDeclContext(Val);
1292 template<class FromTy>
1293 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
1294 static const ::clang::DeclContext &doit(const FromTy &Val) {
1295 return *FromTy::castToDeclContext(&Val);
1299 template<class FromTy>
1300 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
1301 static const ::clang::DeclContext *doit(const FromTy *Val) {
1302 return FromTy::castToDeclContext(Val);
1306 } // end namespace llvm