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/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclarationName.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/UnresolvedSet.h"
24 #include "clang/Basic/LLVM.h"
25 #include "clang/Basic/LangOptions.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/Specifiers.h"
28 #include "clang/Sema/Sema.h"
29 #include "llvm/ADT/MapVector.h"
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/Casting.h"
40 /// Represents the results of name lookup.
42 /// An instance of the LookupResult class captures the results of a
43 /// single name lookup, which can return no result (nothing found),
44 /// a single declaration, a set of overloaded functions, or an
45 /// ambiguity. Use the getKind() method to determine which of these
46 /// results occurred for a given lookup.
49 enum LookupResultKind {
50 /// No entity found met the criteria.
53 /// No entity found met the criteria within the current
54 /// instantiation,, but there were dependent base classes of the
55 /// current instantiation that could not be searched.
56 NotFoundInCurrentInstantiation,
58 /// Name lookup found a single declaration that met the
59 /// criteria. getFoundDecl() will return this declaration.
62 /// Name lookup found a set of overloaded functions that
66 /// Name lookup found an unresolvable value declaration
67 /// and cannot yet complete. This only happens in C++ dependent
68 /// contexts with dependent using declarations.
71 /// Name lookup results in an ambiguity; use
72 /// getAmbiguityKind to figure out what kind of ambiguity
78 /// Name lookup results in an ambiguity because multiple
79 /// entities that meet the lookup criteria were found in
80 /// subobjects of different types. For example:
82 /// struct A { void f(int); }
83 /// struct B { void f(double); }
84 /// struct C : A, B { };
86 /// c.f(0); // error: A::f and B::f come from subobjects of different
87 /// // types. overload resolution is not performed.
90 AmbiguousBaseSubobjectTypes,
92 /// Name lookup results in an ambiguity because multiple
93 /// nonstatic entities that meet the lookup criteria were found
94 /// in different subobjects of the same type. For example:
96 /// struct A { int x; };
99 /// struct D : B, C { };
101 /// return d.x; // error: 'x' is found in two A subobjects (of B and C)
104 AmbiguousBaseSubobjects,
106 /// Name lookup results in an ambiguity because multiple definitions
107 /// of entity that meet the lookup criteria were found in different
108 /// declaration contexts.
112 /// namespace B { int i; }
114 /// using namespace B;
115 /// return i; // error 'i' is found in namespace A and A::B
121 /// Name lookup results in an ambiguity because an entity with a
122 /// tag name was hidden by an entity with an ordinary name from
123 /// a different context.
125 /// namespace A { struct Foo {}; }
126 /// namespace B { void Foo(); }
128 /// using namespace A;
129 /// using namespace B;
132 /// C::Foo(); // error: tag 'A::Foo' is hidden by an object in a
133 /// // different namespace
139 /// A little identifier for flagging temporary lookup results.
140 enum TemporaryToken {
144 using iterator = UnresolvedSetImpl::iterator;
146 LookupResult(Sema &SemaRef, const DeclarationNameInfo &NameInfo,
147 Sema::LookupNameKind LookupKind,
148 Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
149 : SemaPtr(&SemaRef), NameInfo(NameInfo), LookupKind(LookupKind),
150 Redecl(Redecl != Sema::NotForRedeclaration),
151 ExternalRedecl(Redecl == Sema::ForExternalRedeclaration),
152 Diagnose(Redecl == Sema::NotForRedeclaration) {
156 // TODO: consider whether this constructor should be restricted to take
157 // as input a const IdentifierInfo* (instead of Name),
158 // forcing other cases towards the constructor taking a DNInfo.
159 LookupResult(Sema &SemaRef, DeclarationName Name,
160 SourceLocation NameLoc, Sema::LookupNameKind LookupKind,
161 Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
162 : SemaPtr(&SemaRef), NameInfo(Name, NameLoc), LookupKind(LookupKind),
163 Redecl(Redecl != Sema::NotForRedeclaration),
164 ExternalRedecl(Redecl == Sema::ForExternalRedeclaration),
165 Diagnose(Redecl == Sema::NotForRedeclaration) {
169 /// Creates a temporary lookup result, initializing its core data
170 /// using the information from another result. Diagnostics are always
172 LookupResult(TemporaryToken _, const LookupResult &Other)
173 : SemaPtr(Other.SemaPtr), NameInfo(Other.NameInfo),
174 LookupKind(Other.LookupKind), IDNS(Other.IDNS), Redecl(Other.Redecl),
175 ExternalRedecl(Other.ExternalRedecl), HideTags(Other.HideTags),
176 AllowHidden(Other.AllowHidden) {}
178 // FIXME: Remove these deleted methods once the default build includes
180 LookupResult(const LookupResult &) = delete;
181 LookupResult &operator=(const LookupResult &) = delete;
183 LookupResult(LookupResult &&Other)
184 : ResultKind(std::move(Other.ResultKind)),
185 Ambiguity(std::move(Other.Ambiguity)), Decls(std::move(Other.Decls)),
186 Paths(std::move(Other.Paths)),
187 NamingClass(std::move(Other.NamingClass)),
188 BaseObjectType(std::move(Other.BaseObjectType)),
189 SemaPtr(std::move(Other.SemaPtr)), NameInfo(std::move(Other.NameInfo)),
190 NameContextRange(std::move(Other.NameContextRange)),
191 LookupKind(std::move(Other.LookupKind)), IDNS(std::move(Other.IDNS)),
192 Redecl(std::move(Other.Redecl)),
193 ExternalRedecl(std::move(Other.ExternalRedecl)),
194 HideTags(std::move(Other.HideTags)),
195 Diagnose(std::move(Other.Diagnose)),
196 AllowHidden(std::move(Other.AllowHidden)),
197 Shadowed(std::move(Other.Shadowed)) {
198 Other.Paths = nullptr;
199 Other.Diagnose = false;
202 LookupResult &operator=(LookupResult &&Other) {
203 ResultKind = std::move(Other.ResultKind);
204 Ambiguity = std::move(Other.Ambiguity);
205 Decls = std::move(Other.Decls);
206 Paths = std::move(Other.Paths);
207 NamingClass = std::move(Other.NamingClass);
208 BaseObjectType = std::move(Other.BaseObjectType);
209 SemaPtr = std::move(Other.SemaPtr);
210 NameInfo = std::move(Other.NameInfo);
211 NameContextRange = std::move(Other.NameContextRange);
212 LookupKind = std::move(Other.LookupKind);
213 IDNS = std::move(Other.IDNS);
214 Redecl = std::move(Other.Redecl);
215 ExternalRedecl = std::move(Other.ExternalRedecl);
216 HideTags = std::move(Other.HideTags);
217 Diagnose = std::move(Other.Diagnose);
218 AllowHidden = std::move(Other.AllowHidden);
219 Shadowed = std::move(Other.Shadowed);
220 Other.Paths = nullptr;
221 Other.Diagnose = false;
226 if (Diagnose) diagnose();
227 if (Paths) deletePaths(Paths);
230 /// Gets the name info to look up.
231 const DeclarationNameInfo &getLookupNameInfo() const {
235 /// Sets the name info to look up.
236 void setLookupNameInfo(const DeclarationNameInfo &NameInfo) {
237 this->NameInfo = NameInfo;
240 /// Gets the name to look up.
241 DeclarationName getLookupName() const {
242 return NameInfo.getName();
245 /// Sets the name to look up.
246 void setLookupName(DeclarationName Name) {
247 NameInfo.setName(Name);
250 /// Gets the kind of lookup to perform.
251 Sema::LookupNameKind getLookupKind() const {
255 /// True if this lookup is just looking for an existing declaration.
256 bool isForRedeclaration() const {
260 /// True if this lookup is just looking for an existing declaration to link
261 /// against a declaration with external linkage.
262 bool isForExternalRedeclaration() const {
263 return ExternalRedecl;
266 Sema::RedeclarationKind redeclarationKind() const {
267 return ExternalRedecl ? Sema::ForExternalRedeclaration :
268 Redecl ? Sema::ForVisibleRedeclaration : Sema::NotForRedeclaration;
271 /// Specify whether hidden declarations are visible, e.g.,
272 /// for recovery reasons.
273 void setAllowHidden(bool AH) {
277 /// Determine whether this lookup is permitted to see hidden
278 /// declarations, such as those in modules that have not yet been imported.
279 bool isHiddenDeclarationVisible(NamedDecl *ND) const {
280 return AllowHidden ||
281 (isForExternalRedeclaration() && ND->isExternallyDeclarable());
284 /// Sets whether tag declarations should be hidden by non-tag
285 /// declarations during resolution. The default is true.
286 void setHideTags(bool Hide) {
290 bool isAmbiguous() const {
291 return getResultKind() == Ambiguous;
294 /// Determines if this names a single result which is not an
295 /// unresolved value using decl. If so, it is safe to call
297 bool isSingleResult() const {
298 return getResultKind() == Found;
301 /// Determines if the results are overloaded.
302 bool isOverloadedResult() const {
303 return getResultKind() == FoundOverloaded;
306 bool isUnresolvableResult() const {
307 return getResultKind() == FoundUnresolvedValue;
310 LookupResultKind getResultKind() const {
315 AmbiguityKind getAmbiguityKind() const {
316 assert(isAmbiguous());
320 const UnresolvedSetImpl &asUnresolvedSet() const {
324 iterator begin() const { return iterator(Decls.begin()); }
325 iterator end() const { return iterator(Decls.end()); }
327 /// Return true if no decls were found
328 bool empty() const { return Decls.empty(); }
330 /// Return the base paths structure that's associated with
331 /// these results, or null if none is.
332 CXXBasePaths *getBasePaths() const {
336 /// Determine whether the given declaration is visible to the
338 static bool isVisible(Sema &SemaRef, NamedDecl *D) {
339 // If this declaration is not hidden, it's visible.
343 // During template instantiation, we can refer to hidden declarations, if
344 // they were visible in any module along the path of instantiation.
345 return isVisibleSlow(SemaRef, D);
348 /// Retrieve the accepted (re)declaration of the given declaration,
350 NamedDecl *getAcceptableDecl(NamedDecl *D) const {
351 if (!D->isInIdentifierNamespace(IDNS))
354 if (isVisible(getSema(), D) || isHiddenDeclarationVisible(D))
357 return getAcceptableDeclSlow(D);
361 static bool isVisibleSlow(Sema &SemaRef, NamedDecl *D);
362 NamedDecl *getAcceptableDeclSlow(NamedDecl *D) const;
365 /// Returns the identifier namespace mask for this lookup.
366 unsigned getIdentifierNamespace() const {
370 /// Returns whether these results arose from performing a
371 /// lookup into a class.
372 bool isClassLookup() const {
373 return NamingClass != nullptr;
376 /// Returns the 'naming class' for this lookup, i.e. the
377 /// class which was looked into to find these results.
379 /// C++0x [class.access.base]p5:
380 /// The access to a member is affected by the class in which the
381 /// member is named. This naming class is the class in which the
382 /// member name was looked up and found. [Note: this class can be
383 /// explicit, e.g., when a qualified-id is used, or implicit,
384 /// e.g., when a class member access operator (5.2.5) is used
385 /// (including cases where an implicit "this->" is added). If both
386 /// a class member access operator and a qualified-id are used to
387 /// name the member (as in p->T::m), the class naming the member
388 /// is the class named by the nested-name-specifier of the
389 /// qualified-id (that is, T). -- end note ]
391 /// This is set by the lookup routines when they find results in a class.
392 CXXRecordDecl *getNamingClass() const {
396 /// Sets the 'naming class' for this lookup.
397 void setNamingClass(CXXRecordDecl *Record) {
398 NamingClass = Record;
401 /// Returns the base object type associated with this lookup;
402 /// important for [class.protected]. Most lookups do not have an
403 /// associated base object.
404 QualType getBaseObjectType() const {
405 return BaseObjectType;
408 /// Sets the base object type for this lookup.
409 void setBaseObjectType(QualType T) {
413 /// Add a declaration to these results with its natural access.
414 /// Does not test the acceptance criteria.
415 void addDecl(NamedDecl *D) {
416 addDecl(D, D->getAccess());
419 /// Add a declaration to these results with the given access.
420 /// Does not test the acceptance criteria.
421 void addDecl(NamedDecl *D, AccessSpecifier AS) {
422 Decls.addDecl(D, AS);
426 /// Add all the declarations from another set of lookup
428 void addAllDecls(const LookupResult &Other) {
429 Decls.append(Other.Decls.begin(), Other.Decls.end());
433 /// Determine whether no result was found because we could not
434 /// search into dependent base classes of the current instantiation.
435 bool wasNotFoundInCurrentInstantiation() const {
436 return ResultKind == NotFoundInCurrentInstantiation;
439 /// Note that while no result was found in the current instantiation,
440 /// there were dependent base classes that could not be searched.
441 void setNotFoundInCurrentInstantiation() {
442 assert(ResultKind == NotFound && Decls.empty());
443 ResultKind = NotFoundInCurrentInstantiation;
446 /// Determine whether the lookup result was shadowed by some other
447 /// declaration that lookup ignored.
448 bool isShadowed() const { return Shadowed; }
450 /// Note that we found and ignored a declaration while performing
452 void setShadowed() { Shadowed = true; }
454 /// Resolves the result kind of the lookup, possibly hiding
457 /// This should be called in any environment where lookup might
458 /// generate multiple lookup results.
461 /// Re-resolves the result kind of the lookup after a set of
462 /// removals has been performed.
463 void resolveKindAfterFilter() {
465 if (ResultKind != NotFoundInCurrentInstantiation)
466 ResultKind = NotFound;
473 llvm::Optional<AmbiguityKind> SavedAK;
474 bool WasAmbiguous = false;
475 if (ResultKind == Ambiguous) {
482 // If we didn't make the lookup unambiguous, restore the old
484 if (ResultKind == Ambiguous) {
486 assert(WasAmbiguous);
487 Ambiguity = SavedAK.getValue();
495 template <class DeclClass>
496 DeclClass *getAsSingle() const {
497 if (getResultKind() != Found) return nullptr;
498 return dyn_cast<DeclClass>(getFoundDecl());
501 /// Fetch the unique decl found by this lookup. Asserts
502 /// that one was found.
504 /// This is intended for users who have examined the result kind
505 /// and are certain that there is only one result.
506 NamedDecl *getFoundDecl() const {
507 assert(getResultKind() == Found
508 && "getFoundDecl called on non-unique result");
509 return (*begin())->getUnderlyingDecl();
512 /// Fetches a representative decl. Useful for lazy diagnostics.
513 NamedDecl *getRepresentativeDecl() const {
514 assert(!Decls.empty() && "cannot get representative of empty set");
518 /// Asks if the result is a single tag decl.
519 bool isSingleTagDecl() const {
520 return getResultKind() == Found && isa<TagDecl>(getFoundDecl());
523 /// Make these results show that the name was found in
524 /// base classes of different types.
526 /// The given paths object is copied and invalidated.
527 void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P);
529 /// Make these results show that the name was found in
530 /// distinct base classes of the same type.
532 /// The given paths object is copied and invalidated.
533 void setAmbiguousBaseSubobjects(CXXBasePaths &P);
535 /// Make these results show that the name was found in
536 /// different contexts and a tag decl was hidden by an ordinary
537 /// decl in a different context.
538 void setAmbiguousQualifiedTagHiding() {
539 setAmbiguous(AmbiguousTagHiding);
542 /// Clears out any current state.
544 ResultKind = NotFound;
546 if (Paths) deletePaths(Paths);
548 NamingClass = nullptr;
552 /// Clears out any current state and re-initializes for a
553 /// different kind of lookup.
554 void clear(Sema::LookupNameKind Kind) {
560 /// Change this lookup's redeclaration kind.
561 void setRedeclarationKind(Sema::RedeclarationKind RK) {
562 Redecl = (RK != Sema::NotForRedeclaration);
563 ExternalRedecl = (RK == Sema::ForExternalRedeclaration);
568 void print(raw_ostream &);
570 /// Suppress the diagnostics that would normally fire because of this
571 /// lookup. This happens during (e.g.) redeclaration lookups.
572 void suppressDiagnostics() {
576 /// Determines whether this lookup is suppressing diagnostics.
577 bool isSuppressingDiagnostics() const {
581 /// Sets a 'context' source range.
582 void setContextRange(SourceRange SR) {
583 NameContextRange = SR;
586 /// Gets the source range of the context of this name; for C++
587 /// qualified lookups, this is the source range of the scope
589 SourceRange getContextRange() const {
590 return NameContextRange;
593 /// Gets the location of the identifier. This isn't always defined:
594 /// sometimes we're doing lookups on synthesized names.
595 SourceLocation getNameLoc() const {
596 return NameInfo.getLoc();
599 /// Get the Sema object that this lookup result is searching
601 Sema &getSema() const { return *SemaPtr; }
603 /// A class for iterating through a result set and possibly
604 /// filtering out results. The results returned are possibly
607 friend class LookupResult;
609 LookupResult &Results;
610 LookupResult::iterator I;
611 bool Changed = false;
612 bool CalledDone = false;
614 Filter(LookupResult &Results) : Results(Results), I(Results.begin()) {}
618 : Results(F.Results), I(F.I), Changed(F.Changed),
619 CalledDone(F.CalledDone) {
625 "LookupResult::Filter destroyed without done() call");
628 bool hasNext() const {
629 return I != Results.end();
633 assert(I != Results.end() && "next() called on empty filter");
637 /// Restart the iteration.
642 /// Erase the last element returned from this iterator.
644 Results.Decls.erase(--I);
648 /// Replaces the current entry with the given one, preserving the
650 void replace(NamedDecl *D) {
651 Results.Decls.replace(I-1, D);
655 /// Replaces the current entry with the given one.
656 void replace(NamedDecl *D, AccessSpecifier AS) {
657 Results.Decls.replace(I-1, D, AS);
662 assert(!CalledDone && "done() called twice");
666 Results.resolveKindAfterFilter();
670 /// Create a filter for this result set.
671 Filter makeFilter() {
672 return Filter(*this);
675 void setFindLocalExtern(bool FindLocalExtern) {
677 IDNS |= Decl::IDNS_LocalExtern;
679 IDNS &= ~Decl::IDNS_LocalExtern;
685 getSema().DiagnoseAmbiguousLookup(*this);
686 else if (isClassLookup() && getSema().getLangOpts().AccessControl)
687 getSema().CheckLookupAccess(*this);
690 void setAmbiguous(AmbiguityKind AK) {
691 ResultKind = Ambiguous;
695 void addDeclsFromBasePaths(const CXXBasePaths &P);
701 bool sanityCheckUnresolved() const {
702 for (iterator I = begin(), E = end(); I != E; ++I)
703 if (isa<UnresolvedUsingValueDecl>((*I)->getUnderlyingDecl()))
708 static void deletePaths(CXXBasePaths *);
711 LookupResultKind ResultKind = NotFound;
712 AmbiguityKind Ambiguity; // ill-defined unless ambiguous
713 UnresolvedSet<8> Decls;
714 CXXBasePaths *Paths = nullptr;
715 CXXRecordDecl *NamingClass = nullptr;
716 QualType BaseObjectType;
720 DeclarationNameInfo NameInfo;
721 SourceRange NameContextRange;
722 Sema::LookupNameKind LookupKind;
723 unsigned IDNS = 0; // set by configure()
728 /// True if tag declarations should be hidden if non-tags
730 bool HideTags = true;
732 bool Diagnose = false;
734 /// True if we should allow hidden declarations to be 'visible'.
735 bool AllowHidden = false;
737 /// True if the found declarations were shadowed by some other
738 /// declaration that we skipped. This only happens when \c LookupKind
739 /// is \c LookupRedeclarationWithLinkage.
740 bool Shadowed = false;
743 /// Consumes visible declarations found when searching for
744 /// all visible names within a given scope or context.
746 /// This abstract class is meant to be subclassed by clients of \c
747 /// Sema::LookupVisibleDecls(), each of which should override the \c
748 /// FoundDecl() function to process declarations as they are found.
749 class VisibleDeclConsumer {
751 /// Destroys the visible declaration consumer.
752 virtual ~VisibleDeclConsumer();
754 /// Determine whether hidden declarations (from unimported
755 /// modules) should be given to this consumer. By default, they
756 /// are not included.
757 virtual bool includeHiddenDecls() const;
759 /// Invoked each time \p Sema::LookupVisibleDecls() finds a
760 /// declaration visible from the current scope or context.
762 /// \param ND the declaration found.
764 /// \param Hiding a declaration that hides the declaration \p ND,
765 /// or NULL if no such declaration exists.
767 /// \param Ctx the original context from which the lookup started.
769 /// \param InBaseClass whether this declaration was found in base
770 /// class of the context we searched.
771 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
772 bool InBaseClass) = 0;
774 /// Callback to inform the client that Sema entered into a new context
775 /// to find a visible declaration.
777 /// \param Ctx the context which Sema entered.
778 virtual void EnteredContext(DeclContext *Ctx) {}
781 /// A class for storing results from argument-dependent lookup.
784 /// A map from canonical decls to the 'most recent' decl.
785 llvm::MapVector<NamedDecl*, NamedDecl*> Decls;
787 struct select_second {
788 NamedDecl *operator()(std::pair<NamedDecl*, NamedDecl*> P) const {
794 /// Adds a new ADL candidate to this map.
795 void insert(NamedDecl *D);
797 /// Removes any data associated with a given decl.
798 void erase(NamedDecl *D) {
799 Decls.erase(cast<NamedDecl>(D->getCanonicalDecl()));
803 llvm::mapped_iterator<decltype(Decls)::iterator, select_second>;
805 iterator begin() { return iterator(Decls.begin(), select_second()); }
806 iterator end() { return iterator(Decls.end(), select_second()); }
811 #endif // LLVM_CLANG_SEMA_LOOKUP_H