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