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