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