DeclBase.h revision c6c8e0ec96bb64f1b9f543d7c8317c6090f80a30
1//===-- DeclBase.h - Base Classes for representing declarations -*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the Decl and DeclContext interfaces. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef LLVM_CLANG_AST_DECLBASE_H 15#define LLVM_CLANG_AST_DECLBASE_H 16 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" 22 23namespace clang { 24class DeclContext; 25class TranslationUnitDecl; 26class NamespaceDecl; 27class UsingDirectiveDecl; 28class NamedDecl; 29class FunctionDecl; 30class CXXRecordDecl; 31class EnumDecl; 32class ObjCMethodDecl; 33class ObjCContainerDecl; 34class ObjCInterfaceDecl; 35class ObjCCategoryDecl; 36class ObjCProtocolDecl; 37class ObjCImplementationDecl; 38class ObjCCategoryImplDecl; 39class ObjCImplDecl; 40class LinkageSpecDecl; 41class BlockDecl; 42class DeclarationName; 43class CompoundStmt; 44class StoredDeclsMap; 45class DependentDiagnostic; 46class ASTMutationListener; 47} 48 49namespace llvm { 50// DeclContext* is only 4-byte aligned on 32-bit systems. 51template<> 52 class PointerLikeTypeTraits<clang::DeclContext*> { 53 typedef clang::DeclContext* PT; 54public: 55 static inline void *getAsVoidPointer(PT P) { return P; } 56 static inline PT getFromVoidPointer(void *P) { 57 return static_cast<PT>(P); 58 } 59 enum { NumLowBitsAvailable = 2 }; 60}; 61} 62 63namespace clang { 64 65 /// \brief Captures the result of checking the availability of a 66 /// declaration. 67 enum AvailabilityResult { 68 AR_Available = 0, 69 AR_NotYetIntroduced, 70 AR_Deprecated, 71 AR_Unavailable 72 }; 73 74/// Decl - This represents one declaration (or definition), e.g. a variable, 75/// typedef, function, struct, etc. 76/// 77class Decl { 78public: 79 /// \brief Lists the kind of concrete classes of Decl. 80 enum Kind { 81#define DECL(DERIVED, BASE) DERIVED, 82#define ABSTRACT_DECL(DECL) 83#define DECL_RANGE(BASE, START, END) \ 84 first##BASE = START, last##BASE = END, 85#define LAST_DECL_RANGE(BASE, START, END) \ 86 first##BASE = START, last##BASE = END 87#include "clang/AST/DeclNodes.inc" 88 }; 89 90 /// \brief A placeholder type used to construct an empty shell of a 91 /// decl-derived type that will be filled in later (e.g., by some 92 /// deserialization method). 93 struct EmptyShell { }; 94 95 /// IdentifierNamespace - The different namespaces in which 96 /// declarations may appear. According to C99 6.2.3, there are 97 /// four namespaces, labels, tags, members and ordinary 98 /// identifiers. C++ describes lookup completely differently: 99 /// certain lookups merely "ignore" certain kinds of declarations, 100 /// usually based on whether the declaration is of a type, etc. 101 /// 102 /// These are meant as bitmasks, so that searches in 103 /// C++ can look into the "tag" namespace during ordinary lookup. 104 /// 105 /// Decl currently provides 15 bits of IDNS bits. 106 enum IdentifierNamespace { 107 /// Labels, declared with 'x:' and referenced with 'goto x'. 108 IDNS_Label = 0x0001, 109 110 /// Tags, declared with 'struct foo;' and referenced with 111 /// 'struct foo'. All tags are also types. This is what 112 /// elaborated-type-specifiers look for in C. 113 IDNS_Tag = 0x0002, 114 115 /// Types, declared with 'struct foo', typedefs, etc. 116 /// This is what elaborated-type-specifiers look for in C++, 117 /// but note that it's ill-formed to find a non-tag. 118 IDNS_Type = 0x0004, 119 120 /// Members, declared with object declarations within tag 121 /// definitions. In C, these can only be found by "qualified" 122 /// lookup in member expressions. In C++, they're found by 123 /// normal lookup. 124 IDNS_Member = 0x0008, 125 126 /// Namespaces, declared with 'namespace foo {}'. 127 /// Lookup for nested-name-specifiers find these. 128 IDNS_Namespace = 0x0010, 129 130 /// Ordinary names. In C, everything that's not a label, tag, 131 /// or member ends up here. 132 IDNS_Ordinary = 0x0020, 133 134 /// Objective C @protocol. 135 IDNS_ObjCProtocol = 0x0040, 136 137 /// This declaration is a friend function. A friend function 138 /// declaration is always in this namespace but may also be in 139 /// IDNS_Ordinary if it was previously declared. 140 IDNS_OrdinaryFriend = 0x0080, 141 142 /// This declaration is a friend class. A friend class 143 /// declaration is always in this namespace but may also be in 144 /// IDNS_Tag|IDNS_Type if it was previously declared. 145 IDNS_TagFriend = 0x0100, 146 147 /// This declaration is a using declaration. A using declaration 148 /// *introduces* a number of other declarations into the current 149 /// scope, and those declarations use the IDNS of their targets, 150 /// but the actual using declarations go in this namespace. 151 IDNS_Using = 0x0200, 152 153 /// This declaration is a C++ operator declared in a non-class 154 /// context. All such operators are also in IDNS_Ordinary. 155 /// C++ lexical operator lookup looks for these. 156 IDNS_NonMemberOperator = 0x0400 157 }; 158 159 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and 160 /// parameter types in method declarations. Other than remembering 161 /// them and mangling them into the method's signature string, these 162 /// are ignored by the compiler; they are consumed by certain 163 /// remote-messaging frameworks. 164 /// 165 /// in, inout, and out are mutually exclusive and apply only to 166 /// method parameters. bycopy and byref are mutually exclusive and 167 /// apply only to method parameters (?). oneway applies only to 168 /// results. All of these expect their corresponding parameter to 169 /// have a particular type. None of this is currently enforced by 170 /// clang. 171 /// 172 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier. 173 enum ObjCDeclQualifier { 174 OBJC_TQ_None = 0x0, 175 OBJC_TQ_In = 0x1, 176 OBJC_TQ_Inout = 0x2, 177 OBJC_TQ_Out = 0x4, 178 OBJC_TQ_Bycopy = 0x8, 179 OBJC_TQ_Byref = 0x10, 180 OBJC_TQ_Oneway = 0x20 181 }; 182 183protected: 184 // Enumeration values used in the bits stored in NextInContextAndBits. 185 enum { 186 /// \brief Whether this declaration is a top-level declaration (function, 187 /// global variable, etc.) that is lexically inside an objc container 188 /// definition. 189 TopLevelDeclInObjCContainerFlag = 0x01, 190 191 /// \brief Whether this declaration is private to the module in which it was 192 /// defined. 193 ModulePrivateFlag = 0x02 194 }; 195 196 /// \brief The next declaration within the same lexical 197 /// DeclContext. These pointers form the linked list that is 198 /// traversed via DeclContext's decls_begin()/decls_end(). 199 /// 200 /// The extra two bits are used for the TopLevelDeclInObjCContainer and 201 /// ModulePrivate bits. 202 llvm::PointerIntPair<Decl *, 2, unsigned> NextInContextAndBits; 203 204private: 205 friend class DeclContext; 206 207 struct MultipleDC { 208 DeclContext *SemanticDC; 209 DeclContext *LexicalDC; 210 }; 211 212 213 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*. 214 /// For declarations that don't contain C++ scope specifiers, it contains 215 /// the DeclContext where the Decl was declared. 216 /// For declarations with C++ scope specifiers, it contains a MultipleDC* 217 /// with the context where it semantically belongs (SemanticDC) and the 218 /// context where it was lexically declared (LexicalDC). 219 /// e.g.: 220 /// 221 /// namespace A { 222 /// void f(); // SemanticDC == LexicalDC == 'namespace A' 223 /// } 224 /// void A::f(); // SemanticDC == namespace 'A' 225 /// // LexicalDC == global namespace 226 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx; 227 228 inline bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); } 229 inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); } 230 inline MultipleDC *getMultipleDC() const { 231 return DeclCtx.get<MultipleDC*>(); 232 } 233 inline DeclContext *getSemanticDC() const { 234 return DeclCtx.get<DeclContext*>(); 235 } 236 237 /// Loc - The location of this decl. 238 SourceLocation Loc; 239 240 /// DeclKind - This indicates which class this is. 241 unsigned DeclKind : 8; 242 243 /// InvalidDecl - This indicates a semantic error occurred. 244 unsigned InvalidDecl : 1; 245 246 /// HasAttrs - This indicates whether the decl has attributes or not. 247 unsigned HasAttrs : 1; 248 249 /// Implicit - Whether this declaration was implicitly generated by 250 /// the implementation rather than explicitly written by the user. 251 unsigned Implicit : 1; 252 253 /// \brief Whether this declaration was "used", meaning that a definition is 254 /// required. 255 unsigned Used : 1; 256 257 /// \brief Whether this declaration was "referenced". 258 /// The difference with 'Used' is whether the reference appears in a 259 /// evaluated context or not, e.g. functions used in uninstantiated templates 260 /// are regarded as "referenced" but not "used". 261 unsigned Referenced : 1; 262 263protected: 264 /// Access - Used by C++ decls for the access specifier. 265 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum 266 unsigned Access : 2; 267 friend class CXXClassMemberWrapper; 268 269 /// \brief Whether this declaration was loaded from an AST file. 270 unsigned FromASTFile : 1; 271 272 /// \brief Whether this declaration is hidden from normal name lookup, e.g., 273 /// because it is was loaded from an AST file is either module-private or 274 /// because its submodule has not been made visible. 275 unsigned Hidden : 1; 276 277 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in. 278 unsigned IdentifierNamespace : 12; 279 280 /// \brief Whether the \c CachedLinkage field is active. 281 /// 282 /// This field is only valid for NamedDecls subclasses. 283 mutable unsigned HasCachedLinkage : 1; 284 285 /// \brief If \c HasCachedLinkage, the linkage of this declaration. 286 /// 287 /// This field is only valid for NamedDecls subclasses. 288 mutable unsigned CachedLinkage : 2; 289 290 friend class ASTDeclWriter; 291 friend class ASTDeclReader; 292 friend class ASTReader; 293 294private: 295 void CheckAccessDeclContext() const; 296 297protected: 298 299 Decl(Kind DK, DeclContext *DC, SourceLocation L) 300 : NextInContextAndBits(), DeclCtx(DC), 301 Loc(L), DeclKind(DK), InvalidDecl(0), 302 HasAttrs(false), Implicit(false), Used(false), Referenced(false), 303 Access(AS_none), FromASTFile(0), Hidden(0), 304 IdentifierNamespace(getIdentifierNamespaceForKind(DK)), 305 HasCachedLinkage(0) 306 { 307 if (Decl::CollectingStats()) add(DK); 308 } 309 310 Decl(Kind DK, EmptyShell Empty) 311 : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0), 312 HasAttrs(false), Implicit(false), Used(false), Referenced(false), 313 Access(AS_none), FromASTFile(0), Hidden(0), 314 IdentifierNamespace(getIdentifierNamespaceForKind(DK)), 315 HasCachedLinkage(0) 316 { 317 if (Decl::CollectingStats()) add(DK); 318 } 319 320 virtual ~Decl(); 321 322 /// \brief Allocate memory for a deserialized declaration. 323 /// 324 /// This routine must be used to allocate memory for any declaration that is 325 /// deserialized from a module file. 326 /// 327 /// \param Context The context in which we will allocate memory. 328 /// \param ID The global ID of the deserialized declaration. 329 /// \param Size The size of the allocated object. 330 static void *AllocateDeserializedDecl(const ASTContext &Context, 331 unsigned ID, 332 unsigned Size); 333 334public: 335 336 /// \brief Source range that this declaration covers. 337 virtual SourceRange getSourceRange() const { 338 return SourceRange(getLocation(), getLocation()); 339 } 340 SourceLocation getLocStart() const { return getSourceRange().getBegin(); } 341 SourceLocation getLocEnd() const { return getSourceRange().getEnd(); } 342 343 SourceLocation getLocation() const { return Loc; } 344 void setLocation(SourceLocation L) { Loc = L; } 345 346 Kind getKind() const { return static_cast<Kind>(DeclKind); } 347 const char *getDeclKindName() const; 348 349 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); } 350 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();} 351 352 DeclContext *getDeclContext() { 353 if (isInSemaDC()) 354 return getSemanticDC(); 355 return getMultipleDC()->SemanticDC; 356 } 357 const DeclContext *getDeclContext() const { 358 return const_cast<Decl*>(this)->getDeclContext(); 359 } 360 361 /// Finds the innermost non-closure context of this declaration. 362 /// That is, walk out the DeclContext chain, skipping any blocks. 363 DeclContext *getNonClosureContext(); 364 const DeclContext *getNonClosureContext() const { 365 return const_cast<Decl*>(this)->getNonClosureContext(); 366 } 367 368 TranslationUnitDecl *getTranslationUnitDecl(); 369 const TranslationUnitDecl *getTranslationUnitDecl() const { 370 return const_cast<Decl*>(this)->getTranslationUnitDecl(); 371 } 372 373 bool isInAnonymousNamespace() const; 374 375 ASTContext &getASTContext() const; 376 377 void setAccess(AccessSpecifier AS) { 378 Access = AS; 379#ifndef NDEBUG 380 CheckAccessDeclContext(); 381#endif 382 } 383 384 AccessSpecifier getAccess() const { 385#ifndef NDEBUG 386 CheckAccessDeclContext(); 387#endif 388 return AccessSpecifier(Access); 389 } 390 391 bool hasAttrs() const { return HasAttrs; } 392 void setAttrs(const AttrVec& Attrs); 393 AttrVec &getAttrs() { 394 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs()); 395 } 396 const AttrVec &getAttrs() const; 397 void swapAttrs(Decl *D); 398 void dropAttrs(); 399 400 void addAttr(Attr *A) { 401 if (hasAttrs()) 402 getAttrs().push_back(A); 403 else 404 setAttrs(AttrVec(1, A)); 405 } 406 407 typedef AttrVec::const_iterator attr_iterator; 408 409 // FIXME: Do not rely on iterators having comparable singular values. 410 // Note that this should error out if they do not. 411 attr_iterator attr_begin() const { 412 return hasAttrs() ? getAttrs().begin() : 0; 413 } 414 attr_iterator attr_end() const { 415 return hasAttrs() ? getAttrs().end() : 0; 416 } 417 418 template <typename T> 419 void dropAttr() { 420 if (!HasAttrs) return; 421 422 AttrVec &Attrs = getAttrs(); 423 for (unsigned i = 0, e = Attrs.size(); i != e; /* in loop */) { 424 if (isa<T>(Attrs[i])) { 425 Attrs.erase(Attrs.begin() + i); 426 --e; 427 } 428 else 429 ++i; 430 } 431 if (Attrs.empty()) 432 HasAttrs = false; 433 } 434 435 template <typename T> 436 specific_attr_iterator<T> specific_attr_begin() const { 437 return specific_attr_iterator<T>(attr_begin()); 438 } 439 template <typename T> 440 specific_attr_iterator<T> specific_attr_end() const { 441 return specific_attr_iterator<T>(attr_end()); 442 } 443 444 template<typename T> T *getAttr() const { 445 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : 0; 446 } 447 template<typename T> bool hasAttr() const { 448 return hasAttrs() && hasSpecificAttr<T>(getAttrs()); 449 } 450 451 /// getMaxAlignment - return the maximum alignment specified by attributes 452 /// on this decl, 0 if there are none. 453 unsigned getMaxAlignment() const { 454 return hasAttrs() ? getMaxAttrAlignment(getAttrs(), getASTContext()) : 0; 455 } 456 457 /// setInvalidDecl - Indicates the Decl had a semantic error. This 458 /// allows for graceful error recovery. 459 void setInvalidDecl(bool Invalid = true); 460 bool isInvalidDecl() const { return (bool) InvalidDecl; } 461 462 /// isImplicit - Indicates whether the declaration was implicitly 463 /// generated by the implementation. If false, this declaration 464 /// was written explicitly in the source code. 465 bool isImplicit() const { return Implicit; } 466 void setImplicit(bool I = true) { Implicit = I; } 467 468 /// \brief Whether this declaration was used, meaning that a definition 469 /// is required. 470 /// 471 /// \param CheckUsedAttr When true, also consider the "used" attribute 472 /// (in addition to the "used" bit set by \c setUsed()) when determining 473 /// whether the function is used. 474 bool isUsed(bool CheckUsedAttr = true) const; 475 476 void setUsed(bool U = true) { Used = U; } 477 478 /// \brief Whether this declaration was referenced. 479 bool isReferenced() const; 480 481 void setReferenced(bool R = true) { Referenced = R; } 482 483 /// \brief Whether this declaration is a top-level declaration (function, 484 /// global variable, etc.) that is lexically inside an objc container 485 /// definition. 486 bool isTopLevelDeclInObjCContainer() const { 487 return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag; 488 } 489 490 void setTopLevelDeclInObjCContainer(bool V = true) { 491 unsigned Bits = NextInContextAndBits.getInt(); 492 if (V) 493 Bits |= TopLevelDeclInObjCContainerFlag; 494 else 495 Bits &= ~TopLevelDeclInObjCContainerFlag; 496 NextInContextAndBits.setInt(Bits); 497 } 498 499protected: 500 /// \brief Whether this declaration was marked as being private to the 501 /// module in which it was defined. 502 bool isModulePrivate() const { 503 return NextInContextAndBits.getInt() & ModulePrivateFlag; 504 } 505 506 /// \brief Specify whether this declaration was marked as being private 507 /// to the module in which it was defined. 508 void setModulePrivate(bool MP = true) { 509 unsigned Bits = NextInContextAndBits.getInt(); 510 if (MP) 511 Bits |= ModulePrivateFlag; 512 else 513 Bits &= ~ModulePrivateFlag; 514 NextInContextAndBits.setInt(Bits); 515 } 516 517 /// \brief Set the owning module ID. 518 void setOwningModuleID(unsigned ID) { 519 assert(isFromASTFile() && "Only works on a deserialized declaration"); 520 *((unsigned*)this - 2) = ID; 521 } 522 523public: 524 525 /// \brief Determine the availability of the given declaration. 526 /// 527 /// This routine will determine the most restrictive availability of 528 /// the given declaration (e.g., preferring 'unavailable' to 529 /// 'deprecated'). 530 /// 531 /// \param Message If non-NULL and the result is not \c 532 /// AR_Available, will be set to a (possibly empty) message 533 /// describing why the declaration has not been introduced, is 534 /// deprecated, or is unavailable. 535 AvailabilityResult getAvailability(std::string *Message = 0) const; 536 537 /// \brief Determine whether this declaration is marked 'deprecated'. 538 /// 539 /// \param Message If non-NULL and the declaration is deprecated, 540 /// this will be set to the message describing why the declaration 541 /// was deprecated (which may be empty). 542 bool isDeprecated(std::string *Message = 0) const { 543 return getAvailability(Message) == AR_Deprecated; 544 } 545 546 /// \brief Determine whether this declaration is marked 'unavailable'. 547 /// 548 /// \param Message If non-NULL and the declaration is unavailable, 549 /// this will be set to the message describing why the declaration 550 /// was made unavailable (which may be empty). 551 bool isUnavailable(std::string *Message = 0) const { 552 return getAvailability(Message) == AR_Unavailable; 553 } 554 555 /// \brief Determine whether this is a weak-imported symbol. 556 /// 557 /// Weak-imported symbols are typically marked with the 558 /// 'weak_import' attribute, but may also be marked with an 559 /// 'availability' attribute where we're targing a platform prior to 560 /// the introduction of this feature. 561 bool isWeakImported() const; 562 563 /// \brief Determines whether this symbol can be weak-imported, 564 /// e.g., whether it would be well-formed to add the weak_import 565 /// attribute. 566 /// 567 /// \param IsDefinition Set to \c true to indicate that this 568 /// declaration cannot be weak-imported because it has a definition. 569 bool canBeWeakImported(bool &IsDefinition) const; 570 571 /// \brief Determine whether this declaration came from an AST file (such as 572 /// a precompiled header or module) rather than having been parsed. 573 bool isFromASTFile() const { return FromASTFile; } 574 575 /// \brief Retrieve the global declaration ID associated with this 576 /// declaration, which specifies where in the 577 unsigned getGlobalID() const { 578 if (isFromASTFile()) 579 return *((const unsigned*)this - 1); 580 return 0; 581 } 582 583 /// \brief Retrieve the global ID of the module that owns this particular 584 /// declaration. 585 unsigned getOwningModuleID() const { 586 if (isFromASTFile()) 587 return *((const unsigned*)this - 2); 588 589 return 0; 590 } 591 592 unsigned getIdentifierNamespace() const { 593 return IdentifierNamespace; 594 } 595 bool isInIdentifierNamespace(unsigned NS) const { 596 return getIdentifierNamespace() & NS; 597 } 598 static unsigned getIdentifierNamespaceForKind(Kind DK); 599 600 bool hasTagIdentifierNamespace() const { 601 return isTagIdentifierNamespace(getIdentifierNamespace()); 602 } 603 static bool isTagIdentifierNamespace(unsigned NS) { 604 // TagDecls have Tag and Type set and may also have TagFriend. 605 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type); 606 } 607 608 /// getLexicalDeclContext - The declaration context where this Decl was 609 /// lexically declared (LexicalDC). May be different from 610 /// getDeclContext() (SemanticDC). 611 /// e.g.: 612 /// 613 /// namespace A { 614 /// void f(); // SemanticDC == LexicalDC == 'namespace A' 615 /// } 616 /// void A::f(); // SemanticDC == namespace 'A' 617 /// // LexicalDC == global namespace 618 DeclContext *getLexicalDeclContext() { 619 if (isInSemaDC()) 620 return getSemanticDC(); 621 return getMultipleDC()->LexicalDC; 622 } 623 const DeclContext *getLexicalDeclContext() const { 624 return const_cast<Decl*>(this)->getLexicalDeclContext(); 625 } 626 627 virtual bool isOutOfLine() const { 628 return getLexicalDeclContext() != getDeclContext(); 629 } 630 631 /// setDeclContext - Set both the semantic and lexical DeclContext 632 /// to DC. 633 void setDeclContext(DeclContext *DC); 634 635 void setLexicalDeclContext(DeclContext *DC); 636 637 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this 638 /// scoped decl is defined outside the current function or method. This is 639 /// roughly global variables and functions, but also handles enums (which 640 /// could be defined inside or outside a function etc). 641 bool isDefinedOutsideFunctionOrMethod() const { 642 return getParentFunctionOrMethod() == 0; 643 } 644 645 /// \brief If this decl is defined inside a function/method/block it returns 646 /// the corresponding DeclContext, otherwise it returns null. 647 const DeclContext *getParentFunctionOrMethod() const; 648 DeclContext *getParentFunctionOrMethod() { 649 return const_cast<DeclContext*>( 650 const_cast<const Decl*>(this)->getParentFunctionOrMethod()); 651 } 652 653 /// \brief Retrieves the "canonical" declaration of the given declaration. 654 virtual Decl *getCanonicalDecl() { return this; } 655 const Decl *getCanonicalDecl() const { 656 return const_cast<Decl*>(this)->getCanonicalDecl(); 657 } 658 659 /// \brief Whether this particular Decl is a canonical one. 660 bool isCanonicalDecl() const { return getCanonicalDecl() == this; } 661 662protected: 663 /// \brief Returns the next redeclaration or itself if this is the only decl. 664 /// 665 /// Decl subclasses that can be redeclared should override this method so that 666 /// Decl::redecl_iterator can iterate over them. 667 virtual Decl *getNextRedeclaration() { return this; } 668 669public: 670 /// \brief Iterates through all the redeclarations of the same decl. 671 class redecl_iterator { 672 /// Current - The current declaration. 673 Decl *Current; 674 Decl *Starter; 675 676 public: 677 typedef Decl* value_type; 678 typedef Decl* reference; 679 typedef Decl* pointer; 680 typedef std::forward_iterator_tag iterator_category; 681 typedef std::ptrdiff_t difference_type; 682 683 redecl_iterator() : Current(0) { } 684 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { } 685 686 reference operator*() const { return Current; } 687 pointer operator->() const { return Current; } 688 689 redecl_iterator& operator++() { 690 assert(Current && "Advancing while iterator has reached end"); 691 // Get either previous decl or latest decl. 692 Decl *Next = Current->getNextRedeclaration(); 693 assert(Next && "Should return next redeclaration or itself, never null!"); 694 Current = (Next != Starter ? Next : 0); 695 return *this; 696 } 697 698 redecl_iterator operator++(int) { 699 redecl_iterator tmp(*this); 700 ++(*this); 701 return tmp; 702 } 703 704 friend bool operator==(redecl_iterator x, redecl_iterator y) { 705 return x.Current == y.Current; 706 } 707 friend bool operator!=(redecl_iterator x, redecl_iterator y) { 708 return x.Current != y.Current; 709 } 710 }; 711 712 /// \brief Returns iterator for all the redeclarations of the same decl. 713 /// It will iterate at least once (when this decl is the only one). 714 redecl_iterator redecls_begin() const { 715 return redecl_iterator(const_cast<Decl*>(this)); 716 } 717 redecl_iterator redecls_end() const { return redecl_iterator(); } 718 719 /// getBody - If this Decl represents a declaration for a body of code, 720 /// such as a function or method definition, this method returns the 721 /// top-level Stmt* of that body. Otherwise this method returns null. 722 virtual Stmt* getBody() const { return 0; } 723 724 /// \brief Returns true if this Decl represents a declaration for a body of 725 /// code, such as a function or method definition. 726 virtual bool hasBody() const { return getBody() != 0; } 727 728 /// getBodyRBrace - Gets the right brace of the body, if a body exists. 729 /// This works whether the body is a CompoundStmt or a CXXTryStmt. 730 SourceLocation getBodyRBrace() const; 731 732 // global temp stats (until we have a per-module visitor) 733 static void add(Kind k); 734 static bool CollectingStats(bool Enable = false); 735 static void PrintStats(); 736 737 /// isTemplateParameter - Determines whether this declaration is a 738 /// template parameter. 739 bool isTemplateParameter() const; 740 741 /// isTemplateParameter - Determines whether this declaration is a 742 /// template parameter pack. 743 bool isTemplateParameterPack() const; 744 745 /// \brief Whether this declaration is a parameter pack. 746 bool isParameterPack() const; 747 748 /// \brief returns true if this declaration is a template 749 bool isTemplateDecl() const; 750 751 /// \brief Whether this declaration is a function or function template. 752 bool isFunctionOrFunctionTemplate() const; 753 754 /// \brief Changes the namespace of this declaration to reflect that it's 755 /// the object of a friend declaration. 756 /// 757 /// These declarations appear in the lexical context of the friending 758 /// class, but in the semantic context of the actual entity. This property 759 /// applies only to a specific decl object; other redeclarations of the 760 /// same entity may not (and probably don't) share this property. 761 void setObjectOfFriendDecl(bool PreviouslyDeclared) { 762 unsigned OldNS = IdentifierNamespace; 763 assert((OldNS & (IDNS_Tag | IDNS_Ordinary | 764 IDNS_TagFriend | IDNS_OrdinaryFriend)) && 765 "namespace includes neither ordinary nor tag"); 766 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | 767 IDNS_TagFriend | IDNS_OrdinaryFriend)) && 768 "namespace includes other than ordinary or tag"); 769 770 IdentifierNamespace = 0; 771 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) { 772 IdentifierNamespace |= IDNS_TagFriend; 773 if (PreviouslyDeclared) IdentifierNamespace |= IDNS_Tag | IDNS_Type; 774 } 775 776 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend)) { 777 IdentifierNamespace |= IDNS_OrdinaryFriend; 778 if (PreviouslyDeclared) IdentifierNamespace |= IDNS_Ordinary; 779 } 780 } 781 782 enum FriendObjectKind { 783 FOK_None, // not a friend object 784 FOK_Declared, // a friend of a previously-declared entity 785 FOK_Undeclared // a friend of a previously-undeclared entity 786 }; 787 788 /// \brief Determines whether this declaration is the object of a 789 /// friend declaration and, if so, what kind. 790 /// 791 /// There is currently no direct way to find the associated FriendDecl. 792 FriendObjectKind getFriendObjectKind() const { 793 unsigned mask 794 = (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend)); 795 if (!mask) return FOK_None; 796 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? 797 FOK_Declared : FOK_Undeclared); 798 } 799 800 /// Specifies that this declaration is a C++ overloaded non-member. 801 void setNonMemberOperator() { 802 assert(getKind() == Function || getKind() == FunctionTemplate); 803 assert((IdentifierNamespace & IDNS_Ordinary) && 804 "visible non-member operators should be in ordinary namespace"); 805 IdentifierNamespace |= IDNS_NonMemberOperator; 806 } 807 808 // Implement isa/cast/dyncast/etc. 809 static bool classof(const Decl *) { return true; } 810 static bool classofKind(Kind K) { return true; } 811 static DeclContext *castToDeclContext(const Decl *); 812 static Decl *castFromDeclContext(const DeclContext *); 813 814 void print(raw_ostream &Out, unsigned Indentation = 0, 815 bool PrintInstantiation = false) const; 816 void print(raw_ostream &Out, const PrintingPolicy &Policy, 817 unsigned Indentation = 0, bool PrintInstantiation = false) const; 818 static void printGroup(Decl** Begin, unsigned NumDecls, 819 raw_ostream &Out, const PrintingPolicy &Policy, 820 unsigned Indentation = 0); 821 void dump() const; 822 void dumpXML() const; 823 void dumpXML(raw_ostream &OS) const; 824 825private: 826 const Attr *getAttrsImpl() const; 827 828protected: 829 ASTMutationListener *getASTMutationListener() const; 830}; 831 832/// \brief Determine whether two declarations declare the same entity. 833inline bool declaresSameEntity(const Decl *D1, const Decl *D2) { 834 if (!D1 || !D2) 835 return false; 836 837 if (D1 == D2) 838 return true; 839 840 return D1->getCanonicalDecl() == D2->getCanonicalDecl(); 841} 842 843/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when 844/// doing something to a specific decl. 845class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry { 846 const Decl *TheDecl; 847 SourceLocation Loc; 848 SourceManager &SM; 849 const char *Message; 850public: 851 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L, 852 SourceManager &sm, const char *Msg) 853 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {} 854 855 virtual void print(raw_ostream &OS) const; 856}; 857 858class DeclContextLookupResult 859 : public std::pair<NamedDecl**,NamedDecl**> { 860public: 861 DeclContextLookupResult(NamedDecl **I, NamedDecl **E) 862 : std::pair<NamedDecl**,NamedDecl**>(I, E) {} 863 DeclContextLookupResult() 864 : std::pair<NamedDecl**,NamedDecl**>() {} 865 866 using std::pair<NamedDecl**,NamedDecl**>::operator=; 867}; 868 869class DeclContextLookupConstResult 870 : public std::pair<NamedDecl*const*, NamedDecl*const*> { 871public: 872 DeclContextLookupConstResult(std::pair<NamedDecl**,NamedDecl**> R) 873 : std::pair<NamedDecl*const*, NamedDecl*const*>(R) {} 874 DeclContextLookupConstResult(NamedDecl * const *I, NamedDecl * const *E) 875 : std::pair<NamedDecl*const*, NamedDecl*const*>(I, E) {} 876 DeclContextLookupConstResult() 877 : std::pair<NamedDecl*const*, NamedDecl*const*>() {} 878 879 using std::pair<NamedDecl*const*,NamedDecl*const*>::operator=; 880}; 881 882/// DeclContext - This is used only as base class of specific decl types that 883/// can act as declaration contexts. These decls are (only the top classes 884/// that directly derive from DeclContext are mentioned, not their subclasses): 885/// 886/// TranslationUnitDecl 887/// NamespaceDecl 888/// FunctionDecl 889/// TagDecl 890/// ObjCMethodDecl 891/// ObjCContainerDecl 892/// LinkageSpecDecl 893/// BlockDecl 894/// 895class DeclContext { 896 /// DeclKind - This indicates which class this is. 897 unsigned DeclKind : 8; 898 899 /// \brief Whether this declaration context also has some external 900 /// storage that contains additional declarations that are lexically 901 /// part of this context. 902 mutable unsigned ExternalLexicalStorage : 1; 903 904 /// \brief Whether this declaration context also has some external 905 /// storage that contains additional declarations that are visible 906 /// in this context. 907 mutable unsigned ExternalVisibleStorage : 1; 908 909 /// \brief Pointer to the data structure used to lookup declarations 910 /// within this context (or a DependentStoredDeclsMap if this is a 911 /// dependent context). 912 mutable StoredDeclsMap *LookupPtr; 913 914protected: 915 /// FirstDecl - The first declaration stored within this declaration 916 /// context. 917 mutable Decl *FirstDecl; 918 919 /// LastDecl - The last declaration stored within this declaration 920 /// context. FIXME: We could probably cache this value somewhere 921 /// outside of the DeclContext, to reduce the size of DeclContext by 922 /// another pointer. 923 mutable Decl *LastDecl; 924 925 friend class ExternalASTSource; 926 927 /// \brief Build up a chain of declarations. 928 /// 929 /// \returns the first/last pair of declarations. 930 static std::pair<Decl *, Decl *> 931 BuildDeclChain(const SmallVectorImpl<Decl*> &Decls, bool FieldsAlreadyLoaded); 932 933 DeclContext(Decl::Kind K) 934 : DeclKind(K), ExternalLexicalStorage(false), 935 ExternalVisibleStorage(false), LookupPtr(0), FirstDecl(0), 936 LastDecl(0) { } 937 938public: 939 ~DeclContext(); 940 941 Decl::Kind getDeclKind() const { 942 return static_cast<Decl::Kind>(DeclKind); 943 } 944 const char *getDeclKindName() const; 945 946 /// getParent - Returns the containing DeclContext. 947 DeclContext *getParent() { 948 return cast<Decl>(this)->getDeclContext(); 949 } 950 const DeclContext *getParent() const { 951 return const_cast<DeclContext*>(this)->getParent(); 952 } 953 954 /// getLexicalParent - Returns the containing lexical DeclContext. May be 955 /// different from getParent, e.g.: 956 /// 957 /// namespace A { 958 /// struct S; 959 /// } 960 /// struct A::S {}; // getParent() == namespace 'A' 961 /// // getLexicalParent() == translation unit 962 /// 963 DeclContext *getLexicalParent() { 964 return cast<Decl>(this)->getLexicalDeclContext(); 965 } 966 const DeclContext *getLexicalParent() const { 967 return const_cast<DeclContext*>(this)->getLexicalParent(); 968 } 969 970 DeclContext *getLookupParent(); 971 972 const DeclContext *getLookupParent() const { 973 return const_cast<DeclContext*>(this)->getLookupParent(); 974 } 975 976 ASTContext &getParentASTContext() const { 977 return cast<Decl>(this)->getASTContext(); 978 } 979 980 bool isClosure() const { 981 return DeclKind == Decl::Block; 982 } 983 984 bool isObjCContainer() const { 985 switch (DeclKind) { 986 case Decl::ObjCCategory: 987 case Decl::ObjCCategoryImpl: 988 case Decl::ObjCImplementation: 989 case Decl::ObjCInterface: 990 case Decl::ObjCProtocol: 991 return true; 992 } 993 return false; 994 } 995 996 bool isFunctionOrMethod() const { 997 switch (DeclKind) { 998 case Decl::Block: 999 case Decl::ObjCMethod: 1000 return true; 1001 default: 1002 return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction; 1003 } 1004 } 1005 1006 bool isFileContext() const { 1007 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace; 1008 } 1009 1010 bool isTranslationUnit() const { 1011 return DeclKind == Decl::TranslationUnit; 1012 } 1013 1014 bool isRecord() const { 1015 return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord; 1016 } 1017 1018 bool isNamespace() const { 1019 return DeclKind == Decl::Namespace; 1020 } 1021 1022 bool isInlineNamespace() const; 1023 1024 /// \brief Determines whether this context is dependent on a 1025 /// template parameter. 1026 bool isDependentContext() const; 1027 1028 /// isTransparentContext - Determines whether this context is a 1029 /// "transparent" context, meaning that the members declared in this 1030 /// context are semantically declared in the nearest enclosing 1031 /// non-transparent (opaque) context but are lexically declared in 1032 /// this context. For example, consider the enumerators of an 1033 /// enumeration type: 1034 /// @code 1035 /// enum E { 1036 /// Val1 1037 /// }; 1038 /// @endcode 1039 /// Here, E is a transparent context, so its enumerator (Val1) will 1040 /// appear (semantically) that it is in the same context of E. 1041 /// Examples of transparent contexts include: enumerations (except for 1042 /// C++0x scoped enums), and C++ linkage specifications. 1043 bool isTransparentContext() const; 1044 1045 /// \brief Determines whether this context is, or is nested within, 1046 /// a C++ extern "C" linkage spec. 1047 bool isExternCContext() const; 1048 1049 /// \brief Determine whether this declaration context is equivalent 1050 /// to the declaration context DC. 1051 bool Equals(const DeclContext *DC) const { 1052 return DC && this->getPrimaryContext() == DC->getPrimaryContext(); 1053 } 1054 1055 /// \brief Determine whether this declaration context encloses the 1056 /// declaration context DC. 1057 bool Encloses(const DeclContext *DC) const; 1058 1059 /// \brief Find the nearest non-closure ancestor of this context, 1060 /// i.e. the innermost semantic parent of this context which is not 1061 /// a closure. A context may be its own non-closure ancestor. 1062 DeclContext *getNonClosureAncestor(); 1063 const DeclContext *getNonClosureAncestor() const { 1064 return const_cast<DeclContext*>(this)->getNonClosureAncestor(); 1065 } 1066 1067 /// getPrimaryContext - There may be many different 1068 /// declarations of the same entity (including forward declarations 1069 /// of classes, multiple definitions of namespaces, etc.), each with 1070 /// a different set of declarations. This routine returns the 1071 /// "primary" DeclContext structure, which will contain the 1072 /// information needed to perform name lookup into this context. 1073 DeclContext *getPrimaryContext(); 1074 const DeclContext *getPrimaryContext() const { 1075 return const_cast<DeclContext*>(this)->getPrimaryContext(); 1076 } 1077 1078 /// getRedeclContext - Retrieve the context in which an entity conflicts with 1079 /// other entities of the same name, or where it is a redeclaration if the 1080 /// two entities are compatible. This skips through transparent contexts. 1081 DeclContext *getRedeclContext(); 1082 const DeclContext *getRedeclContext() const { 1083 return const_cast<DeclContext *>(this)->getRedeclContext(); 1084 } 1085 1086 /// \brief Retrieve the nearest enclosing namespace context. 1087 DeclContext *getEnclosingNamespaceContext(); 1088 const DeclContext *getEnclosingNamespaceContext() const { 1089 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext(); 1090 } 1091 1092 /// \brief Test if this context is part of the enclosing namespace set of 1093 /// the context NS, as defined in C++0x [namespace.def]p9. If either context 1094 /// isn't a namespace, this is equivalent to Equals(). 1095 /// 1096 /// The enclosing namespace set of a namespace is the namespace and, if it is 1097 /// inline, its enclosing namespace, recursively. 1098 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const; 1099 1100 /// \\brief Collects all of the declaration contexts that are semantically 1101 /// connected to this declaration context. 1102 /// 1103 /// For declaration contexts that have multiple semantically connected but 1104 /// syntactically distinct contexts, such as C++ namespaces, this routine 1105 /// retrieves the complete set of such declaration contexts in source order. 1106 /// For example, given: 1107 /// 1108 /// \code 1109 /// namespace N { 1110 /// int x; 1111 /// } 1112 /// namespace N { 1113 /// int y; 1114 /// } 1115 /// \endcode 1116 /// 1117 /// The \c Contexts parameter will contain both definitions of N. 1118 /// 1119 /// \param Contexts Will be cleared and set to the set of declaration 1120 /// contexts that are semanticaly connected to this declaration context, 1121 /// in source order, including this context (which may be the only result, 1122 /// for non-namespace contexts). 1123 void collectAllContexts(llvm::SmallVectorImpl<DeclContext *> &Contexts); 1124 1125 /// decl_iterator - Iterates through the declarations stored 1126 /// within this context. 1127 class decl_iterator { 1128 /// Current - The current declaration. 1129 Decl *Current; 1130 1131 public: 1132 typedef Decl* value_type; 1133 typedef Decl* reference; 1134 typedef Decl* pointer; 1135 typedef std::forward_iterator_tag iterator_category; 1136 typedef std::ptrdiff_t difference_type; 1137 1138 decl_iterator() : Current(0) { } 1139 explicit decl_iterator(Decl *C) : Current(C) { } 1140 1141 reference operator*() const { return Current; } 1142 pointer operator->() const { return Current; } 1143 1144 decl_iterator& operator++() { 1145 Current = Current->getNextDeclInContext(); 1146 return *this; 1147 } 1148 1149 decl_iterator operator++(int) { 1150 decl_iterator tmp(*this); 1151 ++(*this); 1152 return tmp; 1153 } 1154 1155 friend bool operator==(decl_iterator x, decl_iterator y) { 1156 return x.Current == y.Current; 1157 } 1158 friend bool operator!=(decl_iterator x, decl_iterator y) { 1159 return x.Current != y.Current; 1160 } 1161 }; 1162 1163 /// decls_begin/decls_end - Iterate over the declarations stored in 1164 /// this context. 1165 decl_iterator decls_begin() const; 1166 decl_iterator decls_end() const; 1167 bool decls_empty() const; 1168 1169 /// noload_decls_begin/end - Iterate over the declarations stored in this 1170 /// context that are currently loaded; don't attempt to retrieve anything 1171 /// from an external source. 1172 decl_iterator noload_decls_begin() const; 1173 decl_iterator noload_decls_end() const; 1174 1175 /// specific_decl_iterator - Iterates over a subrange of 1176 /// declarations stored in a DeclContext, providing only those that 1177 /// are of type SpecificDecl (or a class derived from it). This 1178 /// iterator is used, for example, to provide iteration over just 1179 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl). 1180 template<typename SpecificDecl> 1181 class specific_decl_iterator { 1182 /// Current - The current, underlying declaration iterator, which 1183 /// will either be NULL or will point to a declaration of 1184 /// type SpecificDecl. 1185 DeclContext::decl_iterator Current; 1186 1187 /// SkipToNextDecl - Advances the current position up to the next 1188 /// declaration of type SpecificDecl that also meets the criteria 1189 /// required by Acceptable. 1190 void SkipToNextDecl() { 1191 while (*Current && !isa<SpecificDecl>(*Current)) 1192 ++Current; 1193 } 1194 1195 public: 1196 typedef SpecificDecl* value_type; 1197 typedef SpecificDecl* reference; 1198 typedef SpecificDecl* pointer; 1199 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type 1200 difference_type; 1201 typedef std::forward_iterator_tag iterator_category; 1202 1203 specific_decl_iterator() : Current() { } 1204 1205 /// specific_decl_iterator - Construct a new iterator over a 1206 /// subset of the declarations the range [C, 1207 /// end-of-declarations). If A is non-NULL, it is a pointer to a 1208 /// member function of SpecificDecl that should return true for 1209 /// all of the SpecificDecl instances that will be in the subset 1210 /// of iterators. For example, if you want Objective-C instance 1211 /// methods, SpecificDecl will be ObjCMethodDecl and A will be 1212 /// &ObjCMethodDecl::isInstanceMethod. 1213 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) { 1214 SkipToNextDecl(); 1215 } 1216 1217 reference operator*() const { return cast<SpecificDecl>(*Current); } 1218 pointer operator->() const { return cast<SpecificDecl>(*Current); } 1219 1220 specific_decl_iterator& operator++() { 1221 ++Current; 1222 SkipToNextDecl(); 1223 return *this; 1224 } 1225 1226 specific_decl_iterator operator++(int) { 1227 specific_decl_iterator tmp(*this); 1228 ++(*this); 1229 return tmp; 1230 } 1231 1232 friend bool operator==(const specific_decl_iterator& x, 1233 const specific_decl_iterator& y) { 1234 return x.Current == y.Current; 1235 } 1236 1237 friend bool operator!=(const specific_decl_iterator& x, 1238 const specific_decl_iterator& y) { 1239 return x.Current != y.Current; 1240 } 1241 }; 1242 1243 /// \brief Iterates over a filtered subrange of declarations stored 1244 /// in a DeclContext. 1245 /// 1246 /// This iterator visits only those declarations that are of type 1247 /// SpecificDecl (or a class derived from it) and that meet some 1248 /// additional run-time criteria. This iterator is used, for 1249 /// example, to provide access to the instance methods within an 1250 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and 1251 /// Acceptable = ObjCMethodDecl::isInstanceMethod). 1252 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const> 1253 class filtered_decl_iterator { 1254 /// Current - The current, underlying declaration iterator, which 1255 /// will either be NULL or will point to a declaration of 1256 /// type SpecificDecl. 1257 DeclContext::decl_iterator Current; 1258 1259 /// SkipToNextDecl - Advances the current position up to the next 1260 /// declaration of type SpecificDecl that also meets the criteria 1261 /// required by Acceptable. 1262 void SkipToNextDecl() { 1263 while (*Current && 1264 (!isa<SpecificDecl>(*Current) || 1265 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)()))) 1266 ++Current; 1267 } 1268 1269 public: 1270 typedef SpecificDecl* value_type; 1271 typedef SpecificDecl* reference; 1272 typedef SpecificDecl* pointer; 1273 typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type 1274 difference_type; 1275 typedef std::forward_iterator_tag iterator_category; 1276 1277 filtered_decl_iterator() : Current() { } 1278 1279 /// specific_decl_iterator - Construct a new iterator over a 1280 /// subset of the declarations the range [C, 1281 /// end-of-declarations). If A is non-NULL, it is a pointer to a 1282 /// member function of SpecificDecl that should return true for 1283 /// all of the SpecificDecl instances that will be in the subset 1284 /// of iterators. For example, if you want Objective-C instance 1285 /// methods, SpecificDecl will be ObjCMethodDecl and A will be 1286 /// &ObjCMethodDecl::isInstanceMethod. 1287 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) { 1288 SkipToNextDecl(); 1289 } 1290 1291 reference operator*() const { return cast<SpecificDecl>(*Current); } 1292 pointer operator->() const { return cast<SpecificDecl>(*Current); } 1293 1294 filtered_decl_iterator& operator++() { 1295 ++Current; 1296 SkipToNextDecl(); 1297 return *this; 1298 } 1299 1300 filtered_decl_iterator operator++(int) { 1301 filtered_decl_iterator tmp(*this); 1302 ++(*this); 1303 return tmp; 1304 } 1305 1306 friend bool operator==(const filtered_decl_iterator& x, 1307 const filtered_decl_iterator& y) { 1308 return x.Current == y.Current; 1309 } 1310 1311 friend bool operator!=(const filtered_decl_iterator& x, 1312 const filtered_decl_iterator& y) { 1313 return x.Current != y.Current; 1314 } 1315 }; 1316 1317 /// @brief Add the declaration D into this context. 1318 /// 1319 /// This routine should be invoked when the declaration D has first 1320 /// been declared, to place D into the context where it was 1321 /// (lexically) defined. Every declaration must be added to one 1322 /// (and only one!) context, where it can be visited via 1323 /// [decls_begin(), decls_end()). Once a declaration has been added 1324 /// to its lexical context, the corresponding DeclContext owns the 1325 /// declaration. 1326 /// 1327 /// If D is also a NamedDecl, it will be made visible within its 1328 /// semantic context via makeDeclVisibleInContext. 1329 void addDecl(Decl *D); 1330 1331 /// @brief Add the declaration D into this context, but suppress 1332 /// searches for external declarations with the same name. 1333 /// 1334 /// Although analogous in function to addDecl, this removes an 1335 /// important check. This is only useful if the Decl is being 1336 /// added in response to an external search; in all other cases, 1337 /// addDecl() is the right function to use. 1338 /// See the ASTImporter for use cases. 1339 void addDeclInternal(Decl *D); 1340 1341 /// @brief Add the declaration D to this context without modifying 1342 /// any lookup tables. 1343 /// 1344 /// This is useful for some operations in dependent contexts where 1345 /// the semantic context might not be dependent; this basically 1346 /// only happens with friends. 1347 void addHiddenDecl(Decl *D); 1348 1349 /// @brief Removes a declaration from this context. 1350 void removeDecl(Decl *D); 1351 1352 /// lookup_iterator - An iterator that provides access to the results 1353 /// of looking up a name within this context. 1354 typedef NamedDecl **lookup_iterator; 1355 1356 /// lookup_const_iterator - An iterator that provides non-mutable 1357 /// access to the results of lookup up a name within this context. 1358 typedef NamedDecl * const * lookup_const_iterator; 1359 1360 typedef DeclContextLookupResult lookup_result; 1361 typedef DeclContextLookupConstResult lookup_const_result; 1362 1363 /// lookup - Find the declarations (if any) with the given Name in 1364 /// this context. Returns a range of iterators that contains all of 1365 /// the declarations with this name, with object, function, member, 1366 /// and enumerator names preceding any tag name. Note that this 1367 /// routine will not look into parent contexts. 1368 lookup_result lookup(DeclarationName Name); 1369 lookup_const_result lookup(DeclarationName Name) const; 1370 1371 /// \brief A simplistic name lookup mechanism that performs name lookup 1372 /// into this declaration context without consulting the external source. 1373 /// 1374 /// This function should almost never be used, because it subverts the 1375 /// usual relationship between a DeclContext and the external source. 1376 /// See the ASTImporter for the (few, but important) use cases. 1377 void localUncachedLookup(DeclarationName Name, 1378 llvm::SmallVectorImpl<NamedDecl *> &Results); 1379 1380 /// @brief Makes a declaration visible within this context. 1381 /// 1382 /// This routine makes the declaration D visible to name lookup 1383 /// within this context and, if this is a transparent context, 1384 /// within its parent contexts up to the first enclosing 1385 /// non-transparent context. Making a declaration visible within a 1386 /// context does not transfer ownership of a declaration, and a 1387 /// declaration can be visible in many contexts that aren't its 1388 /// lexical context. 1389 /// 1390 /// If D is a redeclaration of an existing declaration that is 1391 /// visible from this context, as determined by 1392 /// NamedDecl::declarationReplaces, the previous declaration will be 1393 /// replaced with D. 1394 /// 1395 /// @param Recoverable true if it's okay to not add this decl to 1396 /// the lookup tables because it can be easily recovered by walking 1397 /// the declaration chains. 1398 void makeDeclVisibleInContext(NamedDecl *D, bool Recoverable = true); 1399 1400 /// udir_iterator - Iterates through the using-directives stored 1401 /// within this context. 1402 typedef UsingDirectiveDecl * const * udir_iterator; 1403 1404 typedef std::pair<udir_iterator, udir_iterator> udir_iterator_range; 1405 1406 udir_iterator_range getUsingDirectives() const; 1407 1408 udir_iterator using_directives_begin() const { 1409 return getUsingDirectives().first; 1410 } 1411 1412 udir_iterator using_directives_end() const { 1413 return getUsingDirectives().second; 1414 } 1415 1416 // These are all defined in DependentDiagnostic.h. 1417 class ddiag_iterator; 1418 inline ddiag_iterator ddiag_begin() const; 1419 inline ddiag_iterator ddiag_end() const; 1420 1421 // Low-level accessors 1422 1423 /// \brief Retrieve the internal representation of the lookup structure. 1424 StoredDeclsMap* getLookupPtr() const { return LookupPtr; } 1425 1426 /// \brief Whether this DeclContext has external storage containing 1427 /// additional declarations that are lexically in this context. 1428 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; } 1429 1430 /// \brief State whether this DeclContext has external storage for 1431 /// declarations lexically in this context. 1432 void setHasExternalLexicalStorage(bool ES = true) { 1433 ExternalLexicalStorage = ES; 1434 } 1435 1436 /// \brief Whether this DeclContext has external storage containing 1437 /// additional declarations that are visible in this context. 1438 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; } 1439 1440 /// \brief State whether this DeclContext has external storage for 1441 /// declarations visible in this context. 1442 void setHasExternalVisibleStorage(bool ES = true) { 1443 ExternalVisibleStorage = ES; 1444 } 1445 1446 /// \brief Determine whether the given declaration is stored in the list of 1447 /// declarations lexically within this context. 1448 bool isDeclInLexicalTraversal(const Decl *D) const { 1449 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl || 1450 D == LastDecl); 1451 } 1452 1453 static bool classof(const Decl *D); 1454 static bool classof(const DeclContext *D) { return true; } 1455#define DECL(NAME, BASE) 1456#define DECL_CONTEXT(NAME) \ 1457 static bool classof(const NAME##Decl *D) { return true; } 1458#include "clang/AST/DeclNodes.inc" 1459 1460 void dumpDeclContext() const; 1461 1462private: 1463 void LoadLexicalDeclsFromExternalStorage() const; 1464 1465 /// @brief Makes a declaration visible within this context, but 1466 /// suppresses searches for external declarations with the same 1467 /// name. 1468 /// 1469 /// Analogous to makeDeclVisibleInContext, but for the exclusive 1470 /// use of addDeclInternal(). 1471 void makeDeclVisibleInContextInternal(NamedDecl *D, 1472 bool Recoverable = true); 1473 1474 friend class DependentDiagnostic; 1475 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const; 1476 1477 void buildLookup(DeclContext *DCtx); 1478 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal, 1479 bool Recoverable); 1480 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal); 1481}; 1482 1483inline bool Decl::isTemplateParameter() const { 1484 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm || 1485 getKind() == TemplateTemplateParm; 1486} 1487 1488// Specialization selected when ToTy is not a known subclass of DeclContext. 1489template <class ToTy, 1490 bool IsKnownSubtype = ::llvm::is_base_of< DeclContext, ToTy>::value> 1491struct cast_convert_decl_context { 1492 static const ToTy *doit(const DeclContext *Val) { 1493 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val)); 1494 } 1495 1496 static ToTy *doit(DeclContext *Val) { 1497 return static_cast<ToTy*>(Decl::castFromDeclContext(Val)); 1498 } 1499}; 1500 1501// Specialization selected when ToTy is a known subclass of DeclContext. 1502template <class ToTy> 1503struct cast_convert_decl_context<ToTy, true> { 1504 static const ToTy *doit(const DeclContext *Val) { 1505 return static_cast<const ToTy*>(Val); 1506 } 1507 1508 static ToTy *doit(DeclContext *Val) { 1509 return static_cast<ToTy*>(Val); 1510 } 1511}; 1512 1513 1514} // end clang. 1515 1516namespace llvm { 1517 1518/// isa<T>(DeclContext*) 1519template <typename To> 1520struct isa_impl<To, ::clang::DeclContext> { 1521 static bool doit(const ::clang::DeclContext &Val) { 1522 return To::classofKind(Val.getDeclKind()); 1523 } 1524}; 1525 1526/// cast<T>(DeclContext*) 1527template<class ToTy> 1528struct cast_convert_val<ToTy, 1529 const ::clang::DeclContext,const ::clang::DeclContext> { 1530 static const ToTy &doit(const ::clang::DeclContext &Val) { 1531 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val); 1532 } 1533}; 1534template<class ToTy> 1535struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> { 1536 static ToTy &doit(::clang::DeclContext &Val) { 1537 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val); 1538 } 1539}; 1540template<class ToTy> 1541struct cast_convert_val<ToTy, 1542 const ::clang::DeclContext*, const ::clang::DeclContext*> { 1543 static const ToTy *doit(const ::clang::DeclContext *Val) { 1544 return ::clang::cast_convert_decl_context<ToTy>::doit(Val); 1545 } 1546}; 1547template<class ToTy> 1548struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> { 1549 static ToTy *doit(::clang::DeclContext *Val) { 1550 return ::clang::cast_convert_decl_context<ToTy>::doit(Val); 1551 } 1552}; 1553 1554/// Implement cast_convert_val for Decl -> DeclContext conversions. 1555template<class FromTy> 1556struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> { 1557 static ::clang::DeclContext &doit(const FromTy &Val) { 1558 return *FromTy::castToDeclContext(&Val); 1559 } 1560}; 1561 1562template<class FromTy> 1563struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> { 1564 static ::clang::DeclContext *doit(const FromTy *Val) { 1565 return FromTy::castToDeclContext(Val); 1566 } 1567}; 1568 1569template<class FromTy> 1570struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> { 1571 static const ::clang::DeclContext &doit(const FromTy &Val) { 1572 return *FromTy::castToDeclContext(&Val); 1573 } 1574}; 1575 1576template<class FromTy> 1577struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> { 1578 static const ::clang::DeclContext *doit(const FromTy *Val) { 1579 return FromTy::castToDeclContext(Val); 1580 } 1581}; 1582 1583} // end namespace llvm 1584 1585#endif 1586