blob: 1419ceb4b660e8bb4efdcffc88c825efad7cdcbb [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
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 implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor34074322009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6538c932009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2d435302009-12-30 17:04:44 +000030#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000031#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000032#include <vector>
33#include <iterator>
34#include <utility>
35#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000036
37using namespace clang;
38
John McCallf6c8a4e2009-11-10 07:01:13 +000039namespace {
40 class UnqualUsingEntry {
41 const DeclContext *Nominated;
42 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000043
John McCallf6c8a4e2009-11-10 07:01:13 +000044 public:
45 UnqualUsingEntry(const DeclContext *Nominated,
46 const DeclContext *CommonAncestor)
47 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
48 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000049
John McCallf6c8a4e2009-11-10 07:01:13 +000050 const DeclContext *getCommonAncestor() const {
51 return CommonAncestor;
52 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000053
John McCallf6c8a4e2009-11-10 07:01:13 +000054 const DeclContext *getNominatedNamespace() const {
55 return Nominated;
56 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 // Sort by the pointer value of the common ancestor.
59 struct Comparator {
60 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
61 return L.getCommonAncestor() < R.getCommonAncestor();
62 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
65 return E.getCommonAncestor() < DC;
66 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000067
John McCallf6c8a4e2009-11-10 07:01:13 +000068 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
69 return DC < E.getCommonAncestor();
70 }
71 };
72 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 /// A collection of using directives, as used by C++ unqualified
75 /// lookup.
76 class UnqualUsingDirectiveSet {
77 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000078
John McCallf6c8a4e2009-11-10 07:01:13 +000079 ListTy list;
80 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 public:
83 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000084
John McCallf6c8a4e2009-11-10 07:01:13 +000085 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
86 // C++ [namespace.udir]p1:
87 // During unqualified name lookup, the names appear as if they
88 // were declared in the nearest enclosing namespace which contains
89 // both the using-directive and the nominated namespace.
90 DeclContext *InnermostFileDC
91 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
92 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +000095 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
96 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
97 visit(Ctx, EffectiveDC);
98 } else {
99 Scope::udir_iterator I = S->using_directives_begin(),
100 End = S->using_directives_end();
101
102 for (; I != End; ++I)
103 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
104 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000105 }
106 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000107
108 // Visits a context and collect all of its using directives
109 // recursively. Treats all using directives as if they were
110 // declared in the context.
111 //
112 // A given context is only every visited once, so it is important
113 // that contexts be visited from the inside out in order to get
114 // the effective DCs right.
115 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
116 if (!visited.insert(DC))
117 return;
118
119 addUsingDirectives(DC, EffectiveDC);
120 }
121
122 // Visits a using directive and collects all of its using
123 // directives recursively. Treats all using directives as if they
124 // were declared in the effective DC.
125 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
126 DeclContext *NS = UD->getNominatedNamespace();
127 if (!visited.insert(NS))
128 return;
129
130 addUsingDirective(UD, EffectiveDC);
131 addUsingDirectives(NS, EffectiveDC);
132 }
133
134 // Adds all the using directives in a context (and those nominated
135 // by its using directives, transitively) as if they appeared in
136 // the given effective context.
137 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
138 llvm::SmallVector<DeclContext*,4> queue;
139 while (true) {
140 DeclContext::udir_iterator I, End;
141 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
142 UsingDirectiveDecl *UD = *I;
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (visited.insert(NS)) {
145 addUsingDirective(UD, EffectiveDC);
146 queue.push_back(NS);
147 }
148 }
149
150 if (queue.empty())
151 return;
152
153 DC = queue.back();
154 queue.pop_back();
155 }
156 }
157
158 // Add a using directive as if it had been declared in the given
159 // context. This helps implement C++ [namespace.udir]p3:
160 // The using-directive is transitive: if a scope contains a
161 // using-directive that nominates a second namespace that itself
162 // contains using-directives, the effect is as if the
163 // using-directives from the second namespace also appeared in
164 // the first.
165 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
166 // Find the common ancestor between the effective context and
167 // the nominated namespace.
168 DeclContext *Common = UD->getNominatedNamespace();
169 while (!Common->Encloses(EffectiveDC))
170 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000171 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000172
173 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
174 }
175
176 void done() {
177 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
178 }
179
180 typedef ListTy::iterator iterator;
181 typedef ListTy::const_iterator const_iterator;
182
183 iterator begin() { return list.begin(); }
184 iterator end() { return list.end(); }
185 const_iterator begin() const { return list.begin(); }
186 const_iterator end() const { return list.end(); }
187
188 std::pair<const_iterator,const_iterator>
189 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000190 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000191 UnqualUsingEntry::Comparator());
192 }
193 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000194}
195
John McCallea305ed2009-12-18 10:40:03 +0000196static bool IsAcceptableIDNS(NamedDecl *D, unsigned IDNS) {
197 return D->isInIdentifierNamespace(IDNS);
198}
199
200static bool IsAcceptableOperatorName(NamedDecl *D, unsigned IDNS) {
201 return D->isInIdentifierNamespace(IDNS) &&
202 !D->getDeclContext()->isRecord();
203}
204
205static bool IsAcceptableNestedNameSpecifierName(NamedDecl *D, unsigned IDNS) {
John McCallc3f09ad2009-12-18 10:48:10 +0000206 // This lookup ignores everything that isn't a type.
207
208 // This is a fast check for the far most common case.
209 if (D->isInIdentifierNamespace(Decl::IDNS_Tag))
210 return true;
211
212 if (isa<UsingShadowDecl>(D))
213 D = cast<UsingShadowDecl>(D)->getTargetDecl();
214
215 return isa<TypeDecl>(D);
John McCallea305ed2009-12-18 10:40:03 +0000216}
217
218static bool IsAcceptableNamespaceName(NamedDecl *D, unsigned IDNS) {
John McCallc3f09ad2009-12-18 10:48:10 +0000219 // We don't need to look through using decls here because
220 // using decls aren't allowed to name namespaces.
221
John McCallea305ed2009-12-18 10:40:03 +0000222 return isa<NamespaceDecl>(D) || isa<NamespaceAliasDecl>(D);
223}
224
225/// Gets the default result filter for the given lookup.
226static inline
227LookupResult::ResultFilter getResultFilter(Sema::LookupNameKind NameKind) {
228 switch (NameKind) {
229 case Sema::LookupOrdinaryName:
230 case Sema::LookupTagName:
231 case Sema::LookupMemberName:
232 case Sema::LookupRedeclarationWithLinkage: // FIXME: check linkage, scoping
233 case Sema::LookupUsingDeclName:
234 case Sema::LookupObjCProtocolName:
235 case Sema::LookupObjCImplementationName:
236 return &IsAcceptableIDNS;
237
238 case Sema::LookupOperatorName:
239 return &IsAcceptableOperatorName;
240
241 case Sema::LookupNestedNameSpecifierName:
242 return &IsAcceptableNestedNameSpecifierName;
243
244 case Sema::LookupNamespaceName:
245 return &IsAcceptableNamespaceName;
246 }
247
248 llvm_unreachable("unkknown lookup kind");
249 return 0;
250}
251
Douglas Gregor889ceb72009-02-03 19:21:40 +0000252// Retrieve the set of identifier namespaces that correspond to a
253// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000254static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
255 bool CPlusPlus,
256 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000257 unsigned IDNS = 0;
258 switch (NameKind) {
259 case Sema::LookupOrdinaryName:
Douglas Gregor94eabf32009-02-04 16:44:47 +0000260 case Sema::LookupOperatorName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000261 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000262 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000263 if (CPlusPlus) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000264 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
John McCallea305ed2009-12-18 10:40:03 +0000265 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
266 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000267 break;
268
269 case Sema::LookupTagName:
270 IDNS = Decl::IDNS_Tag;
John McCallea305ed2009-12-18 10:40:03 +0000271 if (CPlusPlus && Redeclaration)
272 IDNS |= Decl::IDNS_TagFriend;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000273 break;
274
275 case Sema::LookupMemberName:
276 IDNS = Decl::IDNS_Member;
277 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000278 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000279 break;
280
281 case Sema::LookupNestedNameSpecifierName:
282 case Sema::LookupNamespaceName:
283 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
284 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000285
John McCall84d87672009-12-10 09:41:52 +0000286 case Sema::LookupUsingDeclName:
287 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
288 | Decl::IDNS_Member | Decl::IDNS_Using;
289 break;
290
Douglas Gregor79947a22009-04-24 00:11:27 +0000291 case Sema::LookupObjCProtocolName:
292 IDNS = Decl::IDNS_ObjCProtocol;
293 break;
294
295 case Sema::LookupObjCImplementationName:
296 IDNS = Decl::IDNS_ObjCImplementation;
297 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000298 }
299 return IDNS;
300}
301
John McCallea305ed2009-12-18 10:40:03 +0000302void LookupResult::configure() {
303 IDNS = getIDNS(LookupKind,
304 SemaRef.getLangOptions().CPlusPlus,
305 isForRedeclaration());
306 IsAcceptableFn = getResultFilter(LookupKind);
307}
308
John McCall9f3059a2009-10-09 21:13:30 +0000309// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000310void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000311 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000312}
313
John McCall283b9012009-11-22 00:44:51 +0000314/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000315void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000316 unsigned N = Decls.size();
John McCall84d87672009-12-10 09:41:52 +0000317
John McCall9f3059a2009-10-09 21:13:30 +0000318 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000319 if (N == 0) {
320 assert(ResultKind == NotFound);
321 return;
322 }
323
John McCall283b9012009-11-22 00:44:51 +0000324 // If there's a single decl, we need to examine it to decide what
325 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000326 if (N == 1) {
John McCall283b9012009-11-22 00:44:51 +0000327 if (isa<FunctionTemplateDecl>(Decls[0]))
328 ResultKind = FoundOverloaded;
329 else if (isa<UnresolvedUsingValueDecl>(Decls[0]))
John McCalle61f2ba2009-11-18 02:36:19 +0000330 ResultKind = FoundUnresolvedValue;
331 return;
332 }
John McCall9f3059a2009-10-09 21:13:30 +0000333
John McCall6538c932009-10-10 05:48:19 +0000334 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000335 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000336
John McCall9f3059a2009-10-09 21:13:30 +0000337 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
338
339 bool Ambiguous = false;
340 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000341 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000342
343 unsigned UniqueTagIndex = 0;
344
345 unsigned I = 0;
346 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000347 NamedDecl *D = Decls[I]->getUnderlyingDecl();
348 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000349
John McCallf0f1cf02009-11-17 07:50:12 +0000350 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000351 // If it's not unique, pull something off the back (and
352 // continue at this index).
353 Decls[I] = Decls[--N];
John McCall9f3059a2009-10-09 21:13:30 +0000354 } else {
355 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000356
357 if (isa<UnresolvedUsingValueDecl>(D)) {
358 HasUnresolved = true;
359 } else if (isa<TagDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000360 if (HasTag)
361 Ambiguous = true;
362 UniqueTagIndex = I;
363 HasTag = true;
John McCall283b9012009-11-22 00:44:51 +0000364 } else if (isa<FunctionTemplateDecl>(D)) {
365 HasFunction = true;
366 HasFunctionTemplate = true;
367 } else if (isa<FunctionDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000368 HasFunction = true;
369 } else {
370 if (HasNonFunction)
371 Ambiguous = true;
372 HasNonFunction = true;
373 }
374 I++;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000375 }
Mike Stump11289f42009-09-09 15:08:12 +0000376 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000377
John McCall9f3059a2009-10-09 21:13:30 +0000378 // C++ [basic.scope.hiding]p2:
379 // A class name or enumeration name can be hidden by the name of
380 // an object, function, or enumerator declared in the same
381 // scope. If a class or enumeration name and an object, function,
382 // or enumerator are declared in the same scope (in any order)
383 // with the same name, the class or enumeration name is hidden
384 // wherever the object, function, or enumerator name is visible.
385 // But it's still an error if there are distinct tag types found,
386 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000387 if (HideTags && HasTag && !Ambiguous &&
388 (HasFunction || HasNonFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000389 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000390
John McCall9f3059a2009-10-09 21:13:30 +0000391 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000392
John McCall80053822009-12-03 00:58:24 +0000393 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000394 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000395
John McCall9f3059a2009-10-09 21:13:30 +0000396 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000397 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000398 else if (HasUnresolved)
399 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000400 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000401 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000402 else
John McCall27b18f82009-11-17 02:14:36 +0000403 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000404}
405
John McCall5cebab12009-11-18 07:57:50 +0000406void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000407 CXXBasePaths::paths_iterator I, E;
408 DeclContext::lookup_iterator DI, DE;
409 for (I = P.begin(), E = P.end(); I != E; ++I)
410 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
411 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000412}
413
John McCall5cebab12009-11-18 07:57:50 +0000414void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000415 Paths = new CXXBasePaths;
416 Paths->swap(P);
417 addDeclsFromBasePaths(*Paths);
418 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000419 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000420}
421
John McCall5cebab12009-11-18 07:57:50 +0000422void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000423 Paths = new CXXBasePaths;
424 Paths->swap(P);
425 addDeclsFromBasePaths(*Paths);
426 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000427 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000428}
429
John McCall5cebab12009-11-18 07:57:50 +0000430void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000431 Out << Decls.size() << " result(s)";
432 if (isAmbiguous()) Out << ", ambiguous";
433 if (Paths) Out << ", base paths present";
434
435 for (iterator I = begin(), E = end(); I != E; ++I) {
436 Out << "\n";
437 (*I)->print(Out, 2);
438 }
439}
440
441// Adds all qualifying matches for a name within a decl context to the
442// given lookup result. Returns true if any matches were found.
John McCall5cebab12009-11-18 07:57:50 +0000443static bool LookupDirect(LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000444 bool Found = false;
445
John McCallf6c8a4e2009-11-10 07:01:13 +0000446 DeclContext::lookup_const_iterator I, E;
John McCall27b18f82009-11-17 02:14:36 +0000447 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I)
John McCallea305ed2009-12-18 10:40:03 +0000448 if (R.isAcceptableDecl(*I))
John McCall9f3059a2009-10-09 21:13:30 +0000449 R.addDecl(*I), Found = true;
450
451 return Found;
452}
453
John McCallf6c8a4e2009-11-10 07:01:13 +0000454// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000455static bool
John McCall5cebab12009-11-18 07:57:50 +0000456CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCall27b18f82009-11-17 02:14:36 +0000457 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000458
459 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
460
John McCallf6c8a4e2009-11-10 07:01:13 +0000461 // Perform direct name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000462 bool Found = LookupDirect(R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000463
John McCallf6c8a4e2009-11-10 07:01:13 +0000464 // Perform direct name lookup into the namespaces nominated by the
465 // using directives whose common ancestor is this namespace.
466 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
467 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000468
John McCallf6c8a4e2009-11-10 07:01:13 +0000469 for (; UI != UEnd; ++UI)
John McCall27b18f82009-11-17 02:14:36 +0000470 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000471 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000472
473 R.resolveKind();
474
475 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000476}
477
478static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000479 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000480 return Ctx->isFileContext();
481 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000482}
Douglas Gregored8f2882009-01-30 01:04:22 +0000483
Douglas Gregor7f737c02009-09-10 16:57:35 +0000484// Find the next outer declaration context corresponding to this scope.
485static DeclContext *findOuterContext(Scope *S) {
486 for (S = S->getParent(); S; S = S->getParent())
487 if (S->getEntity())
488 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
489
490 return 0;
491}
492
John McCall27b18f82009-11-17 02:14:36 +0000493bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000494 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000495
496 DeclarationName Name = R.getLookupName();
497
Douglas Gregor889ceb72009-02-03 19:21:40 +0000498 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000499 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000500 I = IdResolver.begin(Name),
501 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000502
Douglas Gregor889ceb72009-02-03 19:21:40 +0000503 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000504 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000505 // ...During unqualified name lookup (3.4.1), the names appear as if
506 // they were declared in the nearest enclosing namespace which contains
507 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000508 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000509 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000510 //
511 // For example:
512 // namespace A { int i; }
513 // void foo() {
514 // int i;
515 // {
516 // using namespace A;
517 // ++i; // finds local 'i', A::i appears at global scope
518 // }
519 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000520 //
Douglas Gregor700792c2009-02-05 19:25:20 +0000521 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000522 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000523 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000524 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000525 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000526 Found = true;
527 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000528 }
529 }
John McCall9f3059a2009-10-09 21:13:30 +0000530 if (Found) {
531 R.resolveKind();
532 return true;
533 }
534
Douglas Gregor700792c2009-02-05 19:25:20 +0000535 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregor7f737c02009-09-10 16:57:35 +0000536 DeclContext *OuterCtx = findOuterContext(S);
537 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
538 Ctx = Ctx->getLookupParent()) {
Douglas Gregora64c1e52009-12-08 15:38:36 +0000539 // We do not directly look into function or method contexts
540 // (since all local variables are found via the identifier
541 // changes) or in transparent contexts (since those entities
542 // will be found in the nearest enclosing non-transparent
543 // context).
544 if (Ctx->isFunctionOrMethod() || Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000545 continue;
546
547 // Perform qualified name lookup into this context.
548 // FIXME: In some cases, we know that every name that could be found by
549 // this qualified name lookup will also be on the identifier chain. For
550 // example, inside a class without any base classes, we never need to
551 // perform qualified lookup because all of the members are on top of the
552 // identifier chain.
John McCall27b18f82009-11-17 02:14:36 +0000553 if (LookupQualifiedName(R, Ctx))
John McCall9f3059a2009-10-09 21:13:30 +0000554 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000555 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000556 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000557 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000558
John McCallf6c8a4e2009-11-10 07:01:13 +0000559 // Stop if we ran out of scopes.
560 // FIXME: This really, really shouldn't be happening.
561 if (!S) return false;
562
Douglas Gregor700792c2009-02-05 19:25:20 +0000563 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000564 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000565 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000566 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
567 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000568
John McCallf6c8a4e2009-11-10 07:01:13 +0000569 UnqualUsingDirectiveSet UDirs;
570 UDirs.visitScopeChain(Initial, S);
571 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000572
Douglas Gregor700792c2009-02-05 19:25:20 +0000573 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000574 // Unqualified name lookup in C++ requires looking into scopes
575 // that aren't strictly lexical, and therefore we walk through the
576 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000577
Douglas Gregor889ceb72009-02-03 19:21:40 +0000578 for (; S; S = S->getParent()) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000579 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregorf2270432009-08-24 18:55:03 +0000580 if (Ctx->isTransparentContext())
581 continue;
582
Douglas Gregor700792c2009-02-05 19:25:20 +0000583 assert(Ctx && Ctx->isFileContext() &&
584 "We should have been looking only at file context here already.");
Douglas Gregor889ceb72009-02-03 19:21:40 +0000585
586 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000587 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000588 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000589 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000590 // We found something. Look for anything else in our scope
591 // with this same name and in an acceptable identifier
592 // namespace, so that we can construct an overload set if we
593 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000594 Found = true;
595 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000596 }
597 }
598
Douglas Gregor700792c2009-02-05 19:25:20 +0000599 // Look into context considering using-directives.
John McCall27b18f82009-11-17 02:14:36 +0000600 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
John McCall9f3059a2009-10-09 21:13:30 +0000601 Found = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000602
John McCall9f3059a2009-10-09 21:13:30 +0000603 if (Found) {
604 R.resolveKind();
605 return true;
606 }
607
John McCall27b18f82009-11-17 02:14:36 +0000608 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000609 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000610 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000611
John McCall9f3059a2009-10-09 21:13:30 +0000612 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000613}
614
Douglas Gregor34074322009-01-14 22:20:51 +0000615/// @brief Perform unqualified name lookup starting from a given
616/// scope.
617///
618/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
619/// used to find names within the current scope. For example, 'x' in
620/// @code
621/// int x;
622/// int f() {
623/// return x; // unqualified name look finds 'x' in the global scope
624/// }
625/// @endcode
626///
627/// Different lookup criteria can find different names. For example, a
628/// particular scope can have both a struct and a function of the same
629/// name, and each can be found by certain lookup criteria. For more
630/// information about lookup criteria, see the documentation for the
631/// class LookupCriteria.
632///
633/// @param S The scope from which unqualified name lookup will
634/// begin. If the lookup criteria permits, name lookup may also search
635/// in the parent scopes.
636///
637/// @param Name The name of the entity that we are searching for.
638///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000639/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000640/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000641/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000642///
643/// @returns The result of name lookup, which includes zero or more
644/// declarations and possibly additional information used to diagnose
645/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000646bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
647 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +0000648 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000649
John McCall27b18f82009-11-17 02:14:36 +0000650 LookupNameKind NameKind = R.getLookupKind();
651
Douglas Gregor34074322009-01-14 22:20:51 +0000652 if (!getLangOptions().CPlusPlus) {
653 // Unqualified name lookup in C/Objective-C is purely lexical, so
654 // search in the declarations attached to the name.
655
John McCallea305ed2009-12-18 10:40:03 +0000656 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000657 // Find the nearest non-transparent declaration scope.
658 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000659 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000660 static_cast<DeclContext *>(S->getEntity())
661 ->isTransparentContext()))
662 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +0000663 }
664
John McCallea305ed2009-12-18 10:40:03 +0000665 unsigned IDNS = R.getIdentifierNamespace();
666
Douglas Gregor34074322009-01-14 22:20:51 +0000667 // Scan up the scope chain looking for a decl that matches this
668 // identifier that is in the appropriate namespace. This search
669 // should not take long, as shadowing of names is uncommon, and
670 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000671 bool LeftStartingScope = false;
672
Douglas Gregored8f2882009-01-30 01:04:22 +0000673 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000674 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000675 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000676 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000677 if (NameKind == LookupRedeclarationWithLinkage) {
678 // Determine whether this (or a previous) declaration is
679 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000680 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000681 LeftStartingScope = true;
682
683 // If we found something outside of our starting scope that
684 // does not have linkage, skip it.
685 if (LeftStartingScope && !((*I)->hasLinkage()))
686 continue;
687 }
688
John McCall9f3059a2009-10-09 21:13:30 +0000689 R.addDecl(*I);
690
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000691 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000692 // If this declaration has the "overloadable" attribute, we
693 // might have a set of overloaded functions.
694
695 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000696 while (!(S->getFlags() & Scope::DeclScope) ||
697 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000698 S = S->getParent();
699
700 // Find the last declaration in this scope (with the same
701 // name, naturally).
702 IdentifierResolver::iterator LastI = I;
703 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000704 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000705 break;
John McCall9f3059a2009-10-09 21:13:30 +0000706 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000707 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000708 }
709
John McCall9f3059a2009-10-09 21:13:30 +0000710 R.resolveKind();
711
712 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000713 }
Douglas Gregor34074322009-01-14 22:20:51 +0000714 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000715 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000716 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +0000717 return true;
Douglas Gregor34074322009-01-14 22:20:51 +0000718 }
719
720 // If we didn't find a use of this identifier, and if the identifier
721 // corresponds to a compiler builtin, create the decl object for the builtin
722 // now, injecting it into translation unit scope, and return it.
Mike Stump11289f42009-09-09 15:08:12 +0000723 if (NameKind == LookupOrdinaryName ||
Douglas Gregoreddf4332009-02-24 20:03:32 +0000724 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor34074322009-01-14 22:20:51 +0000725 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000726 if (II && AllowBuiltinCreation) {
Douglas Gregor34074322009-01-14 22:20:51 +0000727 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000728 if (unsigned BuiltinID = II->getBuiltinID()) {
729 // In C++, we don't have any predefined library functions like
730 // 'malloc'. Instead, we'll just error.
Mike Stump11289f42009-09-09 15:08:12 +0000731 if (getLangOptions().CPlusPlus &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000732 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCall9f3059a2009-10-09 21:13:30 +0000733 return false;
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000734
John McCall9f3059a2009-10-09 21:13:30 +0000735 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCall27b18f82009-11-17 02:14:36 +0000736 S, R.isForRedeclaration(),
737 R.getNameLoc());
John McCall9f3059a2009-10-09 21:13:30 +0000738 if (D) R.addDecl(D);
739 return (D != NULL);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000740 }
Douglas Gregor34074322009-01-14 22:20:51 +0000741 }
Douglas Gregor34074322009-01-14 22:20:51 +0000742 }
John McCall9f3059a2009-10-09 21:13:30 +0000743 return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000744}
745
John McCall6538c932009-10-10 05:48:19 +0000746/// @brief Perform qualified name lookup in the namespaces nominated by
747/// using directives by the given context.
748///
749/// C++98 [namespace.qual]p2:
750/// Given X::m (where X is a user-declared namespace), or given ::m
751/// (where X is the global namespace), let S be the set of all
752/// declarations of m in X and in the transitive closure of all
753/// namespaces nominated by using-directives in X and its used
754/// namespaces, except that using-directives are ignored in any
755/// namespace, including X, directly containing one or more
756/// declarations of m. No namespace is searched more than once in
757/// the lookup of a name. If S is the empty set, the program is
758/// ill-formed. Otherwise, if S has exactly one member, or if the
759/// context of the reference is a using-declaration
760/// (namespace.udecl), S is the required set of declarations of
761/// m. Otherwise if the use of m is not one that allows a unique
762/// declaration to be chosen from S, the program is ill-formed.
763/// C++98 [namespace.qual]p5:
764/// During the lookup of a qualified namespace member name, if the
765/// lookup finds more than one declaration of the member, and if one
766/// declaration introduces a class name or enumeration name and the
767/// other declarations either introduce the same object, the same
768/// enumerator or a set of functions, the non-type name hides the
769/// class or enumeration name if and only if the declarations are
770/// from the same namespace; otherwise (the declarations are from
771/// different namespaces), the program is ill-formed.
John McCall5cebab12009-11-18 07:57:50 +0000772static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +0000773 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +0000774 assert(StartDC->isFileContext() && "start context is not a file context");
775
776 DeclContext::udir_iterator I = StartDC->using_directives_begin();
777 DeclContext::udir_iterator E = StartDC->using_directives_end();
778
779 if (I == E) return false;
780
781 // We have at least added all these contexts to the queue.
782 llvm::DenseSet<DeclContext*> Visited;
783 Visited.insert(StartDC);
784
785 // We have not yet looked into these namespaces, much less added
786 // their "using-children" to the queue.
787 llvm::SmallVector<NamespaceDecl*, 8> Queue;
788
789 // We have already looked into the initial namespace; seed the queue
790 // with its using-children.
791 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +0000792 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +0000793 if (Visited.insert(ND).second)
794 Queue.push_back(ND);
795 }
796
797 // The easiest way to implement the restriction in [namespace.qual]p5
798 // is to check whether any of the individual results found a tag
799 // and, if so, to declare an ambiguity if the final result is not
800 // a tag.
801 bool FoundTag = false;
802 bool FoundNonTag = false;
803
John McCall5cebab12009-11-18 07:57:50 +0000804 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +0000805
806 bool Found = false;
807 while (!Queue.empty()) {
808 NamespaceDecl *ND = Queue.back();
809 Queue.pop_back();
810
811 // We go through some convolutions here to avoid copying results
812 // between LookupResults.
813 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +0000814 LookupResult &DirectR = UseLocal ? LocalR : R;
John McCall27b18f82009-11-17 02:14:36 +0000815 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +0000816
817 if (FoundDirect) {
818 // First do any local hiding.
819 DirectR.resolveKind();
820
821 // If the local result is a tag, remember that.
822 if (DirectR.isSingleTagDecl())
823 FoundTag = true;
824 else
825 FoundNonTag = true;
826
827 // Append the local results to the total results if necessary.
828 if (UseLocal) {
829 R.addAllDecls(LocalR);
830 LocalR.clear();
831 }
832 }
833
834 // If we find names in this namespace, ignore its using directives.
835 if (FoundDirect) {
836 Found = true;
837 continue;
838 }
839
840 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
841 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
842 if (Visited.insert(Nom).second)
843 Queue.push_back(Nom);
844 }
845 }
846
847 if (Found) {
848 if (FoundTag && FoundNonTag)
849 R.setAmbiguousQualifiedTagHiding();
850 else
851 R.resolveKind();
852 }
853
854 return Found;
855}
856
Douglas Gregor34074322009-01-14 22:20:51 +0000857/// @brief Perform qualified name lookup into a given context.
858///
859/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
860/// names when the context of those names is explicit specified, e.g.,
861/// "std::vector" or "x->member".
862///
863/// Different lookup criteria can find different names. For example, a
864/// particular scope can have both a struct and a function of the same
865/// name, and each can be found by certain lookup criteria. For more
866/// information about lookup criteria, see the documentation for the
867/// class LookupCriteria.
868///
869/// @param LookupCtx The context in which qualified name lookup will
870/// search. If the lookup criteria permits, name lookup may also search
871/// in the parent contexts or (for C++ classes) base classes.
872///
873/// @param Name The name of the entity that we are searching for.
874///
875/// @param Criteria The criteria that this routine will use to
876/// determine which names are visible and which names will be
877/// found. Note that name lookup will find a name that is visible by
878/// the given criteria, but the entity itself may not be semantically
879/// correct or even the kind of entity expected based on the
880/// lookup. For example, searching for a nested-name-specifier name
881/// might result in an EnumDecl, which is visible but is not permitted
882/// as a nested-name-specifier in C++03.
883///
884/// @returns The result of name lookup, which includes zero or more
885/// declarations and possibly additional information used to diagnose
886/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000887bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx) {
Douglas Gregor34074322009-01-14 22:20:51 +0000888 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +0000889
John McCall27b18f82009-11-17 02:14:36 +0000890 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +0000891 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000892
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000893 // Make sure that the declaration context is complete.
894 assert((!isa<TagDecl>(LookupCtx) ||
895 LookupCtx->isDependentContext() ||
896 cast<TagDecl>(LookupCtx)->isDefinition() ||
897 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
898 ->isBeingDefined()) &&
899 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +0000900
Douglas Gregor34074322009-01-14 22:20:51 +0000901 // Perform qualified name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000902 if (LookupDirect(R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +0000903 R.resolveKind();
904 return true;
905 }
Douglas Gregor34074322009-01-14 22:20:51 +0000906
John McCall6538c932009-10-10 05:48:19 +0000907 // Don't descend into implied contexts for redeclarations.
908 // C++98 [namespace.qual]p6:
909 // In a declaration for a namespace member in which the
910 // declarator-id is a qualified-id, given that the qualified-id
911 // for the namespace member has the form
912 // nested-name-specifier unqualified-id
913 // the unqualified-id shall name a member of the namespace
914 // designated by the nested-name-specifier.
915 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +0000916 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +0000917 return false;
918
John McCall27b18f82009-11-17 02:14:36 +0000919 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +0000920 if (LookupCtx->isFileContext())
John McCall27b18f82009-11-17 02:14:36 +0000921 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +0000922
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000923 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +0000924 // classes, we're done.
John McCall6538c932009-10-10 05:48:19 +0000925 if (!isa<CXXRecordDecl>(LookupCtx))
John McCall9f3059a2009-10-09 21:13:30 +0000926 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000927
928 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +0000929 CXXRecordDecl *LookupRec = cast<CXXRecordDecl>(LookupCtx);
930 CXXBasePaths Paths;
931 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000932
933 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +0000934 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +0000935 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000936 case LookupOrdinaryName:
937 case LookupMemberName:
938 case LookupRedeclarationWithLinkage:
939 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
940 break;
941
942 case LookupTagName:
943 BaseCallback = &CXXRecordDecl::FindTagMember;
944 break;
John McCall84d87672009-12-10 09:41:52 +0000945
946 case LookupUsingDeclName:
947 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +0000948
949 case LookupOperatorName:
950 case LookupNamespaceName:
951 case LookupObjCProtocolName:
952 case LookupObjCImplementationName:
Douglas Gregor36d1b142009-10-06 17:59:45 +0000953 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +0000954 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000955
956 case LookupNestedNameSpecifierName:
957 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
958 break;
959 }
960
John McCall27b18f82009-11-17 02:14:36 +0000961 if (!LookupRec->lookupInBases(BaseCallback,
962 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +0000963 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000964
965 // C++ [class.member.lookup]p2:
966 // [...] If the resulting set of declarations are not all from
967 // sub-objects of the same type, or the set has a nonstatic member
968 // and includes members from distinct sub-objects, there is an
969 // ambiguity and the program is ill-formed. Otherwise that set is
970 // the result of the lookup.
971 // FIXME: support using declarations!
972 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +0000973 int SubobjectNumber = 0;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000974 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000975 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000976 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000977
978 // Determine whether we're looking at a distinct sub-object or not.
979 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +0000980 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000981 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
982 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +0000983 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000984 != Context.getCanonicalType(PathElement.Base->getType())) {
985 // We found members of the given name in two subobjects of
986 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +0000987 R.setAmbiguousBaseSubobjectTypes(Paths);
988 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000989 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
990 // We have a different subobject of the same type.
991
992 // C++ [class.member.lookup]p5:
993 // A static member, a nested type or an enumerator defined in
994 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +0000995 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000996 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000997 if (isa<VarDecl>(FirstDecl) ||
998 isa<TypeDecl>(FirstDecl) ||
999 isa<EnumConstantDecl>(FirstDecl))
1000 continue;
1001
1002 if (isa<CXXMethodDecl>(FirstDecl)) {
1003 // Determine whether all of the methods are static.
1004 bool AllMethodsAreStatic = true;
1005 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1006 Func != Path->Decls.second; ++Func) {
1007 if (!isa<CXXMethodDecl>(*Func)) {
1008 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1009 break;
1010 }
1011
1012 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1013 AllMethodsAreStatic = false;
1014 break;
1015 }
1016 }
1017
1018 if (AllMethodsAreStatic)
1019 continue;
1020 }
1021
1022 // We have found a nonstatic member name in multiple, distinct
1023 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001024 R.setAmbiguousBaseSubobjects(Paths);
1025 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001026 }
1027 }
1028
1029 // Lookup in a base class succeeded; return these results.
1030
John McCall9f3059a2009-10-09 21:13:30 +00001031 DeclContext::lookup_iterator I, E;
1032 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I)
1033 R.addDecl(*I);
1034 R.resolveKind();
1035 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001036}
1037
1038/// @brief Performs name lookup for a name that was parsed in the
1039/// source code, and may contain a C++ scope specifier.
1040///
1041/// This routine is a convenience routine meant to be called from
1042/// contexts that receive a name and an optional C++ scope specifier
1043/// (e.g., "N::M::x"). It will then perform either qualified or
1044/// unqualified name lookup (with LookupQualifiedName or LookupName,
1045/// respectively) on the given name and return those results.
1046///
1047/// @param S The scope from which unqualified name lookup will
1048/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001049///
Douglas Gregore861bac2009-08-25 22:51:20 +00001050/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001051///
1052/// @param Name The name of the entity that name lookup will
1053/// search for.
1054///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001055/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001056/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001057/// C library functions (like "malloc") are implicitly declared.
1058///
Douglas Gregore861bac2009-08-25 22:51:20 +00001059/// @param EnteringContext Indicates whether we are going to enter the
1060/// context of the scope-specifier SS (if present).
1061///
John McCall9f3059a2009-10-09 21:13:30 +00001062/// @returns True if any decls were found (but possibly ambiguous)
1063bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001064 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001065 if (SS && SS->isInvalid()) {
1066 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001067 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001068 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001069 }
Mike Stump11289f42009-09-09 15:08:12 +00001070
Douglas Gregore861bac2009-08-25 22:51:20 +00001071 if (SS && SS->isSet()) {
1072 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001073 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001074 // contex, and will perform name lookup in that context.
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001075 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCall9f3059a2009-10-09 21:13:30 +00001076 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001077
John McCall27b18f82009-11-17 02:14:36 +00001078 R.setContextRange(SS->getRange());
1079
1080 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001081 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001082
Douglas Gregore861bac2009-08-25 22:51:20 +00001083 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001084 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001085 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001086 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001087 }
1088
Mike Stump11289f42009-09-09 15:08:12 +00001089 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001090 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001091}
1092
Douglas Gregor889ceb72009-02-03 19:21:40 +00001093
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001094/// @brief Produce a diagnostic describing the ambiguity that resulted
1095/// from name lookup.
1096///
1097/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001098///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001099/// @param Name The name of the entity that name lookup was
1100/// searching for.
1101///
1102/// @param NameLoc The location of the name within the source code.
1103///
1104/// @param LookupRange A source range that provides more
1105/// source-location information concerning the lookup itself. For
1106/// example, this range might highlight a nested-name-specifier that
1107/// precedes the name.
1108///
1109/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001110bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001111 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1112
John McCall27b18f82009-11-17 02:14:36 +00001113 DeclarationName Name = Result.getLookupName();
1114 SourceLocation NameLoc = Result.getNameLoc();
1115 SourceRange LookupRange = Result.getContextRange();
1116
John McCall6538c932009-10-10 05:48:19 +00001117 switch (Result.getAmbiguityKind()) {
1118 case LookupResult::AmbiguousBaseSubobjects: {
1119 CXXBasePaths *Paths = Result.getBasePaths();
1120 QualType SubobjectType = Paths->front().back().Base->getType();
1121 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1122 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1123 << LookupRange;
1124
1125 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1126 while (isa<CXXMethodDecl>(*Found) &&
1127 cast<CXXMethodDecl>(*Found)->isStatic())
1128 ++Found;
1129
1130 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1131
1132 return true;
1133 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001134
John McCall6538c932009-10-10 05:48:19 +00001135 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001136 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1137 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001138
1139 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001140 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001141 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1142 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001143 Path != PathEnd; ++Path) {
1144 Decl *D = *Path->Decls.first;
1145 if (DeclsPrinted.insert(D).second)
1146 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1147 }
1148
Douglas Gregor1c846b02009-01-16 00:38:09 +00001149 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001150 }
1151
John McCall6538c932009-10-10 05:48:19 +00001152 case LookupResult::AmbiguousTagHiding: {
1153 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001154
John McCall6538c932009-10-10 05:48:19 +00001155 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1156
1157 LookupResult::iterator DI, DE = Result.end();
1158 for (DI = Result.begin(); DI != DE; ++DI)
1159 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1160 TagDecls.insert(TD);
1161 Diag(TD->getLocation(), diag::note_hidden_tag);
1162 }
1163
1164 for (DI = Result.begin(); DI != DE; ++DI)
1165 if (!isa<TagDecl>(*DI))
1166 Diag((*DI)->getLocation(), diag::note_hiding_object);
1167
1168 // For recovery purposes, go ahead and implement the hiding.
1169 Result.hideDecls(TagDecls);
1170
1171 return true;
1172 }
1173
1174 case LookupResult::AmbiguousReference: {
1175 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001176
John McCall6538c932009-10-10 05:48:19 +00001177 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1178 for (; DI != DE; ++DI)
1179 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001180
John McCall6538c932009-10-10 05:48:19 +00001181 return true;
1182 }
1183 }
1184
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001185 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001186 return true;
1187}
Douglas Gregore254f902009-02-04 00:32:51 +00001188
Mike Stump11289f42009-09-09 15:08:12 +00001189static void
1190addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001191 ASTContext &Context,
1192 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001193 Sema::AssociatedClassSet &AssociatedClasses);
1194
1195static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1196 DeclContext *Ctx) {
1197 if (Ctx->isFileContext())
1198 Namespaces.insert(Ctx);
1199}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001200
Mike Stump11289f42009-09-09 15:08:12 +00001201// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001202// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001203static void
1204addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001205 ASTContext &Context,
1206 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001207 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001208 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001209 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001210 switch (Arg.getKind()) {
1211 case TemplateArgument::Null:
1212 break;
Mike Stump11289f42009-09-09 15:08:12 +00001213
Douglas Gregor197e5f72009-07-08 07:51:57 +00001214 case TemplateArgument::Type:
1215 // [...] the namespaces and classes associated with the types of the
1216 // template arguments provided for template type parameters (excluding
1217 // template template parameters)
1218 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1219 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001220 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001221 break;
Mike Stump11289f42009-09-09 15:08:12 +00001222
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001223 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001224 // [...] the namespaces in which any template template arguments are
1225 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001226 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001227 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001228 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001229 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001230 DeclContext *Ctx = ClassTemplate->getDeclContext();
1231 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1232 AssociatedClasses.insert(EnclosingClass);
1233 // Add the associated namespace for this class.
1234 while (Ctx->isRecord())
1235 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001236 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001237 }
1238 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001239 }
1240
1241 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001242 case TemplateArgument::Integral:
1243 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001244 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001245 // associated namespaces. ]
1246 break;
Mike Stump11289f42009-09-09 15:08:12 +00001247
Douglas Gregor197e5f72009-07-08 07:51:57 +00001248 case TemplateArgument::Pack:
1249 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1250 PEnd = Arg.pack_end();
1251 P != PEnd; ++P)
1252 addAssociatedClassesAndNamespaces(*P, Context,
1253 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001254 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001255 break;
1256 }
1257}
1258
Douglas Gregore254f902009-02-04 00:32:51 +00001259// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001260// argument-dependent lookup with an argument of class type
1261// (C++ [basic.lookup.koenig]p2).
1262static void
1263addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregore254f902009-02-04 00:32:51 +00001264 ASTContext &Context,
1265 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001266 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001267 // C++ [basic.lookup.koenig]p2:
1268 // [...]
1269 // -- If T is a class type (including unions), its associated
1270 // classes are: the class itself; the class of which it is a
1271 // member, if any; and its direct and indirect base
1272 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001273 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001274
1275 // Add the class of which it is a member, if any.
1276 DeclContext *Ctx = Class->getDeclContext();
1277 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1278 AssociatedClasses.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001279 // Add the associated namespace for this class.
1280 while (Ctx->isRecord())
1281 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001282 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001283
Douglas Gregore254f902009-02-04 00:32:51 +00001284 // Add the class itself. If we've already seen this class, we don't
1285 // need to visit base classes.
1286 if (!AssociatedClasses.insert(Class))
1287 return;
1288
Mike Stump11289f42009-09-09 15:08:12 +00001289 // -- If T is a template-id, its associated namespaces and classes are
1290 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001291 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001292 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001293 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001294 // namespaces in which any template template arguments are defined; and
1295 // the classes in which any member templates used as template template
1296 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001297 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001298 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001299 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1300 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1301 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1302 AssociatedClasses.insert(EnclosingClass);
1303 // Add the associated namespace for this class.
1304 while (Ctx->isRecord())
1305 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001306 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001307
Douglas Gregor197e5f72009-07-08 07:51:57 +00001308 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1309 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1310 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1311 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001312 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001313 }
Mike Stump11289f42009-09-09 15:08:12 +00001314
Douglas Gregore254f902009-02-04 00:32:51 +00001315 // Add direct and indirect base classes along with their associated
1316 // namespaces.
1317 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1318 Bases.push_back(Class);
1319 while (!Bases.empty()) {
1320 // Pop this class off the stack.
1321 Class = Bases.back();
1322 Bases.pop_back();
1323
1324 // Visit the base classes.
1325 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1326 BaseEnd = Class->bases_end();
1327 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001328 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001329 // In dependent contexts, we do ADL twice, and the first time around,
1330 // the base type might be a dependent TemplateSpecializationType, or a
1331 // TemplateTypeParmType. If that happens, simply ignore it.
1332 // FIXME: If we want to support export, we probably need to add the
1333 // namespace of the template in a TemplateSpecializationType, or even
1334 // the classes and namespaces of known non-dependent arguments.
1335 if (!BaseType)
1336 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001337 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1338 if (AssociatedClasses.insert(BaseDecl)) {
1339 // Find the associated namespace for this base class.
1340 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1341 while (BaseCtx->isRecord())
1342 BaseCtx = BaseCtx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001343 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001344
1345 // Make sure we visit the bases of this base class.
1346 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1347 Bases.push_back(BaseDecl);
1348 }
1349 }
1350 }
1351}
1352
1353// \brief Add the associated classes and namespaces for
1354// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001355// (C++ [basic.lookup.koenig]p2).
1356static void
1357addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregore254f902009-02-04 00:32:51 +00001358 ASTContext &Context,
1359 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001360 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001361 // C++ [basic.lookup.koenig]p2:
1362 //
1363 // For each argument type T in the function call, there is a set
1364 // of zero or more associated namespaces and a set of zero or more
1365 // associated classes to be considered. The sets of namespaces and
1366 // classes is determined entirely by the types of the function
1367 // arguments (and the namespace of any template template
1368 // argument). Typedef names and using-declarations used to specify
1369 // the types do not contribute to this set. The sets of namespaces
1370 // and classes are determined in the following way:
1371 T = Context.getCanonicalType(T).getUnqualifiedType();
1372
1373 // -- If T is a pointer to U or an array of U, its associated
Mike Stump11289f42009-09-09 15:08:12 +00001374 // namespaces and classes are those associated with U.
Douglas Gregore254f902009-02-04 00:32:51 +00001375 //
1376 // We handle this by unwrapping pointer and array types immediately,
1377 // to avoid unnecessary recursion.
1378 while (true) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001379 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001380 T = Ptr->getPointeeType();
1381 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1382 T = Ptr->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001383 else
Douglas Gregore254f902009-02-04 00:32:51 +00001384 break;
1385 }
1386
1387 // -- If T is a fundamental type, its associated sets of
1388 // namespaces and classes are both empty.
John McCall9dd450b2009-09-21 23:43:11 +00001389 if (T->getAs<BuiltinType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001390 return;
1391
1392 // -- If T is a class type (including unions), its associated
1393 // classes are: the class itself; the class of which it is a
1394 // member, if any; and its direct and indirect base
1395 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001396 // which its associated classes are defined.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001397 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump11289f42009-09-09 15:08:12 +00001398 if (CXXRecordDecl *ClassDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001399 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001400 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1401 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001402 AssociatedClasses);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001403 return;
1404 }
Douglas Gregore254f902009-02-04 00:32:51 +00001405
1406 // -- If T is an enumeration type, its associated namespace is
1407 // the namespace in which it is defined. If it is class
1408 // member, its associated class is the member’s class; else
Mike Stump11289f42009-09-09 15:08:12 +00001409 // it has no associated class.
John McCall9dd450b2009-09-21 23:43:11 +00001410 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001411 EnumDecl *Enum = EnumT->getDecl();
1412
1413 DeclContext *Ctx = Enum->getDeclContext();
1414 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1415 AssociatedClasses.insert(EnclosingClass);
1416
1417 // Add the associated namespace for this class.
1418 while (Ctx->isRecord())
1419 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001420 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001421
1422 return;
1423 }
1424
1425 // -- If T is a function type, its associated namespaces and
1426 // classes are those associated with the function parameter
1427 // types and those associated with the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001428 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001429 // Return type
John McCall9dd450b2009-09-21 23:43:11 +00001430 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregore254f902009-02-04 00:32:51 +00001431 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001432 AssociatedNamespaces, AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001433
John McCall9dd450b2009-09-21 23:43:11 +00001434 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregore254f902009-02-04 00:32:51 +00001435 if (!Proto)
1436 return;
1437
1438 // Argument types
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001439 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001440 ArgEnd = Proto->arg_type_end();
Douglas Gregore254f902009-02-04 00:32:51 +00001441 Arg != ArgEnd; ++Arg)
1442 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallc7e8e792009-08-07 22:18:02 +00001443 AssociatedNamespaces, AssociatedClasses);
Mike Stump11289f42009-09-09 15:08:12 +00001444
Douglas Gregore254f902009-02-04 00:32:51 +00001445 return;
1446 }
1447
1448 // -- If T is a pointer to a member function of a class X, its
1449 // associated namespaces and classes are those associated
1450 // with the function parameter types and return type,
Mike Stump11289f42009-09-09 15:08:12 +00001451 // together with those associated with X.
Douglas Gregore254f902009-02-04 00:32:51 +00001452 //
1453 // -- If T is a pointer to a data member of class X, its
1454 // associated namespaces and classes are those associated
1455 // with the member type together with those associated with
Mike Stump11289f42009-09-09 15:08:12 +00001456 // X.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001457 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001458 // Handle the type that the pointer to member points to.
1459 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1460 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001461 AssociatedNamespaces,
1462 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001463
1464 // Handle the class type into which this points.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001465 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001466 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1467 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001468 AssociatedNamespaces,
1469 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001470
1471 return;
1472 }
1473
1474 // FIXME: What about block pointers?
1475 // FIXME: What about Objective-C message sends?
1476}
1477
1478/// \brief Find the associated classes and namespaces for
1479/// argument-dependent lookup for a call with the given set of
1480/// arguments.
1481///
1482/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001483/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001484/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001485void
Douglas Gregore254f902009-02-04 00:32:51 +00001486Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1487 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001488 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001489 AssociatedNamespaces.clear();
1490 AssociatedClasses.clear();
1491
1492 // C++ [basic.lookup.koenig]p2:
1493 // For each argument type T in the function call, there is a set
1494 // of zero or more associated namespaces and a set of zero or more
1495 // associated classes to be considered. The sets of namespaces and
1496 // classes is determined entirely by the types of the function
1497 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001498 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001499 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1500 Expr *Arg = Args[ArgIdx];
1501
1502 if (Arg->getType() != Context.OverloadTy) {
1503 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001504 AssociatedNamespaces,
1505 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001506 continue;
1507 }
1508
1509 // [...] In addition, if the argument is the name or address of a
1510 // set of overloaded functions and/or function templates, its
1511 // associated classes and namespaces are the union of those
1512 // associated with each of the members of the set: the namespace
1513 // in which the function or function template is defined and the
1514 // classes and namespaces associated with its (non-dependent)
1515 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001516 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001517 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1518 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1519 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001520
John McCalld14a8642009-11-21 08:51:07 +00001521 // TODO: avoid the copies. This should be easy when the cases
1522 // share a storage implementation.
1523 llvm::SmallVector<NamedDecl*, 8> Functions;
1524
1525 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1526 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00001527 else
Douglas Gregore254f902009-02-04 00:32:51 +00001528 continue;
1529
John McCalld14a8642009-11-21 08:51:07 +00001530 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1531 E = Functions.end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001532 // Look through any using declarations to find the underlying function.
1533 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001534
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001535 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1536 if (!FDecl)
1537 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001538
1539 // Add the classes and namespaces associated with the parameter
1540 // types and return type of this function.
1541 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001542 AssociatedNamespaces,
1543 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001544 }
1545 }
1546}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001547
1548/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1549/// an acceptable non-member overloaded operator for a call whose
1550/// arguments have types T1 (and, if non-empty, T2). This routine
1551/// implements the check in C++ [over.match.oper]p3b2 concerning
1552/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001553static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001554IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1555 QualType T1, QualType T2,
1556 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001557 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1558 return true;
1559
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001560 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1561 return true;
1562
John McCall9dd450b2009-09-21 23:43:11 +00001563 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001564 if (Proto->getNumArgs() < 1)
1565 return false;
1566
1567 if (T1->isEnumeralType()) {
1568 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001569 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001570 return true;
1571 }
1572
1573 if (Proto->getNumArgs() < 2)
1574 return false;
1575
1576 if (!T2.isNull() && T2->isEnumeralType()) {
1577 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001578 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001579 return true;
1580 }
1581
1582 return false;
1583}
1584
John McCall5cebab12009-11-18 07:57:50 +00001585NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1586 LookupNameKind NameKind,
1587 RedeclarationKind Redecl) {
1588 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1589 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00001590 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00001591}
1592
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001593/// \brief Find the protocol with the given name, if any.
1594ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001595 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001596 return cast_or_null<ObjCProtocolDecl>(D);
1597}
1598
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001599void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001600 QualType T1, QualType T2,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001601 FunctionSet &Functions) {
1602 // C++ [over.match.oper]p3:
1603 // -- The set of non-member candidates is the result of the
1604 // unqualified lookup of operator@ in the context of the
1605 // expression according to the usual rules for name lookup in
1606 // unqualified function calls (3.4.2) except that all member
1607 // functions are ignored. However, if no operand has a class
1608 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001609 // that have a first parameter of type T1 or "reference to
1610 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001611 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001612 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001613 // when T2 is an enumeration type, are candidate functions.
1614 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00001615 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1616 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00001617
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001618 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1619
John McCall9f3059a2009-10-09 21:13:30 +00001620 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001621 return;
1622
1623 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1624 Op != OpEnd; ++Op) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001625 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001626 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1627 Functions.insert(FD); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001628 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor15448f82009-06-27 21:05:07 +00001629 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1630 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001631 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001632 // later?
1633 if (!FunTmpl->getDeclContext()->isRecord())
1634 Functions.insert(FunTmpl);
1635 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001636 }
1637}
1638
John McCallc7e8e792009-08-07 22:18:02 +00001639static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1640 Decl *D) {
1641 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1642 Functions.insert(Func);
1643 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1644 Functions.insert(FunTmpl);
1645}
1646
Sebastian Redlc057f422009-10-23 19:23:15 +00001647void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001648 Expr **Args, unsigned NumArgs,
1649 FunctionSet &Functions) {
1650 // Find all of the associated namespaces and classes based on the
1651 // arguments we have.
1652 AssociatedNamespaceSet AssociatedNamespaces;
1653 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00001654 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00001655 AssociatedNamespaces,
1656 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001657
Sebastian Redlc057f422009-10-23 19:23:15 +00001658 QualType T1, T2;
1659 if (Operator) {
1660 T1 = Args[0]->getType();
1661 if (NumArgs >= 2)
1662 T2 = Args[1]->getType();
1663 }
1664
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001665 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001666 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1667 // and let Y be the lookup set produced by argument dependent
1668 // lookup (defined as follows). If X contains [...] then Y is
1669 // empty. Otherwise Y is the set of declarations found in the
1670 // namespaces associated with the argument types as described
1671 // below. The set of declarations found by the lookup of the name
1672 // is the union of X and Y.
1673 //
1674 // Here, we compute Y and add its members to the overloaded
1675 // candidate set.
1676 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001677 NSEnd = AssociatedNamespaces.end();
1678 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001679 // When considering an associated namespace, the lookup is the
1680 // same as the lookup performed when the associated namespace is
1681 // used as a qualifier (3.4.3.2) except that:
1682 //
1683 // -- Any using-directives in the associated namespace are
1684 // ignored.
1685 //
John McCallc7e8e792009-08-07 22:18:02 +00001686 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001687 // associated classes are visible within their respective
1688 // namespaces even if they are not visible during an ordinary
1689 // lookup (11.4).
1690 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00001691 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCallc7e8e792009-08-07 22:18:02 +00001692 Decl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00001693 // If the only declaration here is an ordinary friend, consider
1694 // it only if it was declared in an associated classes.
1695 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00001696 DeclContext *LexDC = D->getLexicalDeclContext();
1697 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1698 continue;
1699 }
Mike Stump11289f42009-09-09 15:08:12 +00001700
Sebastian Redlc057f422009-10-23 19:23:15 +00001701 FunctionDecl *Fn;
1702 if (!Operator || !(Fn = dyn_cast<FunctionDecl>(D)) ||
1703 IsAcceptableNonMemberOperatorCandidate(Fn, T1, T2, Context))
1704 CollectFunctionDecl(Functions, D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00001705 }
1706 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001707}
Douglas Gregor2d435302009-12-30 17:04:44 +00001708
1709//----------------------------------------------------------------------------
1710// Search for all visible declarations.
1711//----------------------------------------------------------------------------
1712VisibleDeclConsumer::~VisibleDeclConsumer() { }
1713
1714namespace {
1715
1716class ShadowContextRAII;
1717
1718class VisibleDeclsRecord {
1719public:
1720 /// \brief An entry in the shadow map, which is optimized to store a
1721 /// single declaration (the common case) but can also store a list
1722 /// of declarations.
1723 class ShadowMapEntry {
1724 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1725
1726 /// \brief Contains either the solitary NamedDecl * or a vector
1727 /// of declarations.
1728 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1729
1730 public:
1731 ShadowMapEntry() : DeclOrVector() { }
1732
1733 void Add(NamedDecl *ND);
1734 void Destroy();
1735
1736 // Iteration.
1737 typedef NamedDecl **iterator;
1738 iterator begin();
1739 iterator end();
1740 };
1741
1742private:
1743 /// \brief A mapping from declaration names to the declarations that have
1744 /// this name within a particular scope.
1745 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
1746
1747 /// \brief A list of shadow maps, which is used to model name hiding.
1748 std::list<ShadowMap> ShadowMaps;
1749
1750 /// \brief The declaration contexts we have already visited.
1751 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
1752
1753 friend class ShadowContextRAII;
1754
1755public:
1756 /// \brief Determine whether we have already visited this context
1757 /// (and, if not, note that we are going to visit that context now).
1758 bool visitedContext(DeclContext *Ctx) {
1759 return !VisitedContexts.insert(Ctx);
1760 }
1761
1762 /// \brief Determine whether the given declaration is hidden in the
1763 /// current scope.
1764 ///
1765 /// \returns the declaration that hides the given declaration, or
1766 /// NULL if no such declaration exists.
1767 NamedDecl *checkHidden(NamedDecl *ND);
1768
1769 /// \brief Add a declaration to the current shadow map.
1770 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
1771};
1772
1773/// \brief RAII object that records when we've entered a shadow context.
1774class ShadowContextRAII {
1775 VisibleDeclsRecord &Visible;
1776
1777 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
1778
1779public:
1780 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
1781 Visible.ShadowMaps.push_back(ShadowMap());
1782 }
1783
1784 ~ShadowContextRAII() {
1785 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
1786 EEnd = Visible.ShadowMaps.back().end();
1787 E != EEnd;
1788 ++E)
1789 E->second.Destroy();
1790
1791 Visible.ShadowMaps.pop_back();
1792 }
1793};
1794
1795} // end anonymous namespace
1796
1797void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
1798 if (DeclOrVector.isNull()) {
1799 // 0 - > 1 elements: just set the single element information.
1800 DeclOrVector = ND;
1801 return;
1802 }
1803
1804 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
1805 // 1 -> 2 elements: create the vector of results and push in the
1806 // existing declaration.
1807 DeclVector *Vec = new DeclVector;
1808 Vec->push_back(PrevND);
1809 DeclOrVector = Vec;
1810 }
1811
1812 // Add the new element to the end of the vector.
1813 DeclOrVector.get<DeclVector*>()->push_back(ND);
1814}
1815
1816void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
1817 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
1818 delete Vec;
1819 DeclOrVector = ((NamedDecl *)0);
1820 }
1821}
1822
1823VisibleDeclsRecord::ShadowMapEntry::iterator
1824VisibleDeclsRecord::ShadowMapEntry::begin() {
1825 if (DeclOrVector.isNull())
1826 return 0;
1827
1828 if (DeclOrVector.dyn_cast<NamedDecl *>())
1829 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
1830
1831 return DeclOrVector.get<DeclVector *>()->begin();
1832}
1833
1834VisibleDeclsRecord::ShadowMapEntry::iterator
1835VisibleDeclsRecord::ShadowMapEntry::end() {
1836 if (DeclOrVector.isNull())
1837 return 0;
1838
1839 if (DeclOrVector.dyn_cast<NamedDecl *>())
1840 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
1841
1842 return DeclOrVector.get<DeclVector *>()->end();
1843}
1844
1845NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
1846 unsigned IDNS = ND->getIdentifierNamespace();
1847 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
1848 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
1849 SM != SMEnd; ++SM) {
1850 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
1851 if (Pos == SM->end())
1852 continue;
1853
1854 for (ShadowMapEntry::iterator I = Pos->second.begin(),
1855 IEnd = Pos->second.end();
1856 I != IEnd; ++I) {
1857 // A tag declaration does not hide a non-tag declaration.
1858 if ((*I)->getIdentifierNamespace() == Decl::IDNS_Tag &&
1859 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
1860 Decl::IDNS_ObjCProtocol)))
1861 continue;
1862
1863 // Protocols are in distinct namespaces from everything else.
1864 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
1865 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
1866 (*I)->getIdentifierNamespace() != IDNS)
1867 continue;
1868
1869 // We've found a declaration that hides this one.
1870 return *I;
1871 }
1872 }
1873
1874 return 0;
1875}
1876
1877static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
1878 bool QualifiedNameLookup,
1879 VisibleDeclConsumer &Consumer,
1880 VisibleDeclsRecord &Visited) {
1881 // Make sure we don't visit the same context twice.
1882 if (Visited.visitedContext(Ctx->getPrimaryContext()))
1883 return;
1884
1885 // Enumerate all of the results in this context.
1886 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
1887 CurCtx = CurCtx->getNextContext()) {
1888 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
1889 DEnd = CurCtx->decls_end();
1890 D != DEnd; ++D) {
1891 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
1892 if (Result.isAcceptableDecl(ND)) {
1893 Consumer.FoundDecl(ND, Visited.checkHidden(ND));
1894 Visited.add(ND);
1895 }
1896
1897 // Visit transparent contexts inside this context.
1898 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
1899 if (InnerCtx->isTransparentContext())
1900 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup,
1901 Consumer, Visited);
1902 }
1903 }
1904 }
1905
1906 // Traverse using directives for qualified name lookup.
1907 if (QualifiedNameLookup) {
1908 ShadowContextRAII Shadow(Visited);
1909 DeclContext::udir_iterator I, E;
1910 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
1911 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
1912 QualifiedNameLookup, Consumer, Visited);
1913 }
1914 }
1915
1916 // Traverse the contexts of inherited classes.
1917 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
1918 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
1919 BEnd = Record->bases_end();
1920 B != BEnd; ++B) {
1921 QualType BaseType = B->getType();
1922
1923 // Don't look into dependent bases, because name lookup can't look
1924 // there anyway.
1925 if (BaseType->isDependentType())
1926 continue;
1927
1928 const RecordType *Record = BaseType->getAs<RecordType>();
1929 if (!Record)
1930 continue;
1931
1932 // FIXME: It would be nice to be able to determine whether referencing
1933 // a particular member would be ambiguous. For example, given
1934 //
1935 // struct A { int member; };
1936 // struct B { int member; };
1937 // struct C : A, B { };
1938 //
1939 // void f(C *c) { c->### }
1940 //
1941 // accessing 'member' would result in an ambiguity. However, we
1942 // could be smart enough to qualify the member with the base
1943 // class, e.g.,
1944 //
1945 // c->B::member
1946 //
1947 // or
1948 //
1949 // c->A::member
1950
1951 // Find results in this base class (and its bases).
1952 ShadowContextRAII Shadow(Visited);
1953 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
1954 Consumer, Visited);
1955 }
1956 }
1957
1958 // FIXME: Look into base classes in Objective-C!
1959}
1960
1961static void LookupVisibleDecls(Scope *S, LookupResult &Result,
1962 UnqualUsingDirectiveSet &UDirs,
1963 VisibleDeclConsumer &Consumer,
1964 VisibleDeclsRecord &Visited) {
1965 if (!S)
1966 return;
1967
1968 DeclContext *Entity = 0;
1969 if (S->getEntity() &&
1970 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
1971 // Look into this scope's declaration context, along with any of its
1972 // parent lookup contexts (e.g., enclosing classes), up to the point
1973 // where we hit the context stored in the next outer scope.
1974 Entity = (DeclContext *)S->getEntity();
1975 DeclContext *OuterCtx = findOuterContext(S);
1976
1977 for (DeclContext *Ctx = Entity; Ctx && Ctx->getPrimaryContext() != OuterCtx;
1978 Ctx = Ctx->getLookupParent()) {
1979 if (Ctx->isFunctionOrMethod())
1980 continue;
1981
1982 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
1983 Consumer, Visited);
1984 }
1985 } else if (!S->getParent()) {
1986 // Look into the translation unit scope. We walk through the translation
1987 // unit's declaration context, because the Scope itself won't have all of
1988 // the declarations if we loaded a precompiled header.
1989 // FIXME: We would like the translation unit's Scope object to point to the
1990 // translation unit, so we don't need this special "if" branch. However,
1991 // doing so would force the normal C++ name-lookup code to look into the
1992 // translation unit decl when the IdentifierInfo chains would suffice.
1993 // Once we fix that problem (which is part of a more general "don't look
1994 // in DeclContexts unless we have to" optimization), we can eliminate the
1995 // TranslationUnit parameter entirely.
1996 Entity = Result.getSema().Context.getTranslationUnitDecl();
1997 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
1998 Consumer, Visited);
1999 } else {
2000 // Walk through the declarations in this Scope.
2001 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2002 D != DEnd; ++D) {
2003 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2004 if (Result.isAcceptableDecl(ND)) {
2005 Consumer.FoundDecl(ND, Visited.checkHidden(ND));
2006 Visited.add(ND);
2007 }
2008 }
2009 }
2010
2011 if (Entity) {
2012 // Lookup visible declarations in any namespaces found by using
2013 // directives.
2014 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2015 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2016 for (; UI != UEnd; ++UI)
2017 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
2018 Result, /*QualifiedNameLookup=*/false, Consumer,
2019 Visited);
2020 }
2021
2022 // Lookup names in the parent scope.
2023 ShadowContextRAII Shadow(Visited);
2024 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2025}
2026
2027void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2028 VisibleDeclConsumer &Consumer) {
2029 // Determine the set of using directives available during
2030 // unqualified name lookup.
2031 Scope *Initial = S;
2032 UnqualUsingDirectiveSet UDirs;
2033 if (getLangOptions().CPlusPlus) {
2034 // Find the first namespace or translation-unit scope.
2035 while (S && !isNamespaceOrTranslationUnitScope(S))
2036 S = S->getParent();
2037
2038 UDirs.visitScopeChain(Initial, S);
2039 }
2040 UDirs.done();
2041
2042 // Look for visible declarations.
2043 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2044 VisibleDeclsRecord Visited;
2045 ShadowContextRAII Shadow(Visited);
2046 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2047}
2048
2049void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2050 VisibleDeclConsumer &Consumer) {
2051 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2052 VisibleDeclsRecord Visited;
2053 ShadowContextRAII Shadow(Visited);
2054 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true, Consumer,
2055 Visited);
2056}
2057
2058//----------------------------------------------------------------------------
2059// Typo correction
2060//----------------------------------------------------------------------------
2061
2062namespace {
2063class TypoCorrectionConsumer : public VisibleDeclConsumer {
2064 /// \brief The name written that is a typo in the source.
2065 llvm::StringRef Typo;
2066
2067 /// \brief The results found that have the smallest edit distance
2068 /// found (so far) with the typo name.
2069 llvm::SmallVector<NamedDecl *, 4> BestResults;
2070
2071 /// \brief The best edit distance found so far.
2072 unsigned BestEditDistance;
2073
2074public:
2075 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2076 : Typo(Typo->getName()) { }
2077
2078 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding);
2079
2080 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2081 iterator begin() const { return BestResults.begin(); }
2082 iterator end() const { return BestResults.end(); }
2083 bool empty() const { return BestResults.empty(); }
2084
2085 unsigned getBestEditDistance() const { return BestEditDistance; }
2086};
2087
2088}
2089
2090void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding) {
2091 // Don't consider hidden names for typo correction.
2092 if (Hiding)
2093 return;
2094
2095 // Only consider entities with identifiers for names, ignoring
2096 // special names (constructors, overloaded operators, selectors,
2097 // etc.).
2098 IdentifierInfo *Name = ND->getIdentifier();
2099 if (!Name)
2100 return;
2101
2102 // Compute the edit distance between the typo and the name of this
2103 // entity. If this edit distance is not worse than the best edit
2104 // distance we've seen so far, add it to the list of results.
2105 unsigned ED = Typo.edit_distance(Name->getName());
2106 if (!BestResults.empty()) {
2107 if (ED < BestEditDistance) {
2108 // This result is better than any we've seen before; clear out
2109 // the previous results.
2110 BestResults.clear();
2111 BestEditDistance = ED;
2112 } else if (ED > BestEditDistance) {
2113 // This result is worse than the best results we've seen so far;
2114 // ignore it.
2115 return;
2116 }
2117 } else
2118 BestEditDistance = ED;
2119
2120 BestResults.push_back(ND);
2121}
2122
2123/// \brief Try to "correct" a typo in the source code by finding
2124/// visible declarations whose names are similar to the name that was
2125/// present in the source code.
2126///
2127/// \param Res the \c LookupResult structure that contains the name
2128/// that was present in the source code along with the name-lookup
2129/// criteria used to search for the name. On success, this structure
2130/// will contain the results of name lookup.
2131///
2132/// \param S the scope in which name lookup occurs.
2133///
2134/// \param SS the nested-name-specifier that precedes the name we're
2135/// looking for, if present.
2136///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002137/// \param MemberContext if non-NULL, the context in which to look for
2138/// a member access expression.
2139///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002140/// \param EnteringContext whether we're entering the context described by
2141/// the nested-name-specifier SS.
2142///
Douglas Gregor2d435302009-12-30 17:04:44 +00002143/// \returns true if the typo was corrected, in which case the \p Res
2144/// structure will contain the results of name lookup for the
2145/// corrected name. Otherwise, returns false.
2146bool Sema::CorrectTypo(LookupResult &Res, Scope *S, const CXXScopeSpec *SS,
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002147 DeclContext *MemberContext, bool EnteringContext) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002148 // We only attempt to correct typos for identifiers.
2149 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2150 if (!Typo)
2151 return false;
2152
2153 // If the scope specifier itself was invalid, don't try to correct
2154 // typos.
2155 if (SS && SS->isInvalid())
2156 return false;
2157
2158 // Never try to correct typos during template deduction or
2159 // instantiation.
2160 if (!ActiveTemplateInstantiations.empty())
2161 return false;
2162
2163 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002164 if (MemberContext)
2165 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
2166 else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002167 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2168 if (!DC)
2169 return false;
2170
2171 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2172 } else {
2173 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2174 }
2175
2176 if (Consumer.empty())
2177 return false;
2178
2179 // Only allow a single, closest name in the result set (it's okay to
2180 // have overloads of that name, though).
2181 TypoCorrectionConsumer::iterator I = Consumer.begin();
2182 DeclarationName BestName = (*I)->getDeclName();
2183 ++I;
2184 for(TypoCorrectionConsumer::iterator IEnd = Consumer.end(); I != IEnd; ++I) {
2185 if (BestName != (*I)->getDeclName())
2186 return false;
2187 }
2188
2189 // BestName is the closest viable name to what the user
2190 // typed. However, to make sure that we don't pick something that's
2191 // way off, make sure that the user typed at least 3 characters for
2192 // each correction.
2193 unsigned ED = Consumer.getBestEditDistance();
2194 if (ED == 0 || (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
2195 return false;
2196
2197 // Perform name lookup again with the name we chose, and declare
2198 // success if we found something that was not ambiguous.
2199 Res.clear();
2200 Res.setLookupName(BestName);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002201 if (MemberContext)
2202 LookupQualifiedName(Res, MemberContext);
2203 else
2204 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2205 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00002206
2207 if (Res.isAmbiguous()) {
2208 Res.suppressDiagnostics();
2209 return false;
2210 }
2211
2212 return Res.getResultKind() != LookupResult::NotFound;
Douglas Gregor2d435302009-12-30 17:04:44 +00002213}