1 //===--- Lookup.h - Classes for name lookup ---------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the LookupResult class, which is integral to
11 // Sema's name-lookup subsystem.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SEMA_LOOKUP_H
16 #define LLVM_CLANG_SEMA_LOOKUP_H
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/Sema/Sema.h"
23 /// @brief Represents the results of name lookup.
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.
32 enum LookupResultKind {
33 /// @brief No entity found met the criteria.
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,
41 /// @brief Name lookup found a single declaration that met the
42 /// criteria. getFoundDecl() will return this declaration.
45 /// @brief Name lookup found a set of overloaded functions that
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.
54 /// @brief Name lookup results in an ambiguity; use
55 /// getAmbiguityKind to figure out what kind of ambiguity
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:
65 /// struct A { void f(int); }
66 /// struct B { void f(double); }
67 /// struct C : A, B { };
69 /// c.f(0); // error: A::f and B::f come from subobjects of different
70 /// // types. overload resolution is not performed.
73 AmbiguousBaseSubobjectTypes,
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:
79 /// struct A { int x; };
82 /// struct D : B, C { };
84 /// return d.x; // error: 'x' is found in two A subobjects (of B and C)
87 AmbiguousBaseSubobjects,
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.
95 /// namespace B { int i; }
97 /// using namespace B;
98 /// return i; // error 'i' is found in namespace A and A::B
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.
108 /// namespace A { struct Foo {}; }
109 /// namespace B { void Foo(); }
111 /// using namespace A;
112 /// using namespace B;
115 /// C::Foo(); // error: tag 'A::Foo' is hidden by an object in a
116 /// // different namespace
122 /// A little identifier for flagging temporary lookup results.
123 enum TemporaryToken {
127 typedef UnresolvedSetImpl::iterator iterator;
129 LookupResult(Sema &SemaRef, const DeclarationNameInfo &NameInfo,
130 Sema::LookupNameKind LookupKind,
131 Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
132 : ResultKind(NotFound),
134 NamingClass(nullptr),
137 LookupKind(LookupKind),
139 Redecl(Redecl != Sema::NotForRedeclaration),
141 Diagnose(Redecl == Sema::NotForRedeclaration),
148 // TODO: consider whether this constructor should be restricted to take
149 // as input a const IdentifierInfo* (instead of Name),
150 // forcing other cases towards the constructor taking a DNInfo.
151 LookupResult(Sema &SemaRef, DeclarationName Name,
152 SourceLocation NameLoc, Sema::LookupNameKind LookupKind,
153 Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
154 : ResultKind(NotFound),
156 NamingClass(nullptr),
158 NameInfo(Name, NameLoc),
159 LookupKind(LookupKind),
161 Redecl(Redecl != Sema::NotForRedeclaration),
163 Diagnose(Redecl == Sema::NotForRedeclaration),
170 /// Creates a temporary lookup result, initializing its core data
171 /// using the information from another result. Diagnostics are always
173 LookupResult(TemporaryToken _, const LookupResult &Other)
174 : ResultKind(NotFound),
176 NamingClass(nullptr),
177 SemaPtr(Other.SemaPtr),
178 NameInfo(Other.NameInfo),
179 LookupKind(Other.LookupKind),
181 Redecl(Other.Redecl),
182 HideTags(Other.HideTags),
184 AllowHidden(Other.AllowHidden),
188 // FIXME: Remove these deleted methods once the default build includes
190 LookupResult(const LookupResult &) = delete;
191 LookupResult &operator=(const LookupResult &) = delete;
193 LookupResult(LookupResult &&Other)
194 : ResultKind(std::move(Other.ResultKind)),
195 Ambiguity(std::move(Other.Ambiguity)), Decls(std::move(Other.Decls)),
196 Paths(std::move(Other.Paths)),
197 NamingClass(std::move(Other.NamingClass)),
198 BaseObjectType(std::move(Other.BaseObjectType)),
199 SemaPtr(std::move(Other.SemaPtr)), NameInfo(std::move(Other.NameInfo)),
200 NameContextRange(std::move(Other.NameContextRange)),
201 LookupKind(std::move(Other.LookupKind)), IDNS(std::move(Other.IDNS)),
202 Redecl(std::move(Other.Redecl)), HideTags(std::move(Other.HideTags)),
203 Diagnose(std::move(Other.Diagnose)),
204 AllowHidden(std::move(Other.AllowHidden)),
205 Shadowed(std::move(Other.Shadowed)) {
206 Other.Paths = nullptr;
207 Other.Diagnose = false;
209 LookupResult &operator=(LookupResult &&Other) {
210 ResultKind = std::move(Other.ResultKind);
211 Ambiguity = std::move(Other.Ambiguity);
212 Decls = std::move(Other.Decls);
213 Paths = std::move(Other.Paths);
214 NamingClass = std::move(Other.NamingClass);
215 BaseObjectType = std::move(Other.BaseObjectType);
216 SemaPtr = std::move(Other.SemaPtr);
217 NameInfo = std::move(Other.NameInfo);
218 NameContextRange = std::move(Other.NameContextRange);
219 LookupKind = std::move(Other.LookupKind);
220 IDNS = std::move(Other.IDNS);
221 Redecl = std::move(Other.Redecl);
222 HideTags = std::move(Other.HideTags);
223 Diagnose = std::move(Other.Diagnose);
224 AllowHidden = std::move(Other.AllowHidden);
225 Shadowed = std::move(Other.Shadowed);
226 Other.Paths = nullptr;
227 Other.Diagnose = false;
232 if (Diagnose) diagnose();
233 if (Paths) deletePaths(Paths);
236 /// Gets the name info to look up.
237 const DeclarationNameInfo &getLookupNameInfo() const {
241 /// \brief Sets the name info to look up.
242 void setLookupNameInfo(const DeclarationNameInfo &NameInfo) {
243 this->NameInfo = NameInfo;
246 /// Gets the name to look up.
247 DeclarationName getLookupName() const {
248 return NameInfo.getName();
251 /// \brief Sets the name to look up.
252 void setLookupName(DeclarationName Name) {
253 NameInfo.setName(Name);
256 /// Gets the kind of lookup to perform.
257 Sema::LookupNameKind getLookupKind() const {
261 /// True if this lookup is just looking for an existing declaration.
262 bool isForRedeclaration() const {
266 /// \brief Specify whether hidden declarations are visible, e.g.,
267 /// for recovery reasons.
268 void setAllowHidden(bool AH) {
272 /// \brief Determine whether this lookup is permitted to see hidden
273 /// declarations, such as those in modules that have not yet been imported.
274 bool isHiddenDeclarationVisible(NamedDecl *ND) const {
275 return AllowHidden ||
276 (isForRedeclaration() && ND->isExternallyVisible());
279 /// Sets whether tag declarations should be hidden by non-tag
280 /// declarations during resolution. The default is true.
281 void setHideTags(bool Hide) {
285 bool isAmbiguous() const {
286 return getResultKind() == Ambiguous;
289 /// Determines if this names a single result which is not an
290 /// unresolved value using decl. If so, it is safe to call
292 bool isSingleResult() const {
293 return getResultKind() == Found;
296 /// Determines if the results are overloaded.
297 bool isOverloadedResult() const {
298 return getResultKind() == FoundOverloaded;
301 bool isUnresolvableResult() const {
302 return getResultKind() == FoundUnresolvedValue;
305 LookupResultKind getResultKind() const {
310 AmbiguityKind getAmbiguityKind() const {
311 assert(isAmbiguous());
315 const UnresolvedSetImpl &asUnresolvedSet() const {
319 iterator begin() const { return iterator(Decls.begin()); }
320 iterator end() const { return iterator(Decls.end()); }
322 /// \brief Return true if no decls were found
323 bool empty() const { return Decls.empty(); }
325 /// \brief Return the base paths structure that's associated with
326 /// these results, or null if none is.
327 CXXBasePaths *getBasePaths() const {
331 /// \brief Determine whether the given declaration is visible to the
333 static bool isVisible(Sema &SemaRef, NamedDecl *D) {
334 // If this declaration is not hidden, it's visible.
338 // During template instantiation, we can refer to hidden declarations, if
339 // they were visible in any module along the path of instantiation.
340 return isVisibleSlow(SemaRef, D);
343 /// \brief Retrieve the accepted (re)declaration of the given declaration,
345 NamedDecl *getAcceptableDecl(NamedDecl *D) const {
346 if (!D->isInIdentifierNamespace(IDNS))
349 if (isVisible(getSema(), D) || isHiddenDeclarationVisible(D))
352 return getAcceptableDeclSlow(D);
356 static bool isVisibleSlow(Sema &SemaRef, NamedDecl *D);
357 NamedDecl *getAcceptableDeclSlow(NamedDecl *D) const;
360 /// \brief Returns the identifier namespace mask for this lookup.
361 unsigned getIdentifierNamespace() const {
365 /// \brief Returns whether these results arose from performing a
366 /// lookup into a class.
367 bool isClassLookup() const {
368 return NamingClass != nullptr;
371 /// \brief Returns the 'naming class' for this lookup, i.e. the
372 /// class which was looked into to find these results.
374 /// C++0x [class.access.base]p5:
375 /// The access to a member is affected by the class in which the
376 /// member is named. This naming class is the class in which the
377 /// member name was looked up and found. [Note: this class can be
378 /// explicit, e.g., when a qualified-id is used, or implicit,
379 /// e.g., when a class member access operator (5.2.5) is used
380 /// (including cases where an implicit "this->" is added). If both
381 /// a class member access operator and a qualified-id are used to
382 /// name the member (as in p->T::m), the class naming the member
383 /// is the class named by the nested-name-specifier of the
384 /// qualified-id (that is, T). -- end note ]
386 /// This is set by the lookup routines when they find results in a class.
387 CXXRecordDecl *getNamingClass() const {
391 /// \brief Sets the 'naming class' for this lookup.
392 void setNamingClass(CXXRecordDecl *Record) {
393 NamingClass = Record;
396 /// \brief Returns the base object type associated with this lookup;
397 /// important for [class.protected]. Most lookups do not have an
398 /// associated base object.
399 QualType getBaseObjectType() const {
400 return BaseObjectType;
403 /// \brief Sets the base object type for this lookup.
404 void setBaseObjectType(QualType T) {
408 /// \brief Add a declaration to these results with its natural access.
409 /// Does not test the acceptance criteria.
410 void addDecl(NamedDecl *D) {
411 addDecl(D, D->getAccess());
414 /// \brief Add a declaration to these results with the given access.
415 /// Does not test the acceptance criteria.
416 void addDecl(NamedDecl *D, AccessSpecifier AS) {
417 Decls.addDecl(D, AS);
421 /// \brief Add all the declarations from another set of lookup
423 void addAllDecls(const LookupResult &Other) {
424 Decls.append(Other.Decls.begin(), Other.Decls.end());
428 /// \brief Determine whether no result was found because we could not
429 /// search into dependent base classes of the current instantiation.
430 bool wasNotFoundInCurrentInstantiation() const {
431 return ResultKind == NotFoundInCurrentInstantiation;
434 /// \brief Note that while no result was found in the current instantiation,
435 /// there were dependent base classes that could not be searched.
436 void setNotFoundInCurrentInstantiation() {
437 assert(ResultKind == NotFound && Decls.empty());
438 ResultKind = NotFoundInCurrentInstantiation;
441 /// \brief Determine whether the lookup result was shadowed by some other
442 /// declaration that lookup ignored.
443 bool isShadowed() const { return Shadowed; }
445 /// \brief Note that we found and ignored a declaration while performing
447 void setShadowed() { Shadowed = true; }
449 /// \brief Resolves the result kind of the lookup, possibly hiding
452 /// This should be called in any environment where lookup might
453 /// generate multiple lookup results.
456 /// \brief Re-resolves the result kind of the lookup after a set of
457 /// removals has been performed.
458 void resolveKindAfterFilter() {
460 if (ResultKind != NotFoundInCurrentInstantiation)
461 ResultKind = NotFound;
468 AmbiguityKind SavedAK;
469 bool WasAmbiguous = false;
470 if (ResultKind == Ambiguous) {
477 // If we didn't make the lookup unambiguous, restore the old
479 if (ResultKind == Ambiguous) {
481 assert(WasAmbiguous);
490 template <class DeclClass>
491 DeclClass *getAsSingle() const {
492 if (getResultKind() != Found) return nullptr;
493 return dyn_cast<DeclClass>(getFoundDecl());
496 /// \brief Fetch the unique decl found by this lookup. Asserts
497 /// that one was found.
499 /// This is intended for users who have examined the result kind
500 /// and are certain that there is only one result.
501 NamedDecl *getFoundDecl() const {
502 assert(getResultKind() == Found
503 && "getFoundDecl called on non-unique result");
504 return (*begin())->getUnderlyingDecl();
507 /// Fetches a representative decl. Useful for lazy diagnostics.
508 NamedDecl *getRepresentativeDecl() const {
509 assert(!Decls.empty() && "cannot get representative of empty set");
513 /// \brief Asks if the result is a single tag decl.
514 bool isSingleTagDecl() const {
515 return getResultKind() == Found && isa<TagDecl>(getFoundDecl());
518 /// \brief Make these results show that the name was found in
519 /// base classes of different types.
521 /// The given paths object is copied and invalidated.
522 void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P);
524 /// \brief Make these results show that the name was found in
525 /// distinct base classes of the same type.
527 /// The given paths object is copied and invalidated.
528 void setAmbiguousBaseSubobjects(CXXBasePaths &P);
530 /// \brief Make these results show that the name was found in
531 /// different contexts and a tag decl was hidden by an ordinary
532 /// decl in a different context.
533 void setAmbiguousQualifiedTagHiding() {
534 setAmbiguous(AmbiguousTagHiding);
537 /// \brief Clears out any current state.
539 ResultKind = NotFound;
541 if (Paths) deletePaths(Paths);
543 NamingClass = nullptr;
547 /// \brief Clears out any current state and re-initializes for a
548 /// different kind of lookup.
549 void clear(Sema::LookupNameKind Kind) {
555 /// \brief Change this lookup's redeclaration kind.
556 void setRedeclarationKind(Sema::RedeclarationKind RK) {
562 void print(raw_ostream &);
564 /// Suppress the diagnostics that would normally fire because of this
565 /// lookup. This happens during (e.g.) redeclaration lookups.
566 void suppressDiagnostics() {
570 /// Determines whether this lookup is suppressing diagnostics.
571 bool isSuppressingDiagnostics() const {
575 /// Sets a 'context' source range.
576 void setContextRange(SourceRange SR) {
577 NameContextRange = SR;
580 /// Gets the source range of the context of this name; for C++
581 /// qualified lookups, this is the source range of the scope
583 SourceRange getContextRange() const {
584 return NameContextRange;
587 /// Gets the location of the identifier. This isn't always defined:
588 /// sometimes we're doing lookups on synthesized names.
589 SourceLocation getNameLoc() const {
590 return NameInfo.getLoc();
593 /// \brief Get the Sema object that this lookup result is searching
595 Sema &getSema() const { return *SemaPtr; }
597 /// A class for iterating through a result set and possibly
598 /// filtering out results. The results returned are possibly
601 LookupResult &Results;
602 LookupResult::iterator I;
606 friend class LookupResult;
607 Filter(LookupResult &Results)
608 : Results(Results), I(Results.begin()), Changed(false), CalledDone(false)
613 : Results(F.Results), I(F.I), Changed(F.Changed),
614 CalledDone(F.CalledDone) {
619 "LookupResult::Filter destroyed without done() call");
622 bool hasNext() const {
623 return I != Results.end();
627 assert(I != Results.end() && "next() called on empty filter");
631 /// Restart the iteration.
636 /// Erase the last element returned from this iterator.
638 Results.Decls.erase(--I);
642 /// Replaces the current entry with the given one, preserving the
644 void replace(NamedDecl *D) {
645 Results.Decls.replace(I-1, D);
649 /// Replaces the current entry with the given one.
650 void replace(NamedDecl *D, AccessSpecifier AS) {
651 Results.Decls.replace(I-1, D, AS);
656 assert(!CalledDone && "done() called twice");
660 Results.resolveKindAfterFilter();
664 /// Create a filter for this result set.
665 Filter makeFilter() {
666 return Filter(*this);
669 void setFindLocalExtern(bool FindLocalExtern) {
671 IDNS |= Decl::IDNS_LocalExtern;
673 IDNS &= ~Decl::IDNS_LocalExtern;
679 getSema().DiagnoseAmbiguousLookup(*this);
680 else if (isClassLookup() && getSema().getLangOpts().AccessControl)
681 getSema().CheckLookupAccess(*this);
684 void setAmbiguous(AmbiguityKind AK) {
685 ResultKind = Ambiguous;
689 void addDeclsFromBasePaths(const CXXBasePaths &P);
695 bool sanityCheckUnresolved() const {
696 for (iterator I = begin(), E = end(); I != E; ++I)
697 if (isa<UnresolvedUsingValueDecl>((*I)->getUnderlyingDecl()))
702 static void deletePaths(CXXBasePaths *);
705 LookupResultKind ResultKind;
706 AmbiguityKind Ambiguity; // ill-defined unless ambiguous
707 UnresolvedSet<8> Decls;
709 CXXRecordDecl *NamingClass;
710 QualType BaseObjectType;
714 DeclarationNameInfo NameInfo;
715 SourceRange NameContextRange;
716 Sema::LookupNameKind LookupKind;
717 unsigned IDNS; // set by configure()
721 /// \brief True if tag declarations should be hidden if non-tags
727 /// \brief True if we should allow hidden declarations to be 'visible'.
730 /// \brief True if the found declarations were shadowed by some other
731 /// declaration that we skipped. This only happens when \c LookupKind
732 /// is \c LookupRedeclarationWithLinkage.
736 /// \brief Consumes visible declarations found when searching for
737 /// all visible names within a given scope or context.
739 /// This abstract class is meant to be subclassed by clients of \c
740 /// Sema::LookupVisibleDecls(), each of which should override the \c
741 /// FoundDecl() function to process declarations as they are found.
742 class VisibleDeclConsumer {
744 /// \brief Destroys the visible declaration consumer.
745 virtual ~VisibleDeclConsumer();
747 /// \brief Determine whether hidden declarations (from unimported
748 /// modules) should be given to this consumer. By default, they
749 /// are not included.
750 virtual bool includeHiddenDecls() const;
752 /// \brief Invoked each time \p Sema::LookupVisibleDecls() finds a
753 /// declaration visible from the current scope or context.
755 /// \param ND the declaration found.
757 /// \param Hiding a declaration that hides the declaration \p ND,
758 /// or NULL if no such declaration exists.
760 /// \param Ctx the original context from which the lookup started.
762 /// \param InBaseClass whether this declaration was found in base
763 /// class of the context we searched.
764 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
765 bool InBaseClass) = 0;
768 /// \brief A class for storing results from argument-dependent lookup.
771 /// A map from canonical decls to the 'most recent' decl.
772 llvm::MapVector<NamedDecl*, NamedDecl*> Decls;
774 struct select_second {
775 NamedDecl *operator()(std::pair<NamedDecl*, NamedDecl*> P) const {
781 /// Adds a new ADL candidate to this map.
782 void insert(NamedDecl *D);
784 /// Removes any data associated with a given decl.
785 void erase(NamedDecl *D) {
786 Decls.erase(cast<NamedDecl>(D->getCanonicalDecl()));
789 typedef llvm::mapped_iterator<decltype(Decls)::iterator, select_second>
792 iterator begin() { return iterator(Decls.begin(), select_second()); }
793 iterator end() { return iterator(Decls.end(), select_second()); }