Lookup.h revision f143ffc4a9af79ac1d822fea6995af4bf45d17dc
1//===--- Lookup.h - Classes for name lookup ---------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the LookupResult class, which is integral to
11// Sema's name-lookup subsystem.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SEMA_LOOKUP_H
16#define LLVM_CLANG_SEMA_LOOKUP_H
17
18#include "clang/Sema/Sema.h"
19#include "clang/AST/DeclCXX.h"
20
21namespace clang {
22
23/// @brief Represents the results of name lookup.
24///
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.
30class LookupResult {
31public:
32  enum LookupResultKind {
33    /// @brief No entity found met the criteria.
34    NotFound = 0,
35
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,
40
41    /// @brief Name lookup found a single declaration that met the
42    /// criteria.  getFoundDecl() will return this declaration.
43    Found,
44
45    /// @brief Name lookup found a set of overloaded functions that
46    /// met the criteria.
47    FoundOverloaded,
48
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.
52    FoundUnresolvedValue,
53
54    /// @brief Name lookup results in an ambiguity; use
55    /// getAmbiguityKind to figure out what kind of ambiguity
56    /// we have.
57    Ambiguous
58  };
59
60  enum AmbiguityKind {
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:
64    /// @code
65    /// struct A { void f(int); }
66    /// struct B { void f(double); }
67    /// struct C : A, B { };
68    /// void test(C c) {
69    ///   c.f(0); // error: A::f and B::f come from subobjects of different
70    ///           // types. overload resolution is not performed.
71    /// }
72    /// @endcode
73    AmbiguousBaseSubobjectTypes,
74
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:
78    /// @code
79    /// struct A { int x; };
80    /// struct B : A { };
81    /// struct C : A { };
82    /// struct D : B, C { };
83    /// int test(D d) {
84    ///   return d.x; // error: 'x' is found in two A subobjects (of B and C)
85    /// }
86    /// @endcode
87    AmbiguousBaseSubobjects,
88
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.
92    /// @code
93    /// namespace A {
94    ///   int i;
95    ///   namespace B { int i; }
96    ///   int test() {
97    ///     using namespace B;
98    ///     return i; // error 'i' is found in namespace A and A::B
99    ///    }
100    /// }
101    /// @endcode
102    AmbiguousReference,
103
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.
107    /// @code
108    /// namespace A { struct Foo {}; }
109    /// namespace B { void Foo(); }
110    /// namespace C {
111    ///   using namespace A;
112    ///   using namespace B;
113    /// }
114    /// void test() {
115    ///   C::Foo(); // error: tag 'A::Foo' is hidden by an object in a
116    ///             // different namespace
117    /// }
118    /// @endcode
119    AmbiguousTagHiding
120  };
121
122  /// A little identifier for flagging temporary lookup results.
123  enum TemporaryToken {
124    Temporary
125  };
126
127  typedef UnresolvedSetImpl::iterator iterator;
128
129  LookupResult(Sema &SemaRef, const DeclarationNameInfo &NameInfo,
130               Sema::LookupNameKind LookupKind,
131               Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
132    : ResultKind(NotFound),
133      Paths(0),
134      NamingClass(0),
135      SemaRef(SemaRef),
136      NameInfo(NameInfo),
137      LookupKind(LookupKind),
138      IDNS(0),
139      Redecl(Redecl != Sema::NotForRedeclaration),
140      HideTags(true),
141      Diagnose(Redecl == Sema::NotForRedeclaration)
142  {
143    configure();
144  }
145
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),
153      Paths(0),
154      NamingClass(0),
155      SemaRef(SemaRef),
156      NameInfo(Name, NameLoc),
157      LookupKind(LookupKind),
158      IDNS(0),
159      Redecl(Redecl != Sema::NotForRedeclaration),
160      HideTags(true),
161      Diagnose(Redecl == Sema::NotForRedeclaration)
162  {
163    configure();
164  }
165
166  /// Creates a temporary lookup result, initializing its core data
167  /// using the information from another result.  Diagnostics are always
168  /// disabled.
169  LookupResult(TemporaryToken _, const LookupResult &Other)
170    : ResultKind(NotFound),
171      Paths(0),
172      NamingClass(0),
173      SemaRef(Other.SemaRef),
174      NameInfo(Other.NameInfo),
175      LookupKind(Other.LookupKind),
176      IDNS(Other.IDNS),
177      Redecl(Other.Redecl),
178      HideTags(Other.HideTags),
179      Diagnose(false)
180  {}
181
182  ~LookupResult() {
183    if (Diagnose) diagnose();
184    if (Paths) deletePaths(Paths);
185  }
186
187  /// Gets the name info to look up.
188  const DeclarationNameInfo &getLookupNameInfo() const {
189    return NameInfo;
190  }
191
192  /// \brief Sets the name info to look up.
193  void setLookupNameInfo(const DeclarationNameInfo &NameInfo) {
194    this->NameInfo = NameInfo;
195  }
196
197  /// Gets the name to look up.
198  DeclarationName getLookupName() const {
199    return NameInfo.getName();
200  }
201
202  /// \brief Sets the name to look up.
203  void setLookupName(DeclarationName Name) {
204    NameInfo.setName(Name);
205  }
206
207  /// Gets the kind of lookup to perform.
208  Sema::LookupNameKind getLookupKind() const {
209    return LookupKind;
210  }
211
212  /// True if this lookup is just looking for an existing declaration.
213  bool isForRedeclaration() const {
214    return Redecl;
215  }
216
217  /// \brief Determine whether this lookup is permitted to see hidden
218  /// declarations, such as those in modules that have not yet been imported.
219  bool isHiddenDeclarationVisible() const {
220    return Redecl || LookupKind == Sema::LookupTagName;
221  }
222
223  /// Sets whether tag declarations should be hidden by non-tag
224  /// declarations during resolution.  The default is true.
225  void setHideTags(bool Hide) {
226    HideTags = Hide;
227  }
228
229  bool isAmbiguous() const {
230    return getResultKind() == Ambiguous;
231  }
232
233  /// Determines if this names a single result which is not an
234  /// unresolved value using decl.  If so, it is safe to call
235  /// getFoundDecl().
236  bool isSingleResult() const {
237    return getResultKind() == Found;
238  }
239
240  /// Determines if the results are overloaded.
241  bool isOverloadedResult() const {
242    return getResultKind() == FoundOverloaded;
243  }
244
245  bool isUnresolvableResult() const {
246    return getResultKind() == FoundUnresolvedValue;
247  }
248
249  LookupResultKind getResultKind() const {
250    sanity();
251    return ResultKind;
252  }
253
254  AmbiguityKind getAmbiguityKind() const {
255    assert(isAmbiguous());
256    return Ambiguity;
257  }
258
259  const UnresolvedSetImpl &asUnresolvedSet() const {
260    return Decls;
261  }
262
263  iterator begin() const { return iterator(Decls.begin()); }
264  iterator end() const { return iterator(Decls.end()); }
265
266  /// \brief Return true if no decls were found
267  bool empty() const { return Decls.empty(); }
268
269  /// \brief Return the base paths structure that's associated with
270  /// these results, or null if none is.
271  CXXBasePaths *getBasePaths() const {
272    return Paths;
273  }
274
275  /// \brief Determine whether the given declaration is visible to the
276  /// program.
277  static bool isVisible(NamedDecl *D) {
278    // If this declaration is not hidden, it's visible.
279    if (!D->isHidden())
280      return true;
281
282    // FIXME: We should be allowed to refer to a module-private name from
283    // within the same module, e.g., during template instantiation.
284    // This requires us know which module a particular declaration came from.
285    return false;
286  }
287
288  /// \brief Retrieve the accepted (re)declaration of the given declaration,
289  /// if there is one.
290  NamedDecl *getAcceptableDecl(NamedDecl *D) const {
291    if (!D->isInIdentifierNamespace(IDNS))
292      return 0;
293
294    if (isHiddenDeclarationVisible() || isVisible(D))
295      return D;
296
297    return getAcceptableDeclSlow(D);
298  }
299
300private:
301  NamedDecl *getAcceptableDeclSlow(NamedDecl *D) const;
302public:
303
304  /// \brief Returns the identifier namespace mask for this lookup.
305  unsigned getIdentifierNamespace() const {
306    return IDNS;
307  }
308
309  /// \brief Returns whether these results arose from performing a
310  /// lookup into a class.
311  bool isClassLookup() const {
312    return NamingClass != 0;
313  }
314
315  /// \brief Returns the 'naming class' for this lookup, i.e. the
316  /// class which was looked into to find these results.
317  ///
318  /// C++0x [class.access.base]p5:
319  ///   The access to a member is affected by the class in which the
320  ///   member is named. This naming class is the class in which the
321  ///   member name was looked up and found. [Note: this class can be
322  ///   explicit, e.g., when a qualified-id is used, or implicit,
323  ///   e.g., when a class member access operator (5.2.5) is used
324  ///   (including cases where an implicit "this->" is added). If both
325  ///   a class member access operator and a qualified-id are used to
326  ///   name the member (as in p->T::m), the class naming the member
327  ///   is the class named by the nested-name-specifier of the
328  ///   qualified-id (that is, T). -- end note ]
329  ///
330  /// This is set by the lookup routines when they find results in a class.
331  CXXRecordDecl *getNamingClass() const {
332    return NamingClass;
333  }
334
335  /// \brief Sets the 'naming class' for this lookup.
336  void setNamingClass(CXXRecordDecl *Record) {
337    NamingClass = Record;
338  }
339
340  /// \brief Returns the base object type associated with this lookup;
341  /// important for [class.protected].  Most lookups do not have an
342  /// associated base object.
343  QualType getBaseObjectType() const {
344    return BaseObjectType;
345  }
346
347  /// \brief Sets the base object type for this lookup.
348  void setBaseObjectType(QualType T) {
349    BaseObjectType = T;
350  }
351
352  /// \brief Add a declaration to these results with its natural access.
353  /// Does not test the acceptance criteria.
354  void addDecl(NamedDecl *D) {
355    addDecl(D, D->getAccess());
356  }
357
358  /// \brief Add a declaration to these results with the given access.
359  /// Does not test the acceptance criteria.
360  void addDecl(NamedDecl *D, AccessSpecifier AS) {
361    Decls.addDecl(D, AS);
362    ResultKind = Found;
363  }
364
365  /// \brief Add all the declarations from another set of lookup
366  /// results.
367  void addAllDecls(const LookupResult &Other) {
368    Decls.append(Other.Decls.begin(), Other.Decls.end());
369    ResultKind = Found;
370  }
371
372  /// \brief Determine whether no result was found because we could not
373  /// search into dependent base classes of the current instantiation.
374  bool wasNotFoundInCurrentInstantiation() const {
375    return ResultKind == NotFoundInCurrentInstantiation;
376  }
377
378  /// \brief Note that while no result was found in the current instantiation,
379  /// there were dependent base classes that could not be searched.
380  void setNotFoundInCurrentInstantiation() {
381    assert(ResultKind == NotFound && Decls.empty());
382    ResultKind = NotFoundInCurrentInstantiation;
383  }
384
385  /// \brief Resolves the result kind of the lookup, possibly hiding
386  /// decls.
387  ///
388  /// This should be called in any environment where lookup might
389  /// generate multiple lookup results.
390  void resolveKind();
391
392  /// \brief Re-resolves the result kind of the lookup after a set of
393  /// removals has been performed.
394  void resolveKindAfterFilter() {
395    if (Decls.empty()) {
396      if (ResultKind != NotFoundInCurrentInstantiation)
397        ResultKind = NotFound;
398
399      if (Paths) {
400        deletePaths(Paths);
401        Paths = 0;
402      }
403    } else {
404      AmbiguityKind SavedAK = Ambiguity;
405      ResultKind = Found;
406      resolveKind();
407
408      // If we didn't make the lookup unambiguous, restore the old
409      // ambiguity kind.
410      if (ResultKind == Ambiguous) {
411        Ambiguity = SavedAK;
412      } else if (Paths) {
413        deletePaths(Paths);
414        Paths = 0;
415      }
416    }
417  }
418
419  template <class DeclClass>
420  DeclClass *getAsSingle() const {
421    if (getResultKind() != Found) return 0;
422    return dyn_cast<DeclClass>(getFoundDecl());
423  }
424
425  /// \brief Fetch the unique decl found by this lookup.  Asserts
426  /// that one was found.
427  ///
428  /// This is intended for users who have examined the result kind
429  /// and are certain that there is only one result.
430  NamedDecl *getFoundDecl() const {
431    assert(getResultKind() == Found
432           && "getFoundDecl called on non-unique result");
433    return (*begin())->getUnderlyingDecl();
434  }
435
436  /// Fetches a representative decl.  Useful for lazy diagnostics.
437  NamedDecl *getRepresentativeDecl() const {
438    assert(!Decls.empty() && "cannot get representative of empty set");
439    return *begin();
440  }
441
442  /// \brief Asks if the result is a single tag decl.
443  bool isSingleTagDecl() const {
444    return getResultKind() == Found && isa<TagDecl>(getFoundDecl());
445  }
446
447  /// \brief Make these results show that the name was found in
448  /// base classes of different types.
449  ///
450  /// The given paths object is copied and invalidated.
451  void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P);
452
453  /// \brief Make these results show that the name was found in
454  /// distinct base classes of the same type.
455  ///
456  /// The given paths object is copied and invalidated.
457  void setAmbiguousBaseSubobjects(CXXBasePaths &P);
458
459  /// \brief Make these results show that the name was found in
460  /// different contexts and a tag decl was hidden by an ordinary
461  /// decl in a different context.
462  void setAmbiguousQualifiedTagHiding() {
463    setAmbiguous(AmbiguousTagHiding);
464  }
465
466  /// \brief Clears out any current state.
467  void clear() {
468    ResultKind = NotFound;
469    Decls.clear();
470    if (Paths) deletePaths(Paths);
471    Paths = NULL;
472    NamingClass = 0;
473  }
474
475  /// \brief Clears out any current state and re-initializes for a
476  /// different kind of lookup.
477  void clear(Sema::LookupNameKind Kind) {
478    clear();
479    LookupKind = Kind;
480    configure();
481  }
482
483  /// \brief Change this lookup's redeclaration kind.
484  void setRedeclarationKind(Sema::RedeclarationKind RK) {
485    Redecl = RK;
486    configure();
487  }
488
489  void print(raw_ostream &);
490
491  /// Suppress the diagnostics that would normally fire because of this
492  /// lookup.  This happens during (e.g.) redeclaration lookups.
493  void suppressDiagnostics() {
494    Diagnose = false;
495  }
496
497  /// Determines whether this lookup is suppressing diagnostics.
498  bool isSuppressingDiagnostics() const {
499    return !Diagnose;
500  }
501
502  /// Sets a 'context' source range.
503  void setContextRange(SourceRange SR) {
504    NameContextRange = SR;
505  }
506
507  /// Gets the source range of the context of this name; for C++
508  /// qualified lookups, this is the source range of the scope
509  /// specifier.
510  SourceRange getContextRange() const {
511    return NameContextRange;
512  }
513
514  /// Gets the location of the identifier.  This isn't always defined:
515  /// sometimes we're doing lookups on synthesized names.
516  SourceLocation getNameLoc() const {
517    return NameInfo.getLoc();
518  }
519
520  /// \brief Get the Sema object that this lookup result is searching
521  /// with.
522  Sema &getSema() const { return SemaRef; }
523
524  /// A class for iterating through a result set and possibly
525  /// filtering out results.  The results returned are possibly
526  /// sugared.
527  class Filter {
528    LookupResult &Results;
529    LookupResult::iterator I;
530    bool Changed;
531    bool CalledDone;
532
533    friend class LookupResult;
534    Filter(LookupResult &Results)
535      : Results(Results), I(Results.begin()), Changed(false), CalledDone(false)
536    {}
537
538  public:
539    ~Filter() {
540      assert(CalledDone &&
541             "LookupResult::Filter destroyed without done() call");
542    }
543
544    bool hasNext() const {
545      return I != Results.end();
546    }
547
548    NamedDecl *next() {
549      assert(I != Results.end() && "next() called on empty filter");
550      return *I++;
551    }
552
553    /// Erase the last element returned from this iterator.
554    void erase() {
555      Results.Decls.erase(--I);
556      Changed = true;
557    }
558
559    /// Replaces the current entry with the given one, preserving the
560    /// access bits.
561    void replace(NamedDecl *D) {
562      Results.Decls.replace(I-1, D);
563      Changed = true;
564    }
565
566    /// Replaces the current entry with the given one.
567    void replace(NamedDecl *D, AccessSpecifier AS) {
568      Results.Decls.replace(I-1, D, AS);
569      Changed = true;
570    }
571
572    void done() {
573      assert(!CalledDone && "done() called twice");
574      CalledDone = true;
575
576      if (Changed)
577        Results.resolveKindAfterFilter();
578    }
579  };
580
581  /// Create a filter for this result set.
582  Filter makeFilter() {
583    return Filter(*this);
584  }
585
586private:
587  void diagnose() {
588    if (isAmbiguous())
589      SemaRef.DiagnoseAmbiguousLookup(*this);
590    else if (isClassLookup() && SemaRef.getLangOptions().AccessControl)
591      SemaRef.CheckLookupAccess(*this);
592  }
593
594  void setAmbiguous(AmbiguityKind AK) {
595    ResultKind = Ambiguous;
596    Ambiguity = AK;
597  }
598
599  void addDeclsFromBasePaths(const CXXBasePaths &P);
600  void configure();
601
602  // Sanity checks.
603  void sanity() const;
604
605  bool sanityCheckUnresolved() const {
606    for (iterator I = begin(), E = end(); I != E; ++I)
607      if (isa<UnresolvedUsingValueDecl>(*I))
608        return true;
609    return false;
610  }
611
612  static void deletePaths(CXXBasePaths *);
613
614  // Results.
615  LookupResultKind ResultKind;
616  AmbiguityKind Ambiguity; // ill-defined unless ambiguous
617  UnresolvedSet<8> Decls;
618  CXXBasePaths *Paths;
619  CXXRecordDecl *NamingClass;
620  QualType BaseObjectType;
621
622  // Parameters.
623  Sema &SemaRef;
624  DeclarationNameInfo NameInfo;
625  SourceRange NameContextRange;
626  Sema::LookupNameKind LookupKind;
627  unsigned IDNS; // set by configure()
628
629  bool Redecl;
630
631  /// \brief True if tag declarations should be hidden if non-tags
632  ///   are present
633  bool HideTags;
634
635  bool Diagnose;
636};
637
638  /// \brief Consumes visible declarations found when searching for
639  /// all visible names within a given scope or context.
640  ///
641  /// This abstract class is meant to be subclassed by clients of \c
642  /// Sema::LookupVisibleDecls(), each of which should override the \c
643  /// FoundDecl() function to process declarations as they are found.
644  class VisibleDeclConsumer {
645  public:
646    /// \brief Destroys the visible declaration consumer.
647    virtual ~VisibleDeclConsumer();
648
649    /// \brief Invoked each time \p Sema::LookupVisibleDecls() finds a
650    /// declaration visible from the current scope or context.
651    ///
652    /// \param ND the declaration found.
653    ///
654    /// \param Hiding a declaration that hides the declaration \p ND,
655    /// or NULL if no such declaration exists.
656    ///
657    /// \param Ctx the original context from which the lookup started.
658    ///
659    /// \param InBaseClass whether this declaration was found in base
660    /// class of the context we searched.
661    virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
662                           bool InBaseClass) = 0;
663  };
664
665/// \brief A class for storing results from argument-dependent lookup.
666class ADLResult {
667private:
668  /// A map from canonical decls to the 'most recent' decl.
669  llvm::DenseMap<NamedDecl*, NamedDecl*> Decls;
670
671public:
672  /// Adds a new ADL candidate to this map.
673  void insert(NamedDecl *D);
674
675  /// Removes any data associated with a given decl.
676  void erase(NamedDecl *D) {
677    Decls.erase(cast<NamedDecl>(D->getCanonicalDecl()));
678  }
679
680  class iterator {
681    typedef llvm::DenseMap<NamedDecl*,NamedDecl*>::iterator inner_iterator;
682    inner_iterator iter;
683
684    friend class ADLResult;
685    iterator(const inner_iterator &iter) : iter(iter) {}
686  public:
687    iterator() {}
688
689    iterator &operator++() { ++iter; return *this; }
690    iterator operator++(int) { return iterator(iter++); }
691
692    NamedDecl *operator*() const { return iter->second; }
693
694    bool operator==(const iterator &other) const { return iter == other.iter; }
695    bool operator!=(const iterator &other) const { return iter != other.iter; }
696  };
697
698  iterator begin() { return iterator(Decls.begin()); }
699  iterator end() { return iterator(Decls.end()); }
700};
701
702}
703
704#endif
705