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),
137 LookupKind(LookupKind),
139 Redecl(Redecl != Sema::NotForRedeclaration),
141 Diagnose(Redecl == Sema::NotForRedeclaration),
142 AllowHidden(Redecl == Sema::ForRedeclaration)
147 // TODO: consider whether this constructor should be restricted to take
148 // as input a const IndentifierInfo* (instead of Name),
149 // forcing other cases towards the constructor taking a DNInfo.
150 LookupResult(Sema &SemaRef, DeclarationName Name,
151 SourceLocation NameLoc, Sema::LookupNameKind LookupKind,
152 Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
153 : ResultKind(NotFound),
157 NameInfo(Name, NameLoc),
158 LookupKind(LookupKind),
160 Redecl(Redecl != Sema::NotForRedeclaration),
162 Diagnose(Redecl == Sema::NotForRedeclaration),
163 AllowHidden(Redecl == Sema::ForRedeclaration)
168 /// Creates a temporary lookup result, initializing its core data
169 /// using the information from another result. Diagnostics are always
171 LookupResult(TemporaryToken _, const LookupResult &Other)
172 : ResultKind(NotFound),
175 SemaRef(Other.SemaRef),
176 NameInfo(Other.NameInfo),
177 LookupKind(Other.LookupKind),
179 Redecl(Other.Redecl),
180 HideTags(Other.HideTags),
182 AllowHidden(Other.AllowHidden)
186 if (Diagnose) diagnose();
187 if (Paths) deletePaths(Paths);
190 /// Gets the name info to look up.
191 const DeclarationNameInfo &getLookupNameInfo() const {
195 /// \brief Sets the name info to look up.
196 void setLookupNameInfo(const DeclarationNameInfo &NameInfo) {
197 this->NameInfo = NameInfo;
200 /// Gets the name to look up.
201 DeclarationName getLookupName() const {
202 return NameInfo.getName();
205 /// \brief Sets the name to look up.
206 void setLookupName(DeclarationName Name) {
207 NameInfo.setName(Name);
210 /// Gets the kind of lookup to perform.
211 Sema::LookupNameKind getLookupKind() const {
215 /// True if this lookup is just looking for an existing declaration.
216 bool isForRedeclaration() const {
220 /// \brief Specify whether hidden declarations are visible, e.g.,
221 /// for recovery reasons.
222 void setAllowHidden(bool AH) {
226 /// \brief Determine whether this lookup is permitted to see hidden
227 /// declarations, such as those in modules that have not yet been imported.
228 bool isHiddenDeclarationVisible() const {
229 return AllowHidden || LookupKind == Sema::LookupTagName;
232 /// Sets whether tag declarations should be hidden by non-tag
233 /// declarations during resolution. The default is true.
234 void setHideTags(bool Hide) {
238 bool isAmbiguous() const {
239 return getResultKind() == Ambiguous;
242 /// Determines if this names a single result which is not an
243 /// unresolved value using decl. If so, it is safe to call
245 bool isSingleResult() const {
246 return getResultKind() == Found;
249 /// Determines if the results are overloaded.
250 bool isOverloadedResult() const {
251 return getResultKind() == FoundOverloaded;
254 bool isUnresolvableResult() const {
255 return getResultKind() == FoundUnresolvedValue;
258 LookupResultKind getResultKind() const {
263 AmbiguityKind getAmbiguityKind() const {
264 assert(isAmbiguous());
268 const UnresolvedSetImpl &asUnresolvedSet() const {
272 iterator begin() const { return iterator(Decls.begin()); }
273 iterator end() const { return iterator(Decls.end()); }
275 /// \brief Return true if no decls were found
276 bool empty() const { return Decls.empty(); }
278 /// \brief Return the base paths structure that's associated with
279 /// these results, or null if none is.
280 CXXBasePaths *getBasePaths() const {
284 /// \brief Determine whether the given declaration is visible to the
286 static bool isVisible(NamedDecl *D) {
287 // If this declaration is not hidden, it's visible.
291 // FIXME: We should be allowed to refer to a module-private name from
292 // within the same module, e.g., during template instantiation.
293 // This requires us know which module a particular declaration came from.
297 /// \brief Retrieve the accepted (re)declaration of the given declaration,
299 NamedDecl *getAcceptableDecl(NamedDecl *D) const {
300 if (!D->isInIdentifierNamespace(IDNS))
303 if (isHiddenDeclarationVisible() || isVisible(D))
306 return getAcceptableDeclSlow(D);
310 NamedDecl *getAcceptableDeclSlow(NamedDecl *D) const;
313 /// \brief Returns the identifier namespace mask for this lookup.
314 unsigned getIdentifierNamespace() const {
318 /// \brief Returns whether these results arose from performing a
319 /// lookup into a class.
320 bool isClassLookup() const {
321 return NamingClass != 0;
324 /// \brief Returns the 'naming class' for this lookup, i.e. the
325 /// class which was looked into to find these results.
327 /// C++0x [class.access.base]p5:
328 /// The access to a member is affected by the class in which the
329 /// member is named. This naming class is the class in which the
330 /// member name was looked up and found. [Note: this class can be
331 /// explicit, e.g., when a qualified-id is used, or implicit,
332 /// e.g., when a class member access operator (5.2.5) is used
333 /// (including cases where an implicit "this->" is added). If both
334 /// a class member access operator and a qualified-id are used to
335 /// name the member (as in p->T::m), the class naming the member
336 /// is the class named by the nested-name-specifier of the
337 /// qualified-id (that is, T). -- end note ]
339 /// This is set by the lookup routines when they find results in a class.
340 CXXRecordDecl *getNamingClass() const {
344 /// \brief Sets the 'naming class' for this lookup.
345 void setNamingClass(CXXRecordDecl *Record) {
346 NamingClass = Record;
349 /// \brief Returns the base object type associated with this lookup;
350 /// important for [class.protected]. Most lookups do not have an
351 /// associated base object.
352 QualType getBaseObjectType() const {
353 return BaseObjectType;
356 /// \brief Sets the base object type for this lookup.
357 void setBaseObjectType(QualType T) {
361 /// \brief Add a declaration to these results with its natural access.
362 /// Does not test the acceptance criteria.
363 void addDecl(NamedDecl *D) {
364 addDecl(D, D->getAccess());
367 /// \brief Add a declaration to these results with the given access.
368 /// Does not test the acceptance criteria.
369 void addDecl(NamedDecl *D, AccessSpecifier AS) {
370 Decls.addDecl(D, AS);
374 /// \brief Add all the declarations from another set of lookup
376 void addAllDecls(const LookupResult &Other) {
377 Decls.append(Other.Decls.begin(), Other.Decls.end());
381 /// \brief Determine whether no result was found because we could not
382 /// search into dependent base classes of the current instantiation.
383 bool wasNotFoundInCurrentInstantiation() const {
384 return ResultKind == NotFoundInCurrentInstantiation;
387 /// \brief Note that while no result was found in the current instantiation,
388 /// there were dependent base classes that could not be searched.
389 void setNotFoundInCurrentInstantiation() {
390 assert(ResultKind == NotFound && Decls.empty());
391 ResultKind = NotFoundInCurrentInstantiation;
394 /// \brief Resolves the result kind of the lookup, possibly hiding
397 /// This should be called in any environment where lookup might
398 /// generate multiple lookup results.
401 /// \brief Re-resolves the result kind of the lookup after a set of
402 /// removals has been performed.
403 void resolveKindAfterFilter() {
405 if (ResultKind != NotFoundInCurrentInstantiation)
406 ResultKind = NotFound;
413 AmbiguityKind SavedAK = Ambiguity;
417 // If we didn't make the lookup unambiguous, restore the old
419 if (ResultKind == Ambiguous) {
428 template <class DeclClass>
429 DeclClass *getAsSingle() const {
430 if (getResultKind() != Found) return 0;
431 return dyn_cast<DeclClass>(getFoundDecl());
434 /// \brief Fetch the unique decl found by this lookup. Asserts
435 /// that one was found.
437 /// This is intended for users who have examined the result kind
438 /// and are certain that there is only one result.
439 NamedDecl *getFoundDecl() const {
440 assert(getResultKind() == Found
441 && "getFoundDecl called on non-unique result");
442 return (*begin())->getUnderlyingDecl();
445 /// Fetches a representative decl. Useful for lazy diagnostics.
446 NamedDecl *getRepresentativeDecl() const {
447 assert(!Decls.empty() && "cannot get representative of empty set");
451 /// \brief Asks if the result is a single tag decl.
452 bool isSingleTagDecl() const {
453 return getResultKind() == Found && isa<TagDecl>(getFoundDecl());
456 /// \brief Make these results show that the name was found in
457 /// base classes of different types.
459 /// The given paths object is copied and invalidated.
460 void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P);
462 /// \brief Make these results show that the name was found in
463 /// distinct base classes of the same type.
465 /// The given paths object is copied and invalidated.
466 void setAmbiguousBaseSubobjects(CXXBasePaths &P);
468 /// \brief Make these results show that the name was found in
469 /// different contexts and a tag decl was hidden by an ordinary
470 /// decl in a different context.
471 void setAmbiguousQualifiedTagHiding() {
472 setAmbiguous(AmbiguousTagHiding);
475 /// \brief Clears out any current state.
477 ResultKind = NotFound;
479 if (Paths) deletePaths(Paths);
484 /// \brief Clears out any current state and re-initializes for a
485 /// different kind of lookup.
486 void clear(Sema::LookupNameKind Kind) {
492 /// \brief Change this lookup's redeclaration kind.
493 void setRedeclarationKind(Sema::RedeclarationKind RK) {
495 AllowHidden = (RK == Sema::ForRedeclaration);
499 void print(raw_ostream &);
501 /// Suppress the diagnostics that would normally fire because of this
502 /// lookup. This happens during (e.g.) redeclaration lookups.
503 void suppressDiagnostics() {
507 /// Determines whether this lookup is suppressing diagnostics.
508 bool isSuppressingDiagnostics() const {
512 /// Sets a 'context' source range.
513 void setContextRange(SourceRange SR) {
514 NameContextRange = SR;
517 /// Gets the source range of the context of this name; for C++
518 /// qualified lookups, this is the source range of the scope
520 SourceRange getContextRange() const {
521 return NameContextRange;
524 /// Gets the location of the identifier. This isn't always defined:
525 /// sometimes we're doing lookups on synthesized names.
526 SourceLocation getNameLoc() const {
527 return NameInfo.getLoc();
530 /// \brief Get the Sema object that this lookup result is searching
532 Sema &getSema() const { return SemaRef; }
534 /// A class for iterating through a result set and possibly
535 /// filtering out results. The results returned are possibly
538 LookupResult &Results;
539 LookupResult::iterator I;
543 friend class LookupResult;
544 Filter(LookupResult &Results)
545 : Results(Results), I(Results.begin()), Changed(false), CalledDone(false)
551 "LookupResult::Filter destroyed without done() call");
554 bool hasNext() const {
555 return I != Results.end();
559 assert(I != Results.end() && "next() called on empty filter");
563 /// Restart the iteration.
568 /// Erase the last element returned from this iterator.
570 Results.Decls.erase(--I);
574 /// Replaces the current entry with the given one, preserving the
576 void replace(NamedDecl *D) {
577 Results.Decls.replace(I-1, D);
581 /// Replaces the current entry with the given one.
582 void replace(NamedDecl *D, AccessSpecifier AS) {
583 Results.Decls.replace(I-1, D, AS);
588 assert(!CalledDone && "done() called twice");
592 Results.resolveKindAfterFilter();
596 /// Create a filter for this result set.
597 Filter makeFilter() {
598 return Filter(*this);
604 SemaRef.DiagnoseAmbiguousLookup(*this);
605 else if (isClassLookup() && SemaRef.getLangOpts().AccessControl)
606 SemaRef.CheckLookupAccess(*this);
609 void setAmbiguous(AmbiguityKind AK) {
610 ResultKind = Ambiguous;
614 void addDeclsFromBasePaths(const CXXBasePaths &P);
618 void sanityImpl() const;
620 void sanity() const {
626 bool sanityCheckUnresolved() const {
627 for (iterator I = begin(), E = end(); I != E; ++I)
628 if (isa<UnresolvedUsingValueDecl>((*I)->getUnderlyingDecl()))
633 static void deletePaths(CXXBasePaths *);
636 LookupResultKind ResultKind;
637 AmbiguityKind Ambiguity; // ill-defined unless ambiguous
638 UnresolvedSet<8> Decls;
640 CXXRecordDecl *NamingClass;
641 QualType BaseObjectType;
645 DeclarationNameInfo NameInfo;
646 SourceRange NameContextRange;
647 Sema::LookupNameKind LookupKind;
648 unsigned IDNS; // set by configure()
652 /// \brief True if tag declarations should be hidden if non-tags
658 /// \brief True if we should allow hidden declarations to be 'visible'.
662 /// \brief Consumes visible declarations found when searching for
663 /// all visible names within a given scope or context.
665 /// This abstract class is meant to be subclassed by clients of \c
666 /// Sema::LookupVisibleDecls(), each of which should override the \c
667 /// FoundDecl() function to process declarations as they are found.
668 class VisibleDeclConsumer {
670 /// \brief Destroys the visible declaration consumer.
671 virtual ~VisibleDeclConsumer();
673 /// \brief Invoked each time \p Sema::LookupVisibleDecls() finds a
674 /// declaration visible from the current scope or context.
676 /// \param ND the declaration found.
678 /// \param Hiding a declaration that hides the declaration \p ND,
679 /// or NULL if no such declaration exists.
681 /// \param Ctx the original context from which the lookup started.
683 /// \param InBaseClass whether this declaration was found in base
684 /// class of the context we searched.
685 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
686 bool InBaseClass) = 0;
689 /// \brief A class for storing results from argument-dependent lookup.
692 /// A map from canonical decls to the 'most recent' decl.
693 llvm::DenseMap<NamedDecl*, NamedDecl*> Decls;
696 /// Adds a new ADL candidate to this map.
697 void insert(NamedDecl *D);
699 /// Removes any data associated with a given decl.
700 void erase(NamedDecl *D) {
701 Decls.erase(cast<NamedDecl>(D->getCanonicalDecl()));
705 typedef llvm::DenseMap<NamedDecl*,NamedDecl*>::iterator inner_iterator;
708 friend class ADLResult;
709 iterator(const inner_iterator &iter) : iter(iter) {}
713 iterator &operator++() { ++iter; return *this; }
714 iterator operator++(int) { return iterator(iter++); }
716 NamedDecl *operator*() const { return iter->second; }
718 bool operator==(const iterator &other) const { return iter == other.iter; }
719 bool operator!=(const iterator &other) const { return iter != other.iter; }
722 iterator begin() { return iterator(Decls.begin()); }
723 iterator end() { return iterator(Decls.end()); }