Lookup.h revision 2ccd89cff3f1c18b48f649240302446a7dae28b9
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 21namespace 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. 30class LookupResult { 31public: 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) 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) 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. 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 182 ~LookupResult() { 183 if (Diagnose) diagnose(); 184 if (Paths) deletePaths(Paths); 185 } 186 187 /// Gets the name info to look up. 188 const DeclarationNameInfo &getLookupNameInfo() const { 189 return NameInfo; 190 } 191 192 /// \brief Sets the name info to look up. 193 void setLookupNameInfo(const DeclarationNameInfo &NameInfo) { 194 this->NameInfo = NameInfo; 195 } 196 197 /// Gets the name to look up. 198 DeclarationName getLookupName() const { 199 return NameInfo.getName(); 200 } 201 202 /// \brief Sets the name to look up. 203 void setLookupName(DeclarationName Name) { 204 NameInfo.setName(Name); 205 } 206 207 /// Gets the kind of lookup to perform. 208 Sema::LookupNameKind getLookupKind() const { 209 return LookupKind; 210 } 211 212 /// True if this lookup is just looking for an existing declaration. 213 bool isForRedeclaration() const { 214 return Redecl; 215 } 216 217 /// Sets whether tag declarations should be hidden by non-tag 218 /// declarations during resolution. The default is true. 219 void setHideTags(bool Hide) { 220 HideTags = Hide; 221 } 222 223 bool isAmbiguous() const { 224 return getResultKind() == Ambiguous; 225 } 226 227 /// Determines if this names a single result which is not an 228 /// unresolved value using decl. If so, it is safe to call 229 /// getFoundDecl(). 230 bool isSingleResult() const { 231 return getResultKind() == Found; 232 } 233 234 /// Determines if the results are overloaded. 235 bool isOverloadedResult() const { 236 return getResultKind() == FoundOverloaded; 237 } 238 239 bool isUnresolvableResult() const { 240 return getResultKind() == FoundUnresolvedValue; 241 } 242 243 LookupResultKind getResultKind() const { 244 sanity(); 245 return ResultKind; 246 } 247 248 AmbiguityKind getAmbiguityKind() const { 249 assert(isAmbiguous()); 250 return Ambiguity; 251 } 252 253 const UnresolvedSetImpl &asUnresolvedSet() const { 254 return Decls; 255 } 256 257 iterator begin() const { return iterator(Decls.begin()); } 258 iterator end() const { return iterator(Decls.end()); } 259 260 /// \brief Return true if no decls were found 261 bool empty() const { return Decls.empty(); } 262 263 /// \brief Return the base paths structure that's associated with 264 /// these results, or null if none is. 265 CXXBasePaths *getBasePaths() const { 266 return Paths; 267 } 268 269 /// \brief Determine whether the given declaration is visible to the 270 /// program. 271 static bool isVisible(NamedDecl *D) { 272 // So long as this declaration is not module-private or was parsed as 273 // part of this translation unit (i.e., in the module), it's visible. 274 if (!D->isModulePrivate() || !D->isFromASTFile()) 275 return true; 276 277 // FIXME: We should be allowed to refer to a module-private name from 278 // within the same module, e.g., during template instantiation. 279 // This requires us know which module a particular declaration came from. 280 return false; 281 } 282 283 /// \brief Retrieve the accepted (re)declaration of the given declaration, 284 /// if there is one. 285 NamedDecl *getAcceptableDecl(NamedDecl *D) const { 286 if (!D->isInIdentifierNamespace(IDNS)) 287 return 0; 288 289 if (Redecl == Sema::ForRedeclaration || isVisible(D)) 290 return D; 291 292 return getAcceptableDeclSlow(D); 293 } 294 295private: 296 NamedDecl *getAcceptableDeclSlow(NamedDecl *D) const; 297public: 298 299 /// \brief Returns the identifier namespace mask for this lookup. 300 unsigned getIdentifierNamespace() const { 301 return IDNS; 302 } 303 304 /// \brief Returns whether these results arose from performing a 305 /// lookup into a class. 306 bool isClassLookup() const { 307 return NamingClass != 0; 308 } 309 310 /// \brief Returns the 'naming class' for this lookup, i.e. the 311 /// class which was looked into to find these results. 312 /// 313 /// C++0x [class.access.base]p5: 314 /// The access to a member is affected by the class in which the 315 /// member is named. This naming class is the class in which the 316 /// member name was looked up and found. [Note: this class can be 317 /// explicit, e.g., when a qualified-id is used, or implicit, 318 /// e.g., when a class member access operator (5.2.5) is used 319 /// (including cases where an implicit "this->" is added). If both 320 /// a class member access operator and a qualified-id are used to 321 /// name the member (as in p->T::m), the class naming the member 322 /// is the class named by the nested-name-specifier of the 323 /// qualified-id (that is, T). -- end note ] 324 /// 325 /// This is set by the lookup routines when they find results in a class. 326 CXXRecordDecl *getNamingClass() const { 327 return NamingClass; 328 } 329 330 /// \brief Sets the 'naming class' for this lookup. 331 void setNamingClass(CXXRecordDecl *Record) { 332 NamingClass = Record; 333 } 334 335 /// \brief Returns the base object type associated with this lookup; 336 /// important for [class.protected]. Most lookups do not have an 337 /// associated base object. 338 QualType getBaseObjectType() const { 339 return BaseObjectType; 340 } 341 342 /// \brief Sets the base object type for this lookup. 343 void setBaseObjectType(QualType T) { 344 BaseObjectType = T; 345 } 346 347 /// \brief Add a declaration to these results with its natural access. 348 /// Does not test the acceptance criteria. 349 void addDecl(NamedDecl *D) { 350 addDecl(D, D->getAccess()); 351 } 352 353 /// \brief Add a declaration to these results with the given access. 354 /// Does not test the acceptance criteria. 355 void addDecl(NamedDecl *D, AccessSpecifier AS) { 356 Decls.addDecl(D, AS); 357 ResultKind = Found; 358 } 359 360 /// \brief Add all the declarations from another set of lookup 361 /// results. 362 void addAllDecls(const LookupResult &Other) { 363 Decls.append(Other.Decls.begin(), Other.Decls.end()); 364 ResultKind = Found; 365 } 366 367 /// \brief Determine whether no result was found because we could not 368 /// search into dependent base classes of the current instantiation. 369 bool wasNotFoundInCurrentInstantiation() const { 370 return ResultKind == NotFoundInCurrentInstantiation; 371 } 372 373 /// \brief Note that while no result was found in the current instantiation, 374 /// there were dependent base classes that could not be searched. 375 void setNotFoundInCurrentInstantiation() { 376 assert(ResultKind == NotFound && Decls.empty()); 377 ResultKind = NotFoundInCurrentInstantiation; 378 } 379 380 /// \brief Resolves the result kind of the lookup, possibly hiding 381 /// decls. 382 /// 383 /// This should be called in any environment where lookup might 384 /// generate multiple lookup results. 385 void resolveKind(); 386 387 /// \brief Re-resolves the result kind of the lookup after a set of 388 /// removals has been performed. 389 void resolveKindAfterFilter() { 390 if (Decls.empty()) { 391 if (ResultKind != NotFoundInCurrentInstantiation) 392 ResultKind = NotFound; 393 394 if (Paths) { 395 deletePaths(Paths); 396 Paths = 0; 397 } 398 } else { 399 AmbiguityKind SavedAK = Ambiguity; 400 ResultKind = Found; 401 resolveKind(); 402 403 // If we didn't make the lookup unambiguous, restore the old 404 // ambiguity kind. 405 if (ResultKind == Ambiguous) { 406 Ambiguity = SavedAK; 407 } else if (Paths) { 408 deletePaths(Paths); 409 Paths = 0; 410 } 411 } 412 } 413 414 template <class DeclClass> 415 DeclClass *getAsSingle() const { 416 if (getResultKind() != Found) return 0; 417 return dyn_cast<DeclClass>(getFoundDecl()); 418 } 419 420 /// \brief Fetch the unique decl found by this lookup. Asserts 421 /// that one was found. 422 /// 423 /// This is intended for users who have examined the result kind 424 /// and are certain that there is only one result. 425 NamedDecl *getFoundDecl() const { 426 assert(getResultKind() == Found 427 && "getFoundDecl called on non-unique result"); 428 return (*begin())->getUnderlyingDecl(); 429 } 430 431 /// Fetches a representative decl. Useful for lazy diagnostics. 432 NamedDecl *getRepresentativeDecl() const { 433 assert(!Decls.empty() && "cannot get representative of empty set"); 434 return *begin(); 435 } 436 437 /// \brief Asks if the result is a single tag decl. 438 bool isSingleTagDecl() const { 439 return getResultKind() == Found && isa<TagDecl>(getFoundDecl()); 440 } 441 442 /// \brief Make these results show that the name was found in 443 /// base classes of different types. 444 /// 445 /// The given paths object is copied and invalidated. 446 void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P); 447 448 /// \brief Make these results show that the name was found in 449 /// distinct base classes of the same type. 450 /// 451 /// The given paths object is copied and invalidated. 452 void setAmbiguousBaseSubobjects(CXXBasePaths &P); 453 454 /// \brief Make these results show that the name was found in 455 /// different contexts and a tag decl was hidden by an ordinary 456 /// decl in a different context. 457 void setAmbiguousQualifiedTagHiding() { 458 setAmbiguous(AmbiguousTagHiding); 459 } 460 461 /// \brief Clears out any current state. 462 void clear() { 463 ResultKind = NotFound; 464 Decls.clear(); 465 if (Paths) deletePaths(Paths); 466 Paths = NULL; 467 NamingClass = 0; 468 } 469 470 /// \brief Clears out any current state and re-initializes for a 471 /// different kind of lookup. 472 void clear(Sema::LookupNameKind Kind) { 473 clear(); 474 LookupKind = Kind; 475 configure(); 476 } 477 478 /// \brief Change this lookup's redeclaration kind. 479 void setRedeclarationKind(Sema::RedeclarationKind RK) { 480 Redecl = RK; 481 configure(); 482 } 483 484 void print(raw_ostream &); 485 486 /// Suppress the diagnostics that would normally fire because of this 487 /// lookup. This happens during (e.g.) redeclaration lookups. 488 void suppressDiagnostics() { 489 Diagnose = false; 490 } 491 492 /// Determines whether this lookup is suppressing diagnostics. 493 bool isSuppressingDiagnostics() const { 494 return !Diagnose; 495 } 496 497 /// Sets a 'context' source range. 498 void setContextRange(SourceRange SR) { 499 NameContextRange = SR; 500 } 501 502 /// Gets the source range of the context of this name; for C++ 503 /// qualified lookups, this is the source range of the scope 504 /// specifier. 505 SourceRange getContextRange() const { 506 return NameContextRange; 507 } 508 509 /// Gets the location of the identifier. This isn't always defined: 510 /// sometimes we're doing lookups on synthesized names. 511 SourceLocation getNameLoc() const { 512 return NameInfo.getLoc(); 513 } 514 515 /// \brief Get the Sema object that this lookup result is searching 516 /// with. 517 Sema &getSema() const { return SemaRef; } 518 519 /// A class for iterating through a result set and possibly 520 /// filtering out results. The results returned are possibly 521 /// sugared. 522 class Filter { 523 LookupResult &Results; 524 LookupResult::iterator I; 525 bool Changed; 526 bool CalledDone; 527 528 friend class LookupResult; 529 Filter(LookupResult &Results) 530 : Results(Results), I(Results.begin()), Changed(false), CalledDone(false) 531 {} 532 533 public: 534 ~Filter() { 535 assert(CalledDone && 536 "LookupResult::Filter destroyed without done() call"); 537 } 538 539 bool hasNext() const { 540 return I != Results.end(); 541 } 542 543 NamedDecl *next() { 544 assert(I != Results.end() && "next() called on empty filter"); 545 return *I++; 546 } 547 548 /// Erase the last element returned from this iterator. 549 void erase() { 550 Results.Decls.erase(--I); 551 Changed = true; 552 } 553 554 /// Replaces the current entry with the given one, preserving the 555 /// access bits. 556 void replace(NamedDecl *D) { 557 Results.Decls.replace(I-1, D); 558 Changed = true; 559 } 560 561 /// Replaces the current entry with the given one. 562 void replace(NamedDecl *D, AccessSpecifier AS) { 563 Results.Decls.replace(I-1, D, AS); 564 Changed = true; 565 } 566 567 void done() { 568 assert(!CalledDone && "done() called twice"); 569 CalledDone = true; 570 571 if (Changed) 572 Results.resolveKindAfterFilter(); 573 } 574 }; 575 576 /// Create a filter for this result set. 577 Filter makeFilter() { 578 return Filter(*this); 579 } 580 581private: 582 void diagnose() { 583 if (isAmbiguous()) 584 SemaRef.DiagnoseAmbiguousLookup(*this); 585 else if (isClassLookup() && SemaRef.getLangOptions().AccessControl) 586 SemaRef.CheckLookupAccess(*this); 587 } 588 589 void setAmbiguous(AmbiguityKind AK) { 590 ResultKind = Ambiguous; 591 Ambiguity = AK; 592 } 593 594 void addDeclsFromBasePaths(const CXXBasePaths &P); 595 void configure(); 596 597 // Sanity checks. 598 void sanity() const; 599 600 bool sanityCheckUnresolved() const { 601 for (iterator I = begin(), E = end(); I != E; ++I) 602 if (isa<UnresolvedUsingValueDecl>(*I)) 603 return true; 604 return false; 605 } 606 607 static void deletePaths(CXXBasePaths *); 608 609 // Results. 610 LookupResultKind ResultKind; 611 AmbiguityKind Ambiguity; // ill-defined unless ambiguous 612 UnresolvedSet<8> Decls; 613 CXXBasePaths *Paths; 614 CXXRecordDecl *NamingClass; 615 QualType BaseObjectType; 616 617 // Parameters. 618 Sema &SemaRef; 619 DeclarationNameInfo NameInfo; 620 SourceRange NameContextRange; 621 Sema::LookupNameKind LookupKind; 622 unsigned IDNS; // set by configure() 623 624 bool Redecl; 625 626 /// \brief True if tag declarations should be hidden if non-tags 627 /// are present 628 bool HideTags; 629 630 bool Diagnose; 631}; 632 633 /// \brief Consumes visible declarations found when searching for 634 /// all visible names within a given scope or context. 635 /// 636 /// This abstract class is meant to be subclassed by clients of \c 637 /// Sema::LookupVisibleDecls(), each of which should override the \c 638 /// FoundDecl() function to process declarations as they are found. 639 class VisibleDeclConsumer { 640 public: 641 /// \brief Destroys the visible declaration consumer. 642 virtual ~VisibleDeclConsumer(); 643 644 /// \brief Invoked each time \p Sema::LookupVisibleDecls() finds a 645 /// declaration visible from the current scope or context. 646 /// 647 /// \param ND the declaration found. 648 /// 649 /// \param Hiding a declaration that hides the declaration \p ND, 650 /// or NULL if no such declaration exists. 651 /// 652 /// \param Ctx the original context from which the lookup started. 653 /// 654 /// \param InBaseClass whether this declaration was found in base 655 /// class of the context we searched. 656 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, 657 bool InBaseClass) = 0; 658 }; 659 660/// \brief A class for storing results from argument-dependent lookup. 661class ADLResult { 662private: 663 /// A map from canonical decls to the 'most recent' decl. 664 llvm::DenseMap<NamedDecl*, NamedDecl*> Decls; 665 666public: 667 /// Adds a new ADL candidate to this map. 668 void insert(NamedDecl *D); 669 670 /// Removes any data associated with a given decl. 671 void erase(NamedDecl *D) { 672 Decls.erase(cast<NamedDecl>(D->getCanonicalDecl())); 673 } 674 675 class iterator { 676 typedef llvm::DenseMap<NamedDecl*,NamedDecl*>::iterator inner_iterator; 677 inner_iterator iter; 678 679 friend class ADLResult; 680 iterator(const inner_iterator &iter) : iter(iter) {} 681 public: 682 iterator() {} 683 684 iterator &operator++() { ++iter; return *this; } 685 iterator operator++(int) { return iterator(iter++); } 686 687 NamedDecl *operator*() const { return iter->second; } 688 689 bool operator==(const iterator &other) const { return iter == other.iter; } 690 bool operator!=(const iterator &other) const { return iter != other.iter; } 691 }; 692 693 iterator begin() { return iterator(Decls.begin()); } 694 iterator end() { return iterator(Decls.end()); } 695}; 696 697} 698 699#endif 700