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/Sema/Sema.h"
19 #include "clang/AST/DeclCXX.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)
146 // TODO: consider whether this constructor should be restricted to take
147 // as input a const IndentifierInfo* (instead of Name),
148 // forcing other cases towards the constructor taking a DNInfo.
149 LookupResult(Sema &SemaRef, DeclarationName Name,
150 SourceLocation NameLoc, Sema::LookupNameKind LookupKind,
151 Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
152 : ResultKind(NotFound),
156 NameInfo(Name, NameLoc),
157 LookupKind(LookupKind),
159 Redecl(Redecl != Sema::NotForRedeclaration),
161 Diagnose(Redecl == Sema::NotForRedeclaration)
166 /// Creates a temporary lookup result, initializing its core data
167 /// using the information from another result. Diagnostics are always
169 LookupResult(TemporaryToken _, const LookupResult &Other)
170 : ResultKind(NotFound),
173 SemaRef(Other.SemaRef),
174 NameInfo(Other.NameInfo),
175 LookupKind(Other.LookupKind),
177 Redecl(Other.Redecl),
178 HideTags(Other.HideTags),
183 if (Diagnose) diagnose();
184 if (Paths) deletePaths(Paths);
187 /// Gets the name info to look up.
188 const DeclarationNameInfo &getLookupNameInfo() const {
192 /// \brief Sets the name info to look up.
193 void setLookupNameInfo(const DeclarationNameInfo &NameInfo) {
194 this->NameInfo = NameInfo;
197 /// Gets the name to look up.
198 DeclarationName getLookupName() const {
199 return NameInfo.getName();
202 /// \brief Sets the name to look up.
203 void setLookupName(DeclarationName Name) {
204 NameInfo.setName(Name);
207 /// Gets the kind of lookup to perform.
208 Sema::LookupNameKind getLookupKind() const {
212 /// True if this lookup is just looking for an existing declaration.
213 bool isForRedeclaration() const {
217 /// Sets whether tag declarations should be hidden by non-tag
218 /// declarations during resolution. The default is true.
219 void setHideTags(bool Hide) {
223 bool isAmbiguous() const {
224 return getResultKind() == Ambiguous;
227 /// Determines if this names a single result which is not an
228 /// unresolved value using decl. If so, it is safe to call
230 bool isSingleResult() const {
231 return getResultKind() == Found;
234 /// Determines if the results are overloaded.
235 bool isOverloadedResult() const {
236 return getResultKind() == FoundOverloaded;
239 bool isUnresolvableResult() const {
240 return getResultKind() == FoundUnresolvedValue;
243 LookupResultKind getResultKind() const {
248 AmbiguityKind getAmbiguityKind() const {
249 assert(isAmbiguous());
253 const UnresolvedSetImpl &asUnresolvedSet() const {
257 iterator begin() const { return iterator(Decls.begin()); }
258 iterator end() const { return iterator(Decls.end()); }
260 /// \brief Return true if no decls were found
261 bool empty() const { return Decls.empty(); }
263 /// \brief Return the base paths structure that's associated with
264 /// these results, or null if none is.
265 CXXBasePaths *getBasePaths() const {
269 /// \brief Tests whether the given declaration is acceptable.
270 bool isAcceptableDecl(NamedDecl *D) const {
271 return D->isInIdentifierNamespace(IDNS);
274 /// \brief Returns the identifier namespace mask for this lookup.
275 unsigned getIdentifierNamespace() const {
279 /// \brief Returns whether these results arose from performing a
280 /// lookup into a class.
281 bool isClassLookup() const {
282 return NamingClass != 0;
285 /// \brief Set whether the name lookup is triggered by a
286 /// using declaration.
287 void setUsingDeclaration(bool U) {
288 UsingDeclaration = U;
291 /// \brief Returns whether the name lookup is triggered by a
292 /// using declaration.
293 bool isUsingDeclaration() const {
294 return UsingDeclaration;
297 /// \brief Returns the 'naming class' for this lookup, i.e. the
298 /// class which was looked into to find these results.
300 /// C++0x [class.access.base]p5:
301 /// The access to a member is affected by the class in which the
302 /// member is named. This naming class is the class in which the
303 /// member name was looked up and found. [Note: this class can be
304 /// explicit, e.g., when a qualified-id is used, or implicit,
305 /// e.g., when a class member access operator (5.2.5) is used
306 /// (including cases where an implicit "this->" is added). If both
307 /// a class member access operator and a qualified-id are used to
308 /// name the member (as in p->T::m), the class naming the member
309 /// is the class named by the nested-name-specifier of the
310 /// qualified-id (that is, T). -- end note ]
312 /// This is set by the lookup routines when they find results in a class.
313 CXXRecordDecl *getNamingClass() const {
317 /// \brief Sets the 'naming class' for this lookup.
318 void setNamingClass(CXXRecordDecl *Record) {
319 NamingClass = Record;
322 /// \brief Returns the base object type associated with this lookup;
323 /// important for [class.protected]. Most lookups do not have an
324 /// associated base object.
325 QualType getBaseObjectType() const {
326 return BaseObjectType;
329 /// \brief Sets the base object type for this lookup.
330 void setBaseObjectType(QualType T) {
334 /// \brief Add a declaration to these results with its natural access.
335 /// Does not test the acceptance criteria.
336 void addDecl(NamedDecl *D) {
337 addDecl(D, D->getAccess());
340 /// \brief Add a declaration to these results with the given access.
341 /// Does not test the acceptance criteria.
342 void addDecl(NamedDecl *D, AccessSpecifier AS) {
343 Decls.addDecl(D, AS);
347 /// \brief Add all the declarations from another set of lookup
349 void addAllDecls(const LookupResult &Other) {
350 Decls.append(Other.Decls.begin(), Other.Decls.end());
354 /// \brief Determine whether no result was found because we could not
355 /// search into dependent base classes of the current instantiation.
356 bool wasNotFoundInCurrentInstantiation() const {
357 return ResultKind == NotFoundInCurrentInstantiation;
360 /// \brief Note that while no result was found in the current instantiation,
361 /// there were dependent base classes that could not be searched.
362 void setNotFoundInCurrentInstantiation() {
363 assert(ResultKind == NotFound && Decls.empty());
364 ResultKind = NotFoundInCurrentInstantiation;
367 /// \brief Resolves the result kind of the lookup, possibly hiding
370 /// This should be called in any environment where lookup might
371 /// generate multiple lookup results.
374 /// \brief Re-resolves the result kind of the lookup after a set of
375 /// removals has been performed.
376 void resolveKindAfterFilter() {
378 if (ResultKind != NotFoundInCurrentInstantiation)
379 ResultKind = NotFound;
386 AmbiguityKind SavedAK = Ambiguity;
390 // If we didn't make the lookup unambiguous, restore the old
392 if (ResultKind == Ambiguous) {
401 template <class DeclClass>
402 DeclClass *getAsSingle() const {
403 if (getResultKind() != Found) return 0;
404 return dyn_cast<DeclClass>(getFoundDecl());
407 /// \brief Fetch the unique decl found by this lookup. Asserts
408 /// that one was found.
410 /// This is intended for users who have examined the result kind
411 /// and are certain that there is only one result.
412 NamedDecl *getFoundDecl() const {
413 assert(getResultKind() == Found
414 && "getFoundDecl called on non-unique result");
415 return (*begin())->getUnderlyingDecl();
418 /// Fetches a representative decl. Useful for lazy diagnostics.
419 NamedDecl *getRepresentativeDecl() const {
420 assert(!Decls.empty() && "cannot get representative of empty set");
424 /// \brief Asks if the result is a single tag decl.
425 bool isSingleTagDecl() const {
426 return getResultKind() == Found && isa<TagDecl>(getFoundDecl());
429 /// \brief Make these results show that the name was found in
430 /// base classes of different types.
432 /// The given paths object is copied and invalidated.
433 void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P);
435 /// \brief Make these results show that the name was found in
436 /// distinct base classes of the same type.
438 /// The given paths object is copied and invalidated.
439 void setAmbiguousBaseSubobjects(CXXBasePaths &P);
441 /// \brief Make these results show that the name was found in
442 /// different contexts and a tag decl was hidden by an ordinary
443 /// decl in a different context.
444 void setAmbiguousQualifiedTagHiding() {
445 setAmbiguous(AmbiguousTagHiding);
448 /// \brief Clears out any current state.
450 ResultKind = NotFound;
452 if (Paths) deletePaths(Paths);
457 /// \brief Clears out any current state and re-initializes for a
458 /// different kind of lookup.
459 void clear(Sema::LookupNameKind Kind) {
465 /// \brief Change this lookup's redeclaration kind.
466 void setRedeclarationKind(Sema::RedeclarationKind RK) {
471 void print(llvm::raw_ostream &);
473 /// Suppress the diagnostics that would normally fire because of this
474 /// lookup. This happens during (e.g.) redeclaration lookups.
475 void suppressDiagnostics() {
479 /// Determines whether this lookup is suppressing diagnostics.
480 bool isSuppressingDiagnostics() const {
484 /// Sets a 'context' source range.
485 void setContextRange(SourceRange SR) {
486 NameContextRange = SR;
489 /// Gets the source range of the context of this name; for C++
490 /// qualified lookups, this is the source range of the scope
492 SourceRange getContextRange() const {
493 return NameContextRange;
496 /// Gets the location of the identifier. This isn't always defined:
497 /// sometimes we're doing lookups on synthesized names.
498 SourceLocation getNameLoc() const {
499 return NameInfo.getLoc();
502 /// \brief Get the Sema object that this lookup result is searching
504 Sema &getSema() const { return SemaRef; }
506 /// A class for iterating through a result set and possibly
507 /// filtering out results. The results returned are possibly
510 LookupResult &Results;
511 LookupResult::iterator I;
515 friend class LookupResult;
516 Filter(LookupResult &Results)
517 : Results(Results), I(Results.begin()), Changed(false), CalledDone(false)
523 "LookupResult::Filter destroyed without done() call");
526 bool hasNext() const {
527 return I != Results.end();
531 assert(I != Results.end() && "next() called on empty filter");
535 /// Erase the last element returned from this iterator.
537 Results.Decls.erase(--I);
541 /// Replaces the current entry with the given one, preserving the
543 void replace(NamedDecl *D) {
544 Results.Decls.replace(I-1, D);
548 /// Replaces the current entry with the given one.
549 void replace(NamedDecl *D, AccessSpecifier AS) {
550 Results.Decls.replace(I-1, D, AS);
555 assert(!CalledDone && "done() called twice");
559 Results.resolveKindAfterFilter();
563 /// Create a filter for this result set.
564 Filter makeFilter() {
565 return Filter(*this);
571 SemaRef.DiagnoseAmbiguousLookup(*this);
572 else if (isClassLookup() && SemaRef.getLangOptions().AccessControl)
573 SemaRef.CheckLookupAccess(*this);
576 void setAmbiguous(AmbiguityKind AK) {
577 ResultKind = Ambiguous;
581 void addDeclsFromBasePaths(const CXXBasePaths &P);
587 bool sanityCheckUnresolved() const {
588 for (iterator I = begin(), E = end(); I != E; ++I)
589 if (isa<UnresolvedUsingValueDecl>(*I))
594 static void deletePaths(CXXBasePaths *);
597 LookupResultKind ResultKind;
598 AmbiguityKind Ambiguity; // ill-defined unless ambiguous
599 UnresolvedSet<8> Decls;
601 CXXRecordDecl *NamingClass;
602 QualType BaseObjectType;
606 DeclarationNameInfo NameInfo;
607 SourceRange NameContextRange;
608 Sema::LookupNameKind LookupKind;
609 unsigned IDNS; // set by configure()
613 /// \brief True if tag declarations should be hidden if non-tags
619 /// \brief True if the lookup is triggered by a using declaration.
620 /// Necessary to handle a MSVC bug.
621 bool UsingDeclaration;
624 /// \brief Consumes visible declarations found when searching for
625 /// all visible names within a given scope or context.
627 /// This abstract class is meant to be subclassed by clients of \c
628 /// Sema::LookupVisibleDecls(), each of which should override the \c
629 /// FoundDecl() function to process declarations as they are found.
630 class VisibleDeclConsumer {
632 /// \brief Destroys the visible declaration consumer.
633 virtual ~VisibleDeclConsumer();
635 /// \brief Invoked each time \p Sema::LookupVisibleDecls() finds a
636 /// declaration visible from the current scope or context.
638 /// \param ND the declaration found.
640 /// \param Hiding a declaration that hides the declaration \p ND,
641 /// or NULL if no such declaration exists.
643 /// \param InBaseClass whether this declaration was found in base
644 /// class of the context we searched.
645 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
646 bool InBaseClass) = 0;
649 /// \brief A class for storing results from argument-dependent lookup.
652 /// A map from canonical decls to the 'most recent' decl.
653 llvm::DenseMap<NamedDecl*, NamedDecl*> Decls;
656 /// Adds a new ADL candidate to this map.
657 void insert(NamedDecl *D);
659 /// Removes any data associated with a given decl.
660 void erase(NamedDecl *D) {
661 Decls.erase(cast<NamedDecl>(D->getCanonicalDecl()));
665 typedef llvm::DenseMap<NamedDecl*,NamedDecl*>::iterator inner_iterator;
668 friend class ADLResult;
669 iterator(const inner_iterator &iter) : iter(iter) {}
673 iterator &operator++() { ++iter; return *this; }
674 iterator operator++(int) { return iterator(iter++); }
676 NamedDecl *operator*() const { return iter->second; }
678 bool operator==(const iterator &other) const { return iter == other.iter; }
679 bool operator!=(const iterator &other) const { return iter != other.iter; }
682 iterator begin() { return iterator(Decls.begin()); }
683 iterator end() { return iterator(Decls.end()); }