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