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),
148 // TODO: consider whether this constructor should be restricted to take
149 // as input a const IndentifierInfo* (instead of Name),
150 // forcing other cases towards the constructor taking a DNInfo.
151 LookupResult(Sema &SemaRef, DeclarationName Name,
152 SourceLocation NameLoc, Sema::LookupNameKind LookupKind,
153 Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
154 : ResultKind(NotFound),
158 NameInfo(Name, NameLoc),
159 LookupKind(LookupKind),
161 Redecl(Redecl != Sema::NotForRedeclaration),
163 Diagnose(Redecl == Sema::NotForRedeclaration),
164 AllowHidden(Redecl == Sema::ForRedeclaration),
170 /// Creates a temporary lookup result, initializing its core data
171 /// using the information from another result. Diagnostics are always
173 LookupResult(TemporaryToken _, const LookupResult &Other)
174 : ResultKind(NotFound),
177 SemaRef(Other.SemaRef),
178 NameInfo(Other.NameInfo),
179 LookupKind(Other.LookupKind),
181 Redecl(Other.Redecl),
182 HideTags(Other.HideTags),
184 AllowHidden(Other.AllowHidden),
189 if (Diagnose) diagnose();
190 if (Paths) deletePaths(Paths);
193 /// Gets the name info to look up.
194 const DeclarationNameInfo &getLookupNameInfo() const {
198 /// \brief Sets the name info to look up.
199 void setLookupNameInfo(const DeclarationNameInfo &NameInfo) {
200 this->NameInfo = NameInfo;
203 /// Gets the name to look up.
204 DeclarationName getLookupName() const {
205 return NameInfo.getName();
208 /// \brief Sets the name to look up.
209 void setLookupName(DeclarationName Name) {
210 NameInfo.setName(Name);
213 /// Gets the kind of lookup to perform.
214 Sema::LookupNameKind getLookupKind() const {
218 /// True if this lookup is just looking for an existing declaration.
219 bool isForRedeclaration() const {
223 /// \brief Specify whether hidden declarations are visible, e.g.,
224 /// for recovery reasons.
225 void setAllowHidden(bool AH) {
229 /// \brief Determine whether this lookup is permitted to see hidden
230 /// declarations, such as those in modules that have not yet been imported.
231 bool isHiddenDeclarationVisible() const {
232 return AllowHidden || LookupKind == Sema::LookupTagName;
235 /// Sets whether tag declarations should be hidden by non-tag
236 /// declarations during resolution. The default is true.
237 void setHideTags(bool Hide) {
241 bool isAmbiguous() const {
242 return getResultKind() == Ambiguous;
245 /// Determines if this names a single result which is not an
246 /// unresolved value using decl. If so, it is safe to call
248 bool isSingleResult() const {
249 return getResultKind() == Found;
252 /// Determines if the results are overloaded.
253 bool isOverloadedResult() const {
254 return getResultKind() == FoundOverloaded;
257 bool isUnresolvableResult() const {
258 return getResultKind() == FoundUnresolvedValue;
261 LookupResultKind getResultKind() const {
266 AmbiguityKind getAmbiguityKind() const {
267 assert(isAmbiguous());
271 const UnresolvedSetImpl &asUnresolvedSet() const {
275 iterator begin() const { return iterator(Decls.begin()); }
276 iterator end() const { return iterator(Decls.end()); }
278 /// \brief Return true if no decls were found
279 bool empty() const { return Decls.empty(); }
281 /// \brief Return the base paths structure that's associated with
282 /// these results, or null if none is.
283 CXXBasePaths *getBasePaths() const {
287 /// \brief Determine whether the given declaration is visible to the
289 static bool isVisible(Sema &SemaRef, NamedDecl *D) {
290 // If this declaration is not hidden, it's visible.
294 if (SemaRef.ActiveTemplateInstantiations.empty())
297 // During template instantiation, we can refer to hidden declarations, if
298 // they were visible in any module along the path of instantiation.
299 return isVisibleSlow(SemaRef, D);
302 /// \brief Retrieve the accepted (re)declaration of the given declaration,
304 NamedDecl *getAcceptableDecl(NamedDecl *D) const {
305 if (!D->isInIdentifierNamespace(IDNS))
308 if (isHiddenDeclarationVisible() || isVisible(SemaRef, D))
311 return getAcceptableDeclSlow(D);
315 static bool isVisibleSlow(Sema &SemaRef, NamedDecl *D);
316 NamedDecl *getAcceptableDeclSlow(NamedDecl *D) const;
319 /// \brief Returns the identifier namespace mask for this lookup.
320 unsigned getIdentifierNamespace() const {
324 /// \brief Returns whether these results arose from performing a
325 /// lookup into a class.
326 bool isClassLookup() const {
327 return NamingClass != 0;
330 /// \brief Returns the 'naming class' for this lookup, i.e. the
331 /// class which was looked into to find these results.
333 /// C++0x [class.access.base]p5:
334 /// The access to a member is affected by the class in which the
335 /// member is named. This naming class is the class in which the
336 /// member name was looked up and found. [Note: this class can be
337 /// explicit, e.g., when a qualified-id is used, or implicit,
338 /// e.g., when a class member access operator (5.2.5) is used
339 /// (including cases where an implicit "this->" is added). If both
340 /// a class member access operator and a qualified-id are used to
341 /// name the member (as in p->T::m), the class naming the member
342 /// is the class named by the nested-name-specifier of the
343 /// qualified-id (that is, T). -- end note ]
345 /// This is set by the lookup routines when they find results in a class.
346 CXXRecordDecl *getNamingClass() const {
350 /// \brief Sets the 'naming class' for this lookup.
351 void setNamingClass(CXXRecordDecl *Record) {
352 NamingClass = Record;
355 /// \brief Returns the base object type associated with this lookup;
356 /// important for [class.protected]. Most lookups do not have an
357 /// associated base object.
358 QualType getBaseObjectType() const {
359 return BaseObjectType;
362 /// \brief Sets the base object type for this lookup.
363 void setBaseObjectType(QualType T) {
367 /// \brief Add a declaration to these results with its natural access.
368 /// Does not test the acceptance criteria.
369 void addDecl(NamedDecl *D) {
370 addDecl(D, D->getAccess());
373 /// \brief Add a declaration to these results with the given access.
374 /// Does not test the acceptance criteria.
375 void addDecl(NamedDecl *D, AccessSpecifier AS) {
376 Decls.addDecl(D, AS);
380 /// \brief Add all the declarations from another set of lookup
382 void addAllDecls(const LookupResult &Other) {
383 Decls.append(Other.Decls.begin(), Other.Decls.end());
387 /// \brief Determine whether no result was found because we could not
388 /// search into dependent base classes of the current instantiation.
389 bool wasNotFoundInCurrentInstantiation() const {
390 return ResultKind == NotFoundInCurrentInstantiation;
393 /// \brief Note that while no result was found in the current instantiation,
394 /// there were dependent base classes that could not be searched.
395 void setNotFoundInCurrentInstantiation() {
396 assert(ResultKind == NotFound && Decls.empty());
397 ResultKind = NotFoundInCurrentInstantiation;
400 /// \brief Determine whether the lookup result was shadowed by some other
401 /// declaration that lookup ignored.
402 bool isShadowed() const { return Shadowed; }
404 /// \brief Note that we found and ignored a declaration while performing
406 void setShadowed() { Shadowed = true; }
408 /// \brief Resolves the result kind of the lookup, possibly hiding
411 /// This should be called in any environment where lookup might
412 /// generate multiple lookup results.
415 /// \brief Re-resolves the result kind of the lookup after a set of
416 /// removals has been performed.
417 void resolveKindAfterFilter() {
419 if (ResultKind != NotFoundInCurrentInstantiation)
420 ResultKind = NotFound;
427 AmbiguityKind SavedAK = Ambiguity;
431 // If we didn't make the lookup unambiguous, restore the old
433 if (ResultKind == Ambiguous) {
442 template <class DeclClass>
443 DeclClass *getAsSingle() const {
444 if (getResultKind() != Found) return 0;
445 return dyn_cast<DeclClass>(getFoundDecl());
448 /// \brief Fetch the unique decl found by this lookup. Asserts
449 /// that one was found.
451 /// This is intended for users who have examined the result kind
452 /// and are certain that there is only one result.
453 NamedDecl *getFoundDecl() const {
454 assert(getResultKind() == Found
455 && "getFoundDecl called on non-unique result");
456 return (*begin())->getUnderlyingDecl();
459 /// Fetches a representative decl. Useful for lazy diagnostics.
460 NamedDecl *getRepresentativeDecl() const {
461 assert(!Decls.empty() && "cannot get representative of empty set");
465 /// \brief Asks if the result is a single tag decl.
466 bool isSingleTagDecl() const {
467 return getResultKind() == Found && isa<TagDecl>(getFoundDecl());
470 /// \brief Make these results show that the name was found in
471 /// base classes of different types.
473 /// The given paths object is copied and invalidated.
474 void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P);
476 /// \brief Make these results show that the name was found in
477 /// distinct base classes of the same type.
479 /// The given paths object is copied and invalidated.
480 void setAmbiguousBaseSubobjects(CXXBasePaths &P);
482 /// \brief Make these results show that the name was found in
483 /// different contexts and a tag decl was hidden by an ordinary
484 /// decl in a different context.
485 void setAmbiguousQualifiedTagHiding() {
486 setAmbiguous(AmbiguousTagHiding);
489 /// \brief Clears out any current state.
491 ResultKind = NotFound;
493 if (Paths) deletePaths(Paths);
499 /// \brief Clears out any current state and re-initializes for a
500 /// different kind of lookup.
501 void clear(Sema::LookupNameKind Kind) {
507 /// \brief Change this lookup's redeclaration kind.
508 void setRedeclarationKind(Sema::RedeclarationKind RK) {
510 AllowHidden = (RK == Sema::ForRedeclaration);
514 void print(raw_ostream &);
516 /// Suppress the diagnostics that would normally fire because of this
517 /// lookup. This happens during (e.g.) redeclaration lookups.
518 void suppressDiagnostics() {
522 /// Determines whether this lookup is suppressing diagnostics.
523 bool isSuppressingDiagnostics() const {
527 /// Sets a 'context' source range.
528 void setContextRange(SourceRange SR) {
529 NameContextRange = SR;
532 /// Gets the source range of the context of this name; for C++
533 /// qualified lookups, this is the source range of the scope
535 SourceRange getContextRange() const {
536 return NameContextRange;
539 /// Gets the location of the identifier. This isn't always defined:
540 /// sometimes we're doing lookups on synthesized names.
541 SourceLocation getNameLoc() const {
542 return NameInfo.getLoc();
545 /// \brief Get the Sema object that this lookup result is searching
547 Sema &getSema() const { return SemaRef; }
549 /// A class for iterating through a result set and possibly
550 /// filtering out results. The results returned are possibly
553 LookupResult &Results;
554 LookupResult::iterator I;
558 friend class LookupResult;
559 Filter(LookupResult &Results)
560 : Results(Results), I(Results.begin()), Changed(false), CalledDone(false)
566 "LookupResult::Filter destroyed without done() call");
569 bool hasNext() const {
570 return I != Results.end();
574 assert(I != Results.end() && "next() called on empty filter");
578 /// Restart the iteration.
583 /// Erase the last element returned from this iterator.
585 Results.Decls.erase(--I);
589 /// Replaces the current entry with the given one, preserving the
591 void replace(NamedDecl *D) {
592 Results.Decls.replace(I-1, D);
596 /// Replaces the current entry with the given one.
597 void replace(NamedDecl *D, AccessSpecifier AS) {
598 Results.Decls.replace(I-1, D, AS);
603 assert(!CalledDone && "done() called twice");
607 Results.resolveKindAfterFilter();
611 /// Create a filter for this result set.
612 Filter makeFilter() {
613 return Filter(*this);
616 void setFindLocalExtern(bool FindLocalExtern) {
618 IDNS |= Decl::IDNS_LocalExtern;
620 IDNS &= ~Decl::IDNS_LocalExtern;
626 SemaRef.DiagnoseAmbiguousLookup(*this);
627 else if (isClassLookup() && SemaRef.getLangOpts().AccessControl)
628 SemaRef.CheckLookupAccess(*this);
631 void setAmbiguous(AmbiguityKind AK) {
632 ResultKind = Ambiguous;
636 void addDeclsFromBasePaths(const CXXBasePaths &P);
640 void sanityImpl() const;
642 void sanity() const {
648 bool sanityCheckUnresolved() const {
649 for (iterator I = begin(), E = end(); I != E; ++I)
650 if (isa<UnresolvedUsingValueDecl>((*I)->getUnderlyingDecl()))
655 static void deletePaths(CXXBasePaths *);
658 LookupResultKind ResultKind;
659 AmbiguityKind Ambiguity; // ill-defined unless ambiguous
660 UnresolvedSet<8> Decls;
662 CXXRecordDecl *NamingClass;
663 QualType BaseObjectType;
667 DeclarationNameInfo NameInfo;
668 SourceRange NameContextRange;
669 Sema::LookupNameKind LookupKind;
670 unsigned IDNS; // set by configure()
674 /// \brief True if tag declarations should be hidden if non-tags
680 /// \brief True if we should allow hidden declarations to be 'visible'.
683 /// \brief True if the found declarations were shadowed by some other
684 /// declaration that we skipped. This only happens when \c LookupKind
685 /// is \c LookupRedeclarationWithLinkage.
689 /// \brief Consumes visible declarations found when searching for
690 /// all visible names within a given scope or context.
692 /// This abstract class is meant to be subclassed by clients of \c
693 /// Sema::LookupVisibleDecls(), each of which should override the \c
694 /// FoundDecl() function to process declarations as they are found.
695 class VisibleDeclConsumer {
697 /// \brief Destroys the visible declaration consumer.
698 virtual ~VisibleDeclConsumer();
700 /// \brief Determine whether hidden declarations (from unimported
701 /// modules) should be given to this consumer. By default, they
702 /// are not included.
703 virtual bool includeHiddenDecls() const;
705 /// \brief Invoked each time \p Sema::LookupVisibleDecls() finds a
706 /// declaration visible from the current scope or context.
708 /// \param ND the declaration found.
710 /// \param Hiding a declaration that hides the declaration \p ND,
711 /// or NULL if no such declaration exists.
713 /// \param Ctx the original context from which the lookup started.
715 /// \param InBaseClass whether this declaration was found in base
716 /// class of the context we searched.
717 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
718 bool InBaseClass) = 0;
721 /// \brief A class for storing results from argument-dependent lookup.
724 /// A map from canonical decls to the 'most recent' decl.
725 llvm::DenseMap<NamedDecl*, NamedDecl*> Decls;
728 /// Adds a new ADL candidate to this map.
729 void insert(NamedDecl *D);
731 /// Removes any data associated with a given decl.
732 void erase(NamedDecl *D) {
733 Decls.erase(cast<NamedDecl>(D->getCanonicalDecl()));
737 : public std::iterator<std::forward_iterator_tag, NamedDecl *> {
738 typedef llvm::DenseMap<NamedDecl*,NamedDecl*>::iterator inner_iterator;
741 friend class ADLResult;
742 iterator(const inner_iterator &iter) : iter(iter) {}
746 iterator &operator++() { ++iter; return *this; }
747 iterator operator++(int) { return iterator(iter++); }
749 value_type operator*() const { return iter->second; }
751 bool operator==(const iterator &other) const { return iter == other.iter; }
752 bool operator!=(const iterator &other) const { return iter != other.iter; }
755 iterator begin() { return iterator(Decls.begin()); }
756 iterator end() { return iterator(Decls.end()); }