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),
142 ExternalRedecl(Redecl == Sema::ForExternalRedeclaration),
144 Diagnose(Redecl == Sema::NotForRedeclaration),
151 // TODO: consider whether this constructor should be restricted to take
152 // as input a const IdentifierInfo* (instead of Name),
153 // forcing other cases towards the constructor taking a DNInfo.
154 LookupResult(Sema &SemaRef, DeclarationName Name,
155 SourceLocation NameLoc, Sema::LookupNameKind LookupKind,
156 Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
157 : ResultKind(NotFound),
159 NamingClass(nullptr),
161 NameInfo(Name, NameLoc),
162 LookupKind(LookupKind),
164 Redecl(Redecl != Sema::NotForRedeclaration),
165 ExternalRedecl(Redecl == Sema::ForExternalRedeclaration),
167 Diagnose(Redecl == Sema::NotForRedeclaration),
174 /// Creates a temporary lookup result, initializing its core data
175 /// using the information from another result. Diagnostics are always
177 LookupResult(TemporaryToken _, const LookupResult &Other)
178 : ResultKind(NotFound),
180 NamingClass(nullptr),
181 SemaPtr(Other.SemaPtr),
182 NameInfo(Other.NameInfo),
183 LookupKind(Other.LookupKind),
185 Redecl(Other.Redecl),
186 ExternalRedecl(Other.ExternalRedecl),
187 HideTags(Other.HideTags),
189 AllowHidden(Other.AllowHidden),
193 // FIXME: Remove these deleted methods once the default build includes
195 LookupResult(const LookupResult &) = delete;
196 LookupResult &operator=(const LookupResult &) = delete;
198 LookupResult(LookupResult &&Other)
199 : ResultKind(std::move(Other.ResultKind)),
200 Ambiguity(std::move(Other.Ambiguity)), Decls(std::move(Other.Decls)),
201 Paths(std::move(Other.Paths)),
202 NamingClass(std::move(Other.NamingClass)),
203 BaseObjectType(std::move(Other.BaseObjectType)),
204 SemaPtr(std::move(Other.SemaPtr)), NameInfo(std::move(Other.NameInfo)),
205 NameContextRange(std::move(Other.NameContextRange)),
206 LookupKind(std::move(Other.LookupKind)), IDNS(std::move(Other.IDNS)),
207 Redecl(std::move(Other.Redecl)),
208 ExternalRedecl(std::move(Other.ExternalRedecl)),
209 HideTags(std::move(Other.HideTags)),
210 Diagnose(std::move(Other.Diagnose)),
211 AllowHidden(std::move(Other.AllowHidden)),
212 Shadowed(std::move(Other.Shadowed)) {
213 Other.Paths = nullptr;
214 Other.Diagnose = false;
216 LookupResult &operator=(LookupResult &&Other) {
217 ResultKind = std::move(Other.ResultKind);
218 Ambiguity = std::move(Other.Ambiguity);
219 Decls = std::move(Other.Decls);
220 Paths = std::move(Other.Paths);
221 NamingClass = std::move(Other.NamingClass);
222 BaseObjectType = std::move(Other.BaseObjectType);
223 SemaPtr = std::move(Other.SemaPtr);
224 NameInfo = std::move(Other.NameInfo);
225 NameContextRange = std::move(Other.NameContextRange);
226 LookupKind = std::move(Other.LookupKind);
227 IDNS = std::move(Other.IDNS);
228 Redecl = std::move(Other.Redecl);
229 ExternalRedecl = std::move(Other.ExternalRedecl);
230 HideTags = std::move(Other.HideTags);
231 Diagnose = std::move(Other.Diagnose);
232 AllowHidden = std::move(Other.AllowHidden);
233 Shadowed = std::move(Other.Shadowed);
234 Other.Paths = nullptr;
235 Other.Diagnose = false;
240 if (Diagnose) diagnose();
241 if (Paths) deletePaths(Paths);
244 /// Gets the name info to look up.
245 const DeclarationNameInfo &getLookupNameInfo() const {
249 /// \brief Sets the name info to look up.
250 void setLookupNameInfo(const DeclarationNameInfo &NameInfo) {
251 this->NameInfo = NameInfo;
254 /// Gets the name to look up.
255 DeclarationName getLookupName() const {
256 return NameInfo.getName();
259 /// \brief Sets the name to look up.
260 void setLookupName(DeclarationName Name) {
261 NameInfo.setName(Name);
264 /// Gets the kind of lookup to perform.
265 Sema::LookupNameKind getLookupKind() const {
269 /// True if this lookup is just looking for an existing declaration.
270 bool isForRedeclaration() const {
274 /// True if this lookup is just looking for an existing declaration to link
275 /// against a declaration with external linkage.
276 bool isForExternalRedeclaration() const {
277 return ExternalRedecl;
280 Sema::RedeclarationKind redeclarationKind() const {
281 return ExternalRedecl ? Sema::ForExternalRedeclaration :
282 Redecl ? Sema::ForVisibleRedeclaration : Sema::NotForRedeclaration;
285 /// \brief Specify whether hidden declarations are visible, e.g.,
286 /// for recovery reasons.
287 void setAllowHidden(bool AH) {
291 /// \brief Determine whether this lookup is permitted to see hidden
292 /// declarations, such as those in modules that have not yet been imported.
293 bool isHiddenDeclarationVisible(NamedDecl *ND) const {
294 return AllowHidden ||
295 (isForExternalRedeclaration() && ND->isExternallyDeclarable());
298 /// Sets whether tag declarations should be hidden by non-tag
299 /// declarations during resolution. The default is true.
300 void setHideTags(bool Hide) {
304 bool isAmbiguous() const {
305 return getResultKind() == Ambiguous;
308 /// Determines if this names a single result which is not an
309 /// unresolved value using decl. If so, it is safe to call
311 bool isSingleResult() const {
312 return getResultKind() == Found;
315 /// Determines if the results are overloaded.
316 bool isOverloadedResult() const {
317 return getResultKind() == FoundOverloaded;
320 bool isUnresolvableResult() const {
321 return getResultKind() == FoundUnresolvedValue;
324 LookupResultKind getResultKind() const {
329 AmbiguityKind getAmbiguityKind() const {
330 assert(isAmbiguous());
334 const UnresolvedSetImpl &asUnresolvedSet() const {
338 iterator begin() const { return iterator(Decls.begin()); }
339 iterator end() const { return iterator(Decls.end()); }
341 /// \brief Return true if no decls were found
342 bool empty() const { return Decls.empty(); }
344 /// \brief Return the base paths structure that's associated with
345 /// these results, or null if none is.
346 CXXBasePaths *getBasePaths() const {
350 /// \brief Determine whether the given declaration is visible to the
352 static bool isVisible(Sema &SemaRef, NamedDecl *D) {
353 // If this declaration is not hidden, it's visible.
357 // During template instantiation, we can refer to hidden declarations, if
358 // they were visible in any module along the path of instantiation.
359 return isVisibleSlow(SemaRef, D);
362 /// \brief Retrieve the accepted (re)declaration of the given declaration,
364 NamedDecl *getAcceptableDecl(NamedDecl *D) const {
365 if (!D->isInIdentifierNamespace(IDNS))
368 if (isVisible(getSema(), D) || isHiddenDeclarationVisible(D))
371 return getAcceptableDeclSlow(D);
375 static bool isVisibleSlow(Sema &SemaRef, NamedDecl *D);
376 NamedDecl *getAcceptableDeclSlow(NamedDecl *D) const;
379 /// \brief Returns the identifier namespace mask for this lookup.
380 unsigned getIdentifierNamespace() const {
384 /// \brief Returns whether these results arose from performing a
385 /// lookup into a class.
386 bool isClassLookup() const {
387 return NamingClass != nullptr;
390 /// \brief Returns the 'naming class' for this lookup, i.e. the
391 /// class which was looked into to find these results.
393 /// C++0x [class.access.base]p5:
394 /// The access to a member is affected by the class in which the
395 /// member is named. This naming class is the class in which the
396 /// member name was looked up and found. [Note: this class can be
397 /// explicit, e.g., when a qualified-id is used, or implicit,
398 /// e.g., when a class member access operator (5.2.5) is used
399 /// (including cases where an implicit "this->" is added). If both
400 /// a class member access operator and a qualified-id are used to
401 /// name the member (as in p->T::m), the class naming the member
402 /// is the class named by the nested-name-specifier of the
403 /// qualified-id (that is, T). -- end note ]
405 /// This is set by the lookup routines when they find results in a class.
406 CXXRecordDecl *getNamingClass() const {
410 /// \brief Sets the 'naming class' for this lookup.
411 void setNamingClass(CXXRecordDecl *Record) {
412 NamingClass = Record;
415 /// \brief Returns the base object type associated with this lookup;
416 /// important for [class.protected]. Most lookups do not have an
417 /// associated base object.
418 QualType getBaseObjectType() const {
419 return BaseObjectType;
422 /// \brief Sets the base object type for this lookup.
423 void setBaseObjectType(QualType T) {
427 /// \brief Add a declaration to these results with its natural access.
428 /// Does not test the acceptance criteria.
429 void addDecl(NamedDecl *D) {
430 addDecl(D, D->getAccess());
433 /// \brief Add a declaration to these results with the given access.
434 /// Does not test the acceptance criteria.
435 void addDecl(NamedDecl *D, AccessSpecifier AS) {
436 Decls.addDecl(D, AS);
440 /// \brief Add all the declarations from another set of lookup
442 void addAllDecls(const LookupResult &Other) {
443 Decls.append(Other.Decls.begin(), Other.Decls.end());
447 /// \brief Determine whether no result was found because we could not
448 /// search into dependent base classes of the current instantiation.
449 bool wasNotFoundInCurrentInstantiation() const {
450 return ResultKind == NotFoundInCurrentInstantiation;
453 /// \brief Note that while no result was found in the current instantiation,
454 /// there were dependent base classes that could not be searched.
455 void setNotFoundInCurrentInstantiation() {
456 assert(ResultKind == NotFound && Decls.empty());
457 ResultKind = NotFoundInCurrentInstantiation;
460 /// \brief Determine whether the lookup result was shadowed by some other
461 /// declaration that lookup ignored.
462 bool isShadowed() const { return Shadowed; }
464 /// \brief Note that we found and ignored a declaration while performing
466 void setShadowed() { Shadowed = true; }
468 /// \brief Resolves the result kind of the lookup, possibly hiding
471 /// This should be called in any environment where lookup might
472 /// generate multiple lookup results.
475 /// \brief Re-resolves the result kind of the lookup after a set of
476 /// removals has been performed.
477 void resolveKindAfterFilter() {
479 if (ResultKind != NotFoundInCurrentInstantiation)
480 ResultKind = NotFound;
487 llvm::Optional<AmbiguityKind> SavedAK;
488 bool WasAmbiguous = false;
489 if (ResultKind == Ambiguous) {
496 // If we didn't make the lookup unambiguous, restore the old
498 if (ResultKind == Ambiguous) {
500 assert(WasAmbiguous);
501 Ambiguity = SavedAK.getValue();
509 template <class DeclClass>
510 DeclClass *getAsSingle() const {
511 if (getResultKind() != Found) return nullptr;
512 return dyn_cast<DeclClass>(getFoundDecl());
515 /// \brief Fetch the unique decl found by this lookup. Asserts
516 /// that one was found.
518 /// This is intended for users who have examined the result kind
519 /// and are certain that there is only one result.
520 NamedDecl *getFoundDecl() const {
521 assert(getResultKind() == Found
522 && "getFoundDecl called on non-unique result");
523 return (*begin())->getUnderlyingDecl();
526 /// Fetches a representative decl. Useful for lazy diagnostics.
527 NamedDecl *getRepresentativeDecl() const {
528 assert(!Decls.empty() && "cannot get representative of empty set");
532 /// \brief Asks if the result is a single tag decl.
533 bool isSingleTagDecl() const {
534 return getResultKind() == Found && isa<TagDecl>(getFoundDecl());
537 /// \brief Make these results show that the name was found in
538 /// base classes of different types.
540 /// The given paths object is copied and invalidated.
541 void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P);
543 /// \brief Make these results show that the name was found in
544 /// distinct base classes of the same type.
546 /// The given paths object is copied and invalidated.
547 void setAmbiguousBaseSubobjects(CXXBasePaths &P);
549 /// \brief Make these results show that the name was found in
550 /// different contexts and a tag decl was hidden by an ordinary
551 /// decl in a different context.
552 void setAmbiguousQualifiedTagHiding() {
553 setAmbiguous(AmbiguousTagHiding);
556 /// \brief Clears out any current state.
558 ResultKind = NotFound;
560 if (Paths) deletePaths(Paths);
562 NamingClass = nullptr;
566 /// \brief Clears out any current state and re-initializes for a
567 /// different kind of lookup.
568 void clear(Sema::LookupNameKind Kind) {
574 /// \brief Change this lookup's redeclaration kind.
575 void setRedeclarationKind(Sema::RedeclarationKind RK) {
576 Redecl = (RK != Sema::NotForRedeclaration);
577 ExternalRedecl = (RK == Sema::ForExternalRedeclaration);
582 void print(raw_ostream &);
584 /// Suppress the diagnostics that would normally fire because of this
585 /// lookup. This happens during (e.g.) redeclaration lookups.
586 void suppressDiagnostics() {
590 /// Determines whether this lookup is suppressing diagnostics.
591 bool isSuppressingDiagnostics() const {
595 /// Sets a 'context' source range.
596 void setContextRange(SourceRange SR) {
597 NameContextRange = SR;
600 /// Gets the source range of the context of this name; for C++
601 /// qualified lookups, this is the source range of the scope
603 SourceRange getContextRange() const {
604 return NameContextRange;
607 /// Gets the location of the identifier. This isn't always defined:
608 /// sometimes we're doing lookups on synthesized names.
609 SourceLocation getNameLoc() const {
610 return NameInfo.getLoc();
613 /// \brief Get the Sema object that this lookup result is searching
615 Sema &getSema() const { return *SemaPtr; }
617 /// A class for iterating through a result set and possibly
618 /// filtering out results. The results returned are possibly
621 LookupResult &Results;
622 LookupResult::iterator I;
626 friend class LookupResult;
627 Filter(LookupResult &Results)
628 : Results(Results), I(Results.begin()), Changed(false), CalledDone(false)
633 : Results(F.Results), I(F.I), Changed(F.Changed),
634 CalledDone(F.CalledDone) {
639 "LookupResult::Filter destroyed without done() call");
642 bool hasNext() const {
643 return I != Results.end();
647 assert(I != Results.end() && "next() called on empty filter");
651 /// Restart the iteration.
656 /// Erase the last element returned from this iterator.
658 Results.Decls.erase(--I);
662 /// Replaces the current entry with the given one, preserving the
664 void replace(NamedDecl *D) {
665 Results.Decls.replace(I-1, D);
669 /// Replaces the current entry with the given one.
670 void replace(NamedDecl *D, AccessSpecifier AS) {
671 Results.Decls.replace(I-1, D, AS);
676 assert(!CalledDone && "done() called twice");
680 Results.resolveKindAfterFilter();
684 /// Create a filter for this result set.
685 Filter makeFilter() {
686 return Filter(*this);
689 void setFindLocalExtern(bool FindLocalExtern) {
691 IDNS |= Decl::IDNS_LocalExtern;
693 IDNS &= ~Decl::IDNS_LocalExtern;
699 getSema().DiagnoseAmbiguousLookup(*this);
700 else if (isClassLookup() && getSema().getLangOpts().AccessControl)
701 getSema().CheckLookupAccess(*this);
704 void setAmbiguous(AmbiguityKind AK) {
705 ResultKind = Ambiguous;
709 void addDeclsFromBasePaths(const CXXBasePaths &P);
715 bool sanityCheckUnresolved() const {
716 for (iterator I = begin(), E = end(); I != E; ++I)
717 if (isa<UnresolvedUsingValueDecl>((*I)->getUnderlyingDecl()))
722 static void deletePaths(CXXBasePaths *);
725 LookupResultKind ResultKind;
726 AmbiguityKind Ambiguity; // ill-defined unless ambiguous
727 UnresolvedSet<8> Decls;
729 CXXRecordDecl *NamingClass;
730 QualType BaseObjectType;
734 DeclarationNameInfo NameInfo;
735 SourceRange NameContextRange;
736 Sema::LookupNameKind LookupKind;
737 unsigned IDNS; // set by configure()
742 /// \brief True if tag declarations should be hidden if non-tags
748 /// \brief True if we should allow hidden declarations to be 'visible'.
751 /// \brief True if the found declarations were shadowed by some other
752 /// declaration that we skipped. This only happens when \c LookupKind
753 /// is \c LookupRedeclarationWithLinkage.
757 /// \brief Consumes visible declarations found when searching for
758 /// all visible names within a given scope or context.
760 /// This abstract class is meant to be subclassed by clients of \c
761 /// Sema::LookupVisibleDecls(), each of which should override the \c
762 /// FoundDecl() function to process declarations as they are found.
763 class VisibleDeclConsumer {
765 /// \brief Destroys the visible declaration consumer.
766 virtual ~VisibleDeclConsumer();
768 /// \brief Determine whether hidden declarations (from unimported
769 /// modules) should be given to this consumer. By default, they
770 /// are not included.
771 virtual bool includeHiddenDecls() const;
773 /// \brief Invoked each time \p Sema::LookupVisibleDecls() finds a
774 /// declaration visible from the current scope or context.
776 /// \param ND the declaration found.
778 /// \param Hiding a declaration that hides the declaration \p ND,
779 /// or NULL if no such declaration exists.
781 /// \param Ctx the original context from which the lookup started.
783 /// \param InBaseClass whether this declaration was found in base
784 /// class of the context we searched.
785 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
786 bool InBaseClass) = 0;
789 /// \brief A class for storing results from argument-dependent lookup.
792 /// A map from canonical decls to the 'most recent' decl.
793 llvm::MapVector<NamedDecl*, NamedDecl*> Decls;
795 struct select_second {
796 NamedDecl *operator()(std::pair<NamedDecl*, NamedDecl*> P) const {
802 /// Adds a new ADL candidate to this map.
803 void insert(NamedDecl *D);
805 /// Removes any data associated with a given decl.
806 void erase(NamedDecl *D) {
807 Decls.erase(cast<NamedDecl>(D->getCanonicalDecl()));
810 typedef llvm::mapped_iterator<decltype(Decls)::iterator, select_second>
813 iterator begin() { return iterator(Decls.begin(), select_second()); }
814 iterator end() { return iterator(Decls.end(), select_second()); }