1 //===--- Lookup.h - Classes for name lookup ---------------------*- 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 LookupResult class, which is integral to 11 // Sema's name-lookup subsystem. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_CLANG_SEMA_LOOKUP_H 16 #define LLVM_CLANG_SEMA_LOOKUP_H 17 18 #include "clang/Sema/Sema.h" 19 #include "clang/AST/DeclCXX.h" 20 21 namespace clang { 22 23 /// @brief Represents the results of name lookup. 24 /// 25 /// An instance of the LookupResult class captures the results of a 26 /// single name lookup, which can return no result (nothing found), 27 /// a single declaration, a set of overloaded functions, or an 28 /// ambiguity. Use the getKind() method to determine which of these 29 /// results occurred for a given lookup. 30 class LookupResult { 31 public: 32 enum LookupResultKind { 33 /// @brief No entity found met the criteria. 34 NotFound = 0, 35 36 /// @brief No entity found met the criteria within the current 37 /// instantiation,, but there were dependent base classes of the 38 /// current instantiation that could not be searched. 39 NotFoundInCurrentInstantiation, 40 41 /// @brief Name lookup found a single declaration that met the 42 /// criteria. getFoundDecl() will return this declaration. 43 Found, 44 45 /// @brief Name lookup found a set of overloaded functions that 46 /// met the criteria. 47 FoundOverloaded, 48 49 /// @brief Name lookup found an unresolvable value declaration 50 /// and cannot yet complete. This only happens in C++ dependent 51 /// contexts with dependent using declarations. 52 FoundUnresolvedValue, 53 54 /// @brief Name lookup results in an ambiguity; use 55 /// getAmbiguityKind to figure out what kind of ambiguity 56 /// we have. 57 Ambiguous 58 }; 59 60 enum AmbiguityKind { 61 /// Name lookup results in an ambiguity because multiple 62 /// entities that meet the lookup criteria were found in 63 /// subobjects of different types. For example: 64 /// @code 65 /// struct A { void f(int); } 66 /// struct B { void f(double); } 67 /// struct C : A, B { }; 68 /// void test(C c) { 69 /// c.f(0); // error: A::f and B::f come from subobjects of different 70 /// // types. overload resolution is not performed. 71 /// } 72 /// @endcode 73 AmbiguousBaseSubobjectTypes, 74 75 /// Name lookup results in an ambiguity because multiple 76 /// nonstatic entities that meet the lookup criteria were found 77 /// in different subobjects of the same type. For example: 78 /// @code 79 /// struct A { int x; }; 80 /// struct B : A { }; 81 /// struct C : A { }; 82 /// struct D : B, C { }; 83 /// int test(D d) { 84 /// return d.x; // error: 'x' is found in two A subobjects (of B and C) 85 /// } 86 /// @endcode 87 AmbiguousBaseSubobjects, 88 89 /// Name lookup results in an ambiguity because multiple definitions 90 /// of entity that meet the lookup criteria were found in different 91 /// declaration contexts. 92 /// @code 93 /// namespace A { 94 /// int i; 95 /// namespace B { int i; } 96 /// int test() { 97 /// using namespace B; 98 /// return i; // error 'i' is found in namespace A and A::B 99 /// } 100 /// } 101 /// @endcode 102 AmbiguousReference, 103 104 /// Name lookup results in an ambiguity because an entity with a 105 /// tag name was hidden by an entity with an ordinary name from 106 /// a different context. 107 /// @code 108 /// namespace A { struct Foo {}; } 109 /// namespace B { void Foo(); } 110 /// namespace C { 111 /// using namespace A; 112 /// using namespace B; 113 /// } 114 /// void test() { 115 /// C::Foo(); // error: tag 'A::Foo' is hidden by an object in a 116 /// // different namespace 117 /// } 118 /// @endcode 119 AmbiguousTagHiding 120 }; 121 122 /// A little identifier for flagging temporary lookup results. 123 enum TemporaryToken { 124 Temporary 125 }; 126 127 typedef UnresolvedSetImpl::iterator iterator; 128 129 LookupResult(Sema &SemaRef, const DeclarationNameInfo &NameInfo, 130 Sema::LookupNameKind LookupKind, 131 Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration) ResultKind(NotFound)132 : ResultKind(NotFound), 133 Paths(0), 134 NamingClass(0), 135 SemaRef(SemaRef), 136 NameInfo(NameInfo), 137 LookupKind(LookupKind), 138 IDNS(0), 139 Redecl(Redecl != Sema::NotForRedeclaration), 140 HideTags(true), 141 Diagnose(Redecl == Sema::NotForRedeclaration) 142 { 143 configure(); 144 } 145 146 // TODO: consider whether this constructor should be restricted to take 147 // as input a const IndentifierInfo* (instead of Name), 148 // forcing other cases towards the constructor taking a DNInfo. 149 LookupResult(Sema &SemaRef, DeclarationName Name, 150 SourceLocation NameLoc, Sema::LookupNameKind LookupKind, 151 Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration) ResultKind(NotFound)152 : ResultKind(NotFound), 153 Paths(0), 154 NamingClass(0), 155 SemaRef(SemaRef), 156 NameInfo(Name, NameLoc), 157 LookupKind(LookupKind), 158 IDNS(0), 159 Redecl(Redecl != Sema::NotForRedeclaration), 160 HideTags(true), 161 Diagnose(Redecl == Sema::NotForRedeclaration) 162 { 163 configure(); 164 } 165 166 /// Creates a temporary lookup result, initializing its core data 167 /// using the information from another result. Diagnostics are always 168 /// disabled. LookupResult(TemporaryToken _,const LookupResult & Other)169 LookupResult(TemporaryToken _, const LookupResult &Other) 170 : ResultKind(NotFound), 171 Paths(0), 172 NamingClass(0), 173 SemaRef(Other.SemaRef), 174 NameInfo(Other.NameInfo), 175 LookupKind(Other.LookupKind), 176 IDNS(Other.IDNS), 177 Redecl(Other.Redecl), 178 HideTags(Other.HideTags), 179 Diagnose(false) 180 {} 181 ~LookupResult()182 ~LookupResult() { 183 if (Diagnose) diagnose(); 184 if (Paths) deletePaths(Paths); 185 } 186 187 /// Gets the name info to look up. getLookupNameInfo()188 const DeclarationNameInfo &getLookupNameInfo() const { 189 return NameInfo; 190 } 191 192 /// \brief Sets the name info to look up. setLookupNameInfo(const DeclarationNameInfo & NameInfo)193 void setLookupNameInfo(const DeclarationNameInfo &NameInfo) { 194 this->NameInfo = NameInfo; 195 } 196 197 /// Gets the name to look up. getLookupName()198 DeclarationName getLookupName() const { 199 return NameInfo.getName(); 200 } 201 202 /// \brief Sets the name to look up. setLookupName(DeclarationName Name)203 void setLookupName(DeclarationName Name) { 204 NameInfo.setName(Name); 205 } 206 207 /// Gets the kind of lookup to perform. getLookupKind()208 Sema::LookupNameKind getLookupKind() const { 209 return LookupKind; 210 } 211 212 /// True if this lookup is just looking for an existing declaration. isForRedeclaration()213 bool isForRedeclaration() const { 214 return Redecl; 215 } 216 217 /// \brief Determine whether this lookup is permitted to see hidden 218 /// declarations, such as those in modules that have not yet been imported. isHiddenDeclarationVisible()219 bool isHiddenDeclarationVisible() const { 220 return Redecl || LookupKind == Sema::LookupTagName; 221 } 222 223 /// Sets whether tag declarations should be hidden by non-tag 224 /// declarations during resolution. The default is true. setHideTags(bool Hide)225 void setHideTags(bool Hide) { 226 HideTags = Hide; 227 } 228 isAmbiguous()229 bool isAmbiguous() const { 230 return getResultKind() == Ambiguous; 231 } 232 233 /// Determines if this names a single result which is not an 234 /// unresolved value using decl. If so, it is safe to call 235 /// getFoundDecl(). isSingleResult()236 bool isSingleResult() const { 237 return getResultKind() == Found; 238 } 239 240 /// Determines if the results are overloaded. isOverloadedResult()241 bool isOverloadedResult() const { 242 return getResultKind() == FoundOverloaded; 243 } 244 isUnresolvableResult()245 bool isUnresolvableResult() const { 246 return getResultKind() == FoundUnresolvedValue; 247 } 248 getResultKind()249 LookupResultKind getResultKind() const { 250 sanity(); 251 return ResultKind; 252 } 253 getAmbiguityKind()254 AmbiguityKind getAmbiguityKind() const { 255 assert(isAmbiguous()); 256 return Ambiguity; 257 } 258 asUnresolvedSet()259 const UnresolvedSetImpl &asUnresolvedSet() const { 260 return Decls; 261 } 262 begin()263 iterator begin() const { return iterator(Decls.begin()); } end()264 iterator end() const { return iterator(Decls.end()); } 265 266 /// \brief Return true if no decls were found empty()267 bool empty() const { return Decls.empty(); } 268 269 /// \brief Return the base paths structure that's associated with 270 /// these results, or null if none is. getBasePaths()271 CXXBasePaths *getBasePaths() const { 272 return Paths; 273 } 274 275 /// \brief Determine whether the given declaration is visible to the 276 /// program. isVisible(NamedDecl * D)277 static bool isVisible(NamedDecl *D) { 278 // If this declaration is not hidden, it's visible. 279 if (!D->isHidden()) 280 return true; 281 282 // FIXME: We should be allowed to refer to a module-private name from 283 // within the same module, e.g., during template instantiation. 284 // This requires us know which module a particular declaration came from. 285 return false; 286 } 287 288 /// \brief Retrieve the accepted (re)declaration of the given declaration, 289 /// if there is one. getAcceptableDecl(NamedDecl * D)290 NamedDecl *getAcceptableDecl(NamedDecl *D) const { 291 if (!D->isInIdentifierNamespace(IDNS)) 292 return 0; 293 294 if (isHiddenDeclarationVisible() || isVisible(D)) 295 return D; 296 297 return getAcceptableDeclSlow(D); 298 } 299 300 private: 301 NamedDecl *getAcceptableDeclSlow(NamedDecl *D) const; 302 public: 303 304 /// \brief Returns the identifier namespace mask for this lookup. getIdentifierNamespace()305 unsigned getIdentifierNamespace() const { 306 return IDNS; 307 } 308 309 /// \brief Returns whether these results arose from performing a 310 /// lookup into a class. isClassLookup()311 bool isClassLookup() const { 312 return NamingClass != 0; 313 } 314 315 /// \brief Returns the 'naming class' for this lookup, i.e. the 316 /// class which was looked into to find these results. 317 /// 318 /// C++0x [class.access.base]p5: 319 /// The access to a member is affected by the class in which the 320 /// member is named. This naming class is the class in which the 321 /// member name was looked up and found. [Note: this class can be 322 /// explicit, e.g., when a qualified-id is used, or implicit, 323 /// e.g., when a class member access operator (5.2.5) is used 324 /// (including cases where an implicit "this->" is added). If both 325 /// a class member access operator and a qualified-id are used to 326 /// name the member (as in p->T::m), the class naming the member 327 /// is the class named by the nested-name-specifier of the 328 /// qualified-id (that is, T). -- end note ] 329 /// 330 /// This is set by the lookup routines when they find results in a class. getNamingClass()331 CXXRecordDecl *getNamingClass() const { 332 return NamingClass; 333 } 334 335 /// \brief Sets the 'naming class' for this lookup. setNamingClass(CXXRecordDecl * Record)336 void setNamingClass(CXXRecordDecl *Record) { 337 NamingClass = Record; 338 } 339 340 /// \brief Returns the base object type associated with this lookup; 341 /// important for [class.protected]. Most lookups do not have an 342 /// associated base object. getBaseObjectType()343 QualType getBaseObjectType() const { 344 return BaseObjectType; 345 } 346 347 /// \brief Sets the base object type for this lookup. setBaseObjectType(QualType T)348 void setBaseObjectType(QualType T) { 349 BaseObjectType = T; 350 } 351 352 /// \brief Add a declaration to these results with its natural access. 353 /// Does not test the acceptance criteria. addDecl(NamedDecl * D)354 void addDecl(NamedDecl *D) { 355 addDecl(D, D->getAccess()); 356 } 357 358 /// \brief Add a declaration to these results with the given access. 359 /// Does not test the acceptance criteria. addDecl(NamedDecl * D,AccessSpecifier AS)360 void addDecl(NamedDecl *D, AccessSpecifier AS) { 361 Decls.addDecl(D, AS); 362 ResultKind = Found; 363 } 364 365 /// \brief Add all the declarations from another set of lookup 366 /// results. addAllDecls(const LookupResult & Other)367 void addAllDecls(const LookupResult &Other) { 368 Decls.append(Other.Decls.begin(), Other.Decls.end()); 369 ResultKind = Found; 370 } 371 372 /// \brief Determine whether no result was found because we could not 373 /// search into dependent base classes of the current instantiation. wasNotFoundInCurrentInstantiation()374 bool wasNotFoundInCurrentInstantiation() const { 375 return ResultKind == NotFoundInCurrentInstantiation; 376 } 377 378 /// \brief Note that while no result was found in the current instantiation, 379 /// there were dependent base classes that could not be searched. setNotFoundInCurrentInstantiation()380 void setNotFoundInCurrentInstantiation() { 381 assert(ResultKind == NotFound && Decls.empty()); 382 ResultKind = NotFoundInCurrentInstantiation; 383 } 384 385 /// \brief Resolves the result kind of the lookup, possibly hiding 386 /// decls. 387 /// 388 /// This should be called in any environment where lookup might 389 /// generate multiple lookup results. 390 void resolveKind(); 391 392 /// \brief Re-resolves the result kind of the lookup after a set of 393 /// removals has been performed. resolveKindAfterFilter()394 void resolveKindAfterFilter() { 395 if (Decls.empty()) { 396 if (ResultKind != NotFoundInCurrentInstantiation) 397 ResultKind = NotFound; 398 399 if (Paths) { 400 deletePaths(Paths); 401 Paths = 0; 402 } 403 } else { 404 AmbiguityKind SavedAK = Ambiguity; 405 ResultKind = Found; 406 resolveKind(); 407 408 // If we didn't make the lookup unambiguous, restore the old 409 // ambiguity kind. 410 if (ResultKind == Ambiguous) { 411 Ambiguity = SavedAK; 412 } else if (Paths) { 413 deletePaths(Paths); 414 Paths = 0; 415 } 416 } 417 } 418 419 template <class DeclClass> getAsSingle()420 DeclClass *getAsSingle() const { 421 if (getResultKind() != Found) return 0; 422 return dyn_cast<DeclClass>(getFoundDecl()); 423 } 424 425 /// \brief Fetch the unique decl found by this lookup. Asserts 426 /// that one was found. 427 /// 428 /// This is intended for users who have examined the result kind 429 /// and are certain that there is only one result. getFoundDecl()430 NamedDecl *getFoundDecl() const { 431 assert(getResultKind() == Found 432 && "getFoundDecl called on non-unique result"); 433 return (*begin())->getUnderlyingDecl(); 434 } 435 436 /// Fetches a representative decl. Useful for lazy diagnostics. getRepresentativeDecl()437 NamedDecl *getRepresentativeDecl() const { 438 assert(!Decls.empty() && "cannot get representative of empty set"); 439 return *begin(); 440 } 441 442 /// \brief Asks if the result is a single tag decl. isSingleTagDecl()443 bool isSingleTagDecl() const { 444 return getResultKind() == Found && isa<TagDecl>(getFoundDecl()); 445 } 446 447 /// \brief Make these results show that the name was found in 448 /// base classes of different types. 449 /// 450 /// The given paths object is copied and invalidated. 451 void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P); 452 453 /// \brief Make these results show that the name was found in 454 /// distinct base classes of the same type. 455 /// 456 /// The given paths object is copied and invalidated. 457 void setAmbiguousBaseSubobjects(CXXBasePaths &P); 458 459 /// \brief Make these results show that the name was found in 460 /// different contexts and a tag decl was hidden by an ordinary 461 /// decl in a different context. setAmbiguousQualifiedTagHiding()462 void setAmbiguousQualifiedTagHiding() { 463 setAmbiguous(AmbiguousTagHiding); 464 } 465 466 /// \brief Clears out any current state. clear()467 void clear() { 468 ResultKind = NotFound; 469 Decls.clear(); 470 if (Paths) deletePaths(Paths); 471 Paths = NULL; 472 NamingClass = 0; 473 } 474 475 /// \brief Clears out any current state and re-initializes for a 476 /// different kind of lookup. clear(Sema::LookupNameKind Kind)477 void clear(Sema::LookupNameKind Kind) { 478 clear(); 479 LookupKind = Kind; 480 configure(); 481 } 482 483 /// \brief Change this lookup's redeclaration kind. setRedeclarationKind(Sema::RedeclarationKind RK)484 void setRedeclarationKind(Sema::RedeclarationKind RK) { 485 Redecl = RK; 486 configure(); 487 } 488 489 void print(raw_ostream &); 490 491 /// Suppress the diagnostics that would normally fire because of this 492 /// lookup. This happens during (e.g.) redeclaration lookups. suppressDiagnostics()493 void suppressDiagnostics() { 494 Diagnose = false; 495 } 496 497 /// Determines whether this lookup is suppressing diagnostics. isSuppressingDiagnostics()498 bool isSuppressingDiagnostics() const { 499 return !Diagnose; 500 } 501 502 /// Sets a 'context' source range. setContextRange(SourceRange SR)503 void setContextRange(SourceRange SR) { 504 NameContextRange = SR; 505 } 506 507 /// Gets the source range of the context of this name; for C++ 508 /// qualified lookups, this is the source range of the scope 509 /// specifier. getContextRange()510 SourceRange getContextRange() const { 511 return NameContextRange; 512 } 513 514 /// Gets the location of the identifier. This isn't always defined: 515 /// sometimes we're doing lookups on synthesized names. getNameLoc()516 SourceLocation getNameLoc() const { 517 return NameInfo.getLoc(); 518 } 519 520 /// \brief Get the Sema object that this lookup result is searching 521 /// with. getSema()522 Sema &getSema() const { return SemaRef; } 523 524 /// A class for iterating through a result set and possibly 525 /// filtering out results. The results returned are possibly 526 /// sugared. 527 class Filter { 528 LookupResult &Results; 529 LookupResult::iterator I; 530 bool Changed; 531 bool CalledDone; 532 533 friend class LookupResult; Filter(LookupResult & Results)534 Filter(LookupResult &Results) 535 : Results(Results), I(Results.begin()), Changed(false), CalledDone(false) 536 {} 537 538 public: ~Filter()539 ~Filter() { 540 assert(CalledDone && 541 "LookupResult::Filter destroyed without done() call"); 542 } 543 hasNext()544 bool hasNext() const { 545 return I != Results.end(); 546 } 547 next()548 NamedDecl *next() { 549 assert(I != Results.end() && "next() called on empty filter"); 550 return *I++; 551 } 552 553 /// Restart the iteration. restart()554 void restart() { 555 I = Results.begin(); 556 } 557 558 /// Erase the last element returned from this iterator. erase()559 void erase() { 560 Results.Decls.erase(--I); 561 Changed = true; 562 } 563 564 /// Replaces the current entry with the given one, preserving the 565 /// access bits. replace(NamedDecl * D)566 void replace(NamedDecl *D) { 567 Results.Decls.replace(I-1, D); 568 Changed = true; 569 } 570 571 /// Replaces the current entry with the given one. replace(NamedDecl * D,AccessSpecifier AS)572 void replace(NamedDecl *D, AccessSpecifier AS) { 573 Results.Decls.replace(I-1, D, AS); 574 Changed = true; 575 } 576 done()577 void done() { 578 assert(!CalledDone && "done() called twice"); 579 CalledDone = true; 580 581 if (Changed) 582 Results.resolveKindAfterFilter(); 583 } 584 }; 585 586 /// Create a filter for this result set. makeFilter()587 Filter makeFilter() { 588 return Filter(*this); 589 } 590 591 private: diagnose()592 void diagnose() { 593 if (isAmbiguous()) 594 SemaRef.DiagnoseAmbiguousLookup(*this); 595 else if (isClassLookup() && SemaRef.getLangOpts().AccessControl) 596 SemaRef.CheckLookupAccess(*this); 597 } 598 setAmbiguous(AmbiguityKind AK)599 void setAmbiguous(AmbiguityKind AK) { 600 ResultKind = Ambiguous; 601 Ambiguity = AK; 602 } 603 604 void addDeclsFromBasePaths(const CXXBasePaths &P); 605 void configure(); 606 607 // Sanity checks. 608 void sanityImpl() const; 609 sanity()610 void sanity() const { 611 #ifndef NDEBUG 612 sanityImpl(); 613 #endif 614 } 615 sanityCheckUnresolved()616 bool sanityCheckUnresolved() const { 617 for (iterator I = begin(), E = end(); I != E; ++I) 618 if (isa<UnresolvedUsingValueDecl>(*I)) 619 return true; 620 return false; 621 } 622 623 static void deletePaths(CXXBasePaths *); 624 625 // Results. 626 LookupResultKind ResultKind; 627 AmbiguityKind Ambiguity; // ill-defined unless ambiguous 628 UnresolvedSet<8> Decls; 629 CXXBasePaths *Paths; 630 CXXRecordDecl *NamingClass; 631 QualType BaseObjectType; 632 633 // Parameters. 634 Sema &SemaRef; 635 DeclarationNameInfo NameInfo; 636 SourceRange NameContextRange; 637 Sema::LookupNameKind LookupKind; 638 unsigned IDNS; // set by configure() 639 640 bool Redecl; 641 642 /// \brief True if tag declarations should be hidden if non-tags 643 /// are present 644 bool HideTags; 645 646 bool Diagnose; 647 }; 648 649 /// \brief Consumes visible declarations found when searching for 650 /// all visible names within a given scope or context. 651 /// 652 /// This abstract class is meant to be subclassed by clients of \c 653 /// Sema::LookupVisibleDecls(), each of which should override the \c 654 /// FoundDecl() function to process declarations as they are found. 655 class VisibleDeclConsumer { 656 public: 657 /// \brief Destroys the visible declaration consumer. 658 virtual ~VisibleDeclConsumer(); 659 660 /// \brief Invoked each time \p Sema::LookupVisibleDecls() finds a 661 /// declaration visible from the current scope or context. 662 /// 663 /// \param ND the declaration found. 664 /// 665 /// \param Hiding a declaration that hides the declaration \p ND, 666 /// or NULL if no such declaration exists. 667 /// 668 /// \param Ctx the original context from which the lookup started. 669 /// 670 /// \param InBaseClass whether this declaration was found in base 671 /// class of the context we searched. 672 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, 673 bool InBaseClass) = 0; 674 }; 675 676 /// \brief A class for storing results from argument-dependent lookup. 677 class ADLResult { 678 private: 679 /// A map from canonical decls to the 'most recent' decl. 680 llvm::DenseMap<NamedDecl*, NamedDecl*> Decls; 681 682 public: 683 /// Adds a new ADL candidate to this map. 684 void insert(NamedDecl *D); 685 686 /// Removes any data associated with a given decl. erase(NamedDecl * D)687 void erase(NamedDecl *D) { 688 Decls.erase(cast<NamedDecl>(D->getCanonicalDecl())); 689 } 690 691 class iterator { 692 typedef llvm::DenseMap<NamedDecl*,NamedDecl*>::iterator inner_iterator; 693 inner_iterator iter; 694 695 friend class ADLResult; iterator(const inner_iterator & iter)696 iterator(const inner_iterator &iter) : iter(iter) {} 697 public: iterator()698 iterator() {} 699 700 iterator &operator++() { ++iter; return *this; } 701 iterator operator++(int) { return iterator(iter++); } 702 703 NamedDecl *operator*() const { return iter->second; } 704 705 bool operator==(const iterator &other) const { return iter == other.iter; } 706 bool operator!=(const iterator &other) const { return iter != other.iter; } 707 }; 708 begin()709 iterator begin() { return iterator(Decls.begin()); } end()710 iterator end() { return iterator(Decls.end()); } 711 }; 712 713 } 714 715 #endif 716