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"
21 #include "llvm/ADT/Optional.h"
25 /// @brief Represents the results of name lookup.
27 /// An instance of the LookupResult class captures the results of a
28 /// single name lookup, which can return no result (nothing found),
29 /// a single declaration, a set of overloaded functions, or an
30 /// ambiguity. Use the getKind() method to determine which of these
31 /// results occurred for a given lookup.
34 enum LookupResultKind {
35 /// @brief No entity found met the criteria.
38 /// @brief No entity found met the criteria within the current
39 /// instantiation,, but there were dependent base classes of the
40 /// current instantiation that could not be searched.
41 NotFoundInCurrentInstantiation,
43 /// @brief Name lookup found a single declaration that met the
44 /// criteria. getFoundDecl() will return this declaration.
47 /// @brief Name lookup found a set of overloaded functions that
51 /// @brief Name lookup found an unresolvable value declaration
52 /// and cannot yet complete. This only happens in C++ dependent
53 /// contexts with dependent using declarations.
56 /// @brief Name lookup results in an ambiguity; use
57 /// getAmbiguityKind to figure out what kind of ambiguity
63 /// Name lookup results in an ambiguity because multiple
64 /// entities that meet the lookup criteria were found in
65 /// subobjects of different types. For example:
67 /// struct A { void f(int); }
68 /// struct B { void f(double); }
69 /// struct C : A, B { };
71 /// c.f(0); // error: A::f and B::f come from subobjects of different
72 /// // types. overload resolution is not performed.
75 AmbiguousBaseSubobjectTypes,
77 /// Name lookup results in an ambiguity because multiple
78 /// nonstatic entities that meet the lookup criteria were found
79 /// in different subobjects of the same type. For example:
81 /// struct A { int x; };
84 /// struct D : B, C { };
86 /// return d.x; // error: 'x' is found in two A subobjects (of B and C)
89 AmbiguousBaseSubobjects,
91 /// Name lookup results in an ambiguity because multiple definitions
92 /// of entity that meet the lookup criteria were found in different
93 /// declaration contexts.
97 /// namespace B { int i; }
99 /// using namespace B;
100 /// return i; // error 'i' is found in namespace A and A::B
106 /// Name lookup results in an ambiguity because an entity with a
107 /// tag name was hidden by an entity with an ordinary name from
108 /// a different context.
110 /// namespace A { struct Foo {}; }
111 /// namespace B { void Foo(); }
113 /// using namespace A;
114 /// using namespace B;
117 /// C::Foo(); // error: tag 'A::Foo' is hidden by an object in a
118 /// // different namespace
124 /// A little identifier for flagging temporary lookup results.
125 enum TemporaryToken {
129 typedef UnresolvedSetImpl::iterator iterator;
131 LookupResult(Sema &SemaRef, const DeclarationNameInfo &NameInfo,
132 Sema::LookupNameKind LookupKind,
133 Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
134 : ResultKind(NotFound),
136 NamingClass(nullptr),
139 LookupKind(LookupKind),
141 Redecl(Redecl != Sema::NotForRedeclaration),
143 Diagnose(Redecl == Sema::NotForRedeclaration),
150 // TODO: consider whether this constructor should be restricted to take
151 // as input a const IdentifierInfo* (instead of Name),
152 // forcing other cases towards the constructor taking a DNInfo.
153 LookupResult(Sema &SemaRef, DeclarationName Name,
154 SourceLocation NameLoc, Sema::LookupNameKind LookupKind,
155 Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
156 : ResultKind(NotFound),
158 NamingClass(nullptr),
160 NameInfo(Name, NameLoc),
161 LookupKind(LookupKind),
163 Redecl(Redecl != Sema::NotForRedeclaration),
165 Diagnose(Redecl == Sema::NotForRedeclaration),
172 /// Creates a temporary lookup result, initializing its core data
173 /// using the information from another result. Diagnostics are always
175 LookupResult(TemporaryToken _, const LookupResult &Other)
176 : ResultKind(NotFound),
178 NamingClass(nullptr),
179 SemaPtr(Other.SemaPtr),
180 NameInfo(Other.NameInfo),
181 LookupKind(Other.LookupKind),
183 Redecl(Other.Redecl),
184 HideTags(Other.HideTags),
186 AllowHidden(Other.AllowHidden),
190 // FIXME: Remove these deleted methods once the default build includes
192 LookupResult(const LookupResult &) = delete;
193 LookupResult &operator=(const LookupResult &) = delete;
195 LookupResult(LookupResult &&Other)
196 : ResultKind(std::move(Other.ResultKind)),
197 Ambiguity(std::move(Other.Ambiguity)), Decls(std::move(Other.Decls)),
198 Paths(std::move(Other.Paths)),
199 NamingClass(std::move(Other.NamingClass)),
200 BaseObjectType(std::move(Other.BaseObjectType)),
201 SemaPtr(std::move(Other.SemaPtr)), NameInfo(std::move(Other.NameInfo)),
202 NameContextRange(std::move(Other.NameContextRange)),
203 LookupKind(std::move(Other.LookupKind)), IDNS(std::move(Other.IDNS)),
204 Redecl(std::move(Other.Redecl)), HideTags(std::move(Other.HideTags)),
205 Diagnose(std::move(Other.Diagnose)),
206 AllowHidden(std::move(Other.AllowHidden)),
207 Shadowed(std::move(Other.Shadowed)) {
208 Other.Paths = nullptr;
209 Other.Diagnose = false;
211 LookupResult &operator=(LookupResult &&Other) {
212 ResultKind = std::move(Other.ResultKind);
213 Ambiguity = std::move(Other.Ambiguity);
214 Decls = std::move(Other.Decls);
215 Paths = std::move(Other.Paths);
216 NamingClass = std::move(Other.NamingClass);
217 BaseObjectType = std::move(Other.BaseObjectType);
218 SemaPtr = std::move(Other.SemaPtr);
219 NameInfo = std::move(Other.NameInfo);
220 NameContextRange = std::move(Other.NameContextRange);
221 LookupKind = std::move(Other.LookupKind);
222 IDNS = std::move(Other.IDNS);
223 Redecl = std::move(Other.Redecl);
224 HideTags = std::move(Other.HideTags);
225 Diagnose = std::move(Other.Diagnose);
226 AllowHidden = std::move(Other.AllowHidden);
227 Shadowed = std::move(Other.Shadowed);
228 Other.Paths = nullptr;
229 Other.Diagnose = false;
234 if (Diagnose) diagnose();
235 if (Paths) deletePaths(Paths);
238 /// Gets the name info to look up.
239 const DeclarationNameInfo &getLookupNameInfo() const {
243 /// \brief Sets the name info to look up.
244 void setLookupNameInfo(const DeclarationNameInfo &NameInfo) {
245 this->NameInfo = NameInfo;
248 /// Gets the name to look up.
249 DeclarationName getLookupName() const {
250 return NameInfo.getName();
253 /// \brief Sets the name to look up.
254 void setLookupName(DeclarationName Name) {
255 NameInfo.setName(Name);
258 /// Gets the kind of lookup to perform.
259 Sema::LookupNameKind getLookupKind() const {
263 /// True if this lookup is just looking for an existing declaration.
264 bool isForRedeclaration() const {
268 /// \brief Specify whether hidden declarations are visible, e.g.,
269 /// for recovery reasons.
270 void setAllowHidden(bool AH) {
274 /// \brief Determine whether this lookup is permitted to see hidden
275 /// declarations, such as those in modules that have not yet been imported.
276 bool isHiddenDeclarationVisible(NamedDecl *ND) const {
277 return AllowHidden ||
278 (isForRedeclaration() && ND->hasExternalFormalLinkage());
281 /// Sets whether tag declarations should be hidden by non-tag
282 /// declarations during resolution. The default is true.
283 void setHideTags(bool Hide) {
287 bool isAmbiguous() const {
288 return getResultKind() == Ambiguous;
291 /// Determines if this names a single result which is not an
292 /// unresolved value using decl. If so, it is safe to call
294 bool isSingleResult() const {
295 return getResultKind() == Found;
298 /// Determines if the results are overloaded.
299 bool isOverloadedResult() const {
300 return getResultKind() == FoundOverloaded;
303 bool isUnresolvableResult() const {
304 return getResultKind() == FoundUnresolvedValue;
307 LookupResultKind getResultKind() const {
312 AmbiguityKind getAmbiguityKind() const {
313 assert(isAmbiguous());
317 const UnresolvedSetImpl &asUnresolvedSet() const {
321 iterator begin() const { return iterator(Decls.begin()); }
322 iterator end() const { return iterator(Decls.end()); }
324 /// \brief Return true if no decls were found
325 bool empty() const { return Decls.empty(); }
327 /// \brief Return the base paths structure that's associated with
328 /// these results, or null if none is.
329 CXXBasePaths *getBasePaths() const {
333 /// \brief Determine whether the given declaration is visible to the
335 static bool isVisible(Sema &SemaRef, NamedDecl *D) {
336 // If this declaration is not hidden, it's visible.
340 // During template instantiation, we can refer to hidden declarations, if
341 // they were visible in any module along the path of instantiation.
342 return isVisibleSlow(SemaRef, D);
345 /// \brief Retrieve the accepted (re)declaration of the given declaration,
347 NamedDecl *getAcceptableDecl(NamedDecl *D) const {
348 if (!D->isInIdentifierNamespace(IDNS))
351 if (isVisible(getSema(), D) || isHiddenDeclarationVisible(D))
354 return getAcceptableDeclSlow(D);
358 static bool isVisibleSlow(Sema &SemaRef, NamedDecl *D);
359 NamedDecl *getAcceptableDeclSlow(NamedDecl *D) const;
362 /// \brief Returns the identifier namespace mask for this lookup.
363 unsigned getIdentifierNamespace() const {
367 /// \brief Returns whether these results arose from performing a
368 /// lookup into a class.
369 bool isClassLookup() const {
370 return NamingClass != nullptr;
373 /// \brief Returns the 'naming class' for this lookup, i.e. the
374 /// class which was looked into to find these results.
376 /// C++0x [class.access.base]p5:
377 /// The access to a member is affected by the class in which the
378 /// member is named. This naming class is the class in which the
379 /// member name was looked up and found. [Note: this class can be
380 /// explicit, e.g., when a qualified-id is used, or implicit,
381 /// e.g., when a class member access operator (5.2.5) is used
382 /// (including cases where an implicit "this->" is added). If both
383 /// a class member access operator and a qualified-id are used to
384 /// name the member (as in p->T::m), the class naming the member
385 /// is the class named by the nested-name-specifier of the
386 /// qualified-id (that is, T). -- end note ]
388 /// This is set by the lookup routines when they find results in a class.
389 CXXRecordDecl *getNamingClass() const {
393 /// \brief Sets the 'naming class' for this lookup.
394 void setNamingClass(CXXRecordDecl *Record) {
395 NamingClass = Record;
398 /// \brief Returns the base object type associated with this lookup;
399 /// important for [class.protected]. Most lookups do not have an
400 /// associated base object.
401 QualType getBaseObjectType() const {
402 return BaseObjectType;
405 /// \brief Sets the base object type for this lookup.
406 void setBaseObjectType(QualType T) {
410 /// \brief Add a declaration to these results with its natural access.
411 /// Does not test the acceptance criteria.
412 void addDecl(NamedDecl *D) {
413 addDecl(D, D->getAccess());
416 /// \brief Add a declaration to these results with the given access.
417 /// Does not test the acceptance criteria.
418 void addDecl(NamedDecl *D, AccessSpecifier AS) {
419 Decls.addDecl(D, AS);
423 /// \brief Add all the declarations from another set of lookup
425 void addAllDecls(const LookupResult &Other) {
426 Decls.append(Other.Decls.begin(), Other.Decls.end());
430 /// \brief Determine whether no result was found because we could not
431 /// search into dependent base classes of the current instantiation.
432 bool wasNotFoundInCurrentInstantiation() const {
433 return ResultKind == NotFoundInCurrentInstantiation;
436 /// \brief Note that while no result was found in the current instantiation,
437 /// there were dependent base classes that could not be searched.
438 void setNotFoundInCurrentInstantiation() {
439 assert(ResultKind == NotFound && Decls.empty());
440 ResultKind = NotFoundInCurrentInstantiation;
443 /// \brief Determine whether the lookup result was shadowed by some other
444 /// declaration that lookup ignored.
445 bool isShadowed() const { return Shadowed; }
447 /// \brief Note that we found and ignored a declaration while performing
449 void setShadowed() { Shadowed = true; }
451 /// \brief Resolves the result kind of the lookup, possibly hiding
454 /// This should be called in any environment where lookup might
455 /// generate multiple lookup results.
458 /// \brief Re-resolves the result kind of the lookup after a set of
459 /// removals has been performed.
460 void resolveKindAfterFilter() {
462 if (ResultKind != NotFoundInCurrentInstantiation)
463 ResultKind = NotFound;
470 llvm::Optional<AmbiguityKind> SavedAK;
471 bool WasAmbiguous = false;
472 if (ResultKind == Ambiguous) {
479 // If we didn't make the lookup unambiguous, restore the old
481 if (ResultKind == Ambiguous) {
483 assert(WasAmbiguous);
484 Ambiguity = SavedAK.getValue();
492 template <class DeclClass>
493 DeclClass *getAsSingle() const {
494 if (getResultKind() != Found) return nullptr;
495 return dyn_cast<DeclClass>(getFoundDecl());
498 /// \brief Fetch the unique decl found by this lookup. Asserts
499 /// that one was found.
501 /// This is intended for users who have examined the result kind
502 /// and are certain that there is only one result.
503 NamedDecl *getFoundDecl() const {
504 assert(getResultKind() == Found
505 && "getFoundDecl called on non-unique result");
506 return (*begin())->getUnderlyingDecl();
509 /// Fetches a representative decl. Useful for lazy diagnostics.
510 NamedDecl *getRepresentativeDecl() const {
511 assert(!Decls.empty() && "cannot get representative of empty set");
515 /// \brief Asks if the result is a single tag decl.
516 bool isSingleTagDecl() const {
517 return getResultKind() == Found && isa<TagDecl>(getFoundDecl());
520 /// \brief Make these results show that the name was found in
521 /// base classes of different types.
523 /// The given paths object is copied and invalidated.
524 void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P);
526 /// \brief Make these results show that the name was found in
527 /// distinct base classes of the same type.
529 /// The given paths object is copied and invalidated.
530 void setAmbiguousBaseSubobjects(CXXBasePaths &P);
532 /// \brief Make these results show that the name was found in
533 /// different contexts and a tag decl was hidden by an ordinary
534 /// decl in a different context.
535 void setAmbiguousQualifiedTagHiding() {
536 setAmbiguous(AmbiguousTagHiding);
539 /// \brief Clears out any current state.
541 ResultKind = NotFound;
543 if (Paths) deletePaths(Paths);
545 NamingClass = nullptr;
549 /// \brief Clears out any current state and re-initializes for a
550 /// different kind of lookup.
551 void clear(Sema::LookupNameKind Kind) {
557 /// \brief Change this lookup's redeclaration kind.
558 void setRedeclarationKind(Sema::RedeclarationKind RK) {
564 void print(raw_ostream &);
566 /// Suppress the diagnostics that would normally fire because of this
567 /// lookup. This happens during (e.g.) redeclaration lookups.
568 void suppressDiagnostics() {
572 /// Determines whether this lookup is suppressing diagnostics.
573 bool isSuppressingDiagnostics() const {
577 /// Sets a 'context' source range.
578 void setContextRange(SourceRange SR) {
579 NameContextRange = SR;
582 /// Gets the source range of the context of this name; for C++
583 /// qualified lookups, this is the source range of the scope
585 SourceRange getContextRange() const {
586 return NameContextRange;
589 /// Gets the location of the identifier. This isn't always defined:
590 /// sometimes we're doing lookups on synthesized names.
591 SourceLocation getNameLoc() const {
592 return NameInfo.getLoc();
595 /// \brief Get the Sema object that this lookup result is searching
597 Sema &getSema() const { return *SemaPtr; }
599 /// A class for iterating through a result set and possibly
600 /// filtering out results. The results returned are possibly
603 LookupResult &Results;
604 LookupResult::iterator I;
608 friend class LookupResult;
609 Filter(LookupResult &Results)
610 : Results(Results), I(Results.begin()), Changed(false), CalledDone(false)
615 : Results(F.Results), I(F.I), Changed(F.Changed),
616 CalledDone(F.CalledDone) {
621 "LookupResult::Filter destroyed without done() call");
624 bool hasNext() const {
625 return I != Results.end();
629 assert(I != Results.end() && "next() called on empty filter");
633 /// Restart the iteration.
638 /// Erase the last element returned from this iterator.
640 Results.Decls.erase(--I);
644 /// Replaces the current entry with the given one, preserving the
646 void replace(NamedDecl *D) {
647 Results.Decls.replace(I-1, D);
651 /// Replaces the current entry with the given one.
652 void replace(NamedDecl *D, AccessSpecifier AS) {
653 Results.Decls.replace(I-1, D, AS);
658 assert(!CalledDone && "done() called twice");
662 Results.resolveKindAfterFilter();
666 /// Create a filter for this result set.
667 Filter makeFilter() {
668 return Filter(*this);
671 void setFindLocalExtern(bool FindLocalExtern) {
673 IDNS |= Decl::IDNS_LocalExtern;
675 IDNS &= ~Decl::IDNS_LocalExtern;
681 getSema().DiagnoseAmbiguousLookup(*this);
682 else if (isClassLookup() && getSema().getLangOpts().AccessControl)
683 getSema().CheckLookupAccess(*this);
686 void setAmbiguous(AmbiguityKind AK) {
687 ResultKind = Ambiguous;
691 void addDeclsFromBasePaths(const CXXBasePaths &P);
697 bool sanityCheckUnresolved() const {
698 for (iterator I = begin(), E = end(); I != E; ++I)
699 if (isa<UnresolvedUsingValueDecl>((*I)->getUnderlyingDecl()))
704 static void deletePaths(CXXBasePaths *);
707 LookupResultKind ResultKind;
708 AmbiguityKind Ambiguity; // ill-defined unless ambiguous
709 UnresolvedSet<8> Decls;
711 CXXRecordDecl *NamingClass;
712 QualType BaseObjectType;
716 DeclarationNameInfo NameInfo;
717 SourceRange NameContextRange;
718 Sema::LookupNameKind LookupKind;
719 unsigned IDNS; // set by configure()
723 /// \brief True if tag declarations should be hidden if non-tags
729 /// \brief True if we should allow hidden declarations to be 'visible'.
732 /// \brief True if the found declarations were shadowed by some other
733 /// declaration that we skipped. This only happens when \c LookupKind
734 /// is \c LookupRedeclarationWithLinkage.
738 /// \brief Consumes visible declarations found when searching for
739 /// all visible names within a given scope or context.
741 /// This abstract class is meant to be subclassed by clients of \c
742 /// Sema::LookupVisibleDecls(), each of which should override the \c
743 /// FoundDecl() function to process declarations as they are found.
744 class VisibleDeclConsumer {
746 /// \brief Destroys the visible declaration consumer.
747 virtual ~VisibleDeclConsumer();
749 /// \brief Determine whether hidden declarations (from unimported
750 /// modules) should be given to this consumer. By default, they
751 /// are not included.
752 virtual bool includeHiddenDecls() const;
754 /// \brief Invoked each time \p Sema::LookupVisibleDecls() finds a
755 /// declaration visible from the current scope or context.
757 /// \param ND the declaration found.
759 /// \param Hiding a declaration that hides the declaration \p ND,
760 /// or NULL if no such declaration exists.
762 /// \param Ctx the original context from which the lookup started.
764 /// \param InBaseClass whether this declaration was found in base
765 /// class of the context we searched.
766 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
767 bool InBaseClass) = 0;
770 /// \brief A class for storing results from argument-dependent lookup.
773 /// A map from canonical decls to the 'most recent' decl.
774 llvm::MapVector<NamedDecl*, NamedDecl*> Decls;
776 struct select_second {
777 NamedDecl *operator()(std::pair<NamedDecl*, NamedDecl*> P) const {
783 /// Adds a new ADL candidate to this map.
784 void insert(NamedDecl *D);
786 /// Removes any data associated with a given decl.
787 void erase(NamedDecl *D) {
788 Decls.erase(cast<NamedDecl>(D->getCanonicalDecl()));
791 typedef llvm::mapped_iterator<decltype(Decls)::iterator, select_second>
794 iterator begin() { return iterator(Decls.begin(), select_second()); }
795 iterator end() { return iterator(Decls.end(), select_second()); }