blob: 615f2f1d84c47491f405c7e4e0868b222b247b30 [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) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000320 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000321 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 McCallad371252010-01-20 00:46:10 +0000327 if (isa<FunctionTemplateDecl>(*Decls.begin()))
John McCall283b9012009-11-22 00:44:51 +0000328 ResultKind = FoundOverloaded;
John McCallad371252010-01-20 00:46:10 +0000329 else if (isa<UnresolvedUsingValueDecl>(*Decls.begin()))
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 McCall5b0829a2010-02-10 09:31:12 +0000407 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000408 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
Douglas Gregord3a59182010-02-12 05:48:04 +0000441/// \brief Lookup a builtin function, when name lookup would otherwise
442/// fail.
443static bool LookupBuiltin(Sema &S, LookupResult &R) {
444 Sema::LookupNameKind NameKind = R.getLookupKind();
445
446 // If we didn't find a use of this identifier, and if the identifier
447 // corresponds to a compiler builtin, create the decl object for the builtin
448 // now, injecting it into translation unit scope, and return it.
449 if (NameKind == Sema::LookupOrdinaryName ||
450 NameKind == Sema::LookupRedeclarationWithLinkage) {
451 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
452 if (II) {
453 // If this is a builtin on this (or all) targets, create the decl.
454 if (unsigned BuiltinID = II->getBuiltinID()) {
455 // In C++, we don't have any predefined library functions like
456 // 'malloc'. Instead, we'll just error.
457 if (S.getLangOptions().CPlusPlus &&
458 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
459 return false;
460
461 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
462 S.TUScope, R.isForRedeclaration(),
463 R.getNameLoc());
464 if (D)
465 R.addDecl(D);
466 return (D != NULL);
467 }
468 }
469 }
470
471 return false;
472}
473
John McCall9f3059a2009-10-09 21:13:30 +0000474// Adds all qualifying matches for a name within a decl context to the
475// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000476static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000477 bool Found = false;
478
John McCallf6c8a4e2009-11-10 07:01:13 +0000479 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000480 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000481 NamedDecl *D = *I;
482 if (R.isAcceptableDecl(D)) {
483 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000484 Found = true;
485 }
486 }
John McCall9f3059a2009-10-09 21:13:30 +0000487
Douglas Gregord3a59182010-02-12 05:48:04 +0000488 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
489 return true;
490
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000491 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000492 != DeclarationName::CXXConversionFunctionName ||
493 R.getLookupName().getCXXNameType()->isDependentType() ||
494 !isa<CXXRecordDecl>(DC))
495 return Found;
496
497 // C++ [temp.mem]p6:
498 // A specialization of a conversion function template is not found by
499 // name lookup. Instead, any conversion function templates visible in the
500 // context of the use are considered. [...]
501 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
502 if (!Record->isDefinition())
503 return Found;
504
505 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
506 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
507 UEnd = Unresolved->end(); U != UEnd; ++U) {
508 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
509 if (!ConvTemplate)
510 continue;
511
512 // When we're performing lookup for the purposes of redeclaration, just
513 // add the conversion function template. When we deduce template
514 // arguments for specializations, we'll end up unifying the return
515 // type of the new declaration with the type of the function template.
516 if (R.isForRedeclaration()) {
517 R.addDecl(ConvTemplate);
518 Found = true;
519 continue;
520 }
521
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000522 // C++ [temp.mem]p6:
Chandler Carruth3a693b72010-01-31 11:44:02 +0000523 // [...] For each such operator, if argument deduction succeeds
524 // (14.9.2.3), the resulting specialization is used as if found by
525 // name lookup.
526 //
527 // When referencing a conversion function for any purpose other than
528 // a redeclaration (such that we'll be building an expression with the
529 // result), perform template argument deduction and place the
530 // specialization into the result set. We do this to avoid forcing all
531 // callers to perform special deduction for conversion functions.
John McCallbc077cf2010-02-08 23:07:23 +0000532 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000533 FunctionDecl *Specialization = 0;
534
535 const FunctionProtoType *ConvProto
536 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
537 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000538
Chandler Carruth3a693b72010-01-31 11:44:02 +0000539 // Compute the type of the function that we would expect the conversion
540 // function to have, if it were to match the name given.
541 // FIXME: Calling convention!
542 QualType ExpectedType
543 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
544 0, 0, ConvProto->isVariadic(),
545 ConvProto->getTypeQuals(),
546 false, false, 0, 0,
Douglas Gregor36c569f2010-02-21 22:15:06 +0000547 ConvProto->getNoReturnAttr(),
548 CC_Default);
Chandler Carruth3a693b72010-01-31 11:44:02 +0000549
550 // Perform template argument deduction against the type that we would
551 // expect the function to have.
552 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
553 Specialization, Info)
554 == Sema::TDK_Success) {
555 R.addDecl(Specialization);
556 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000557 }
558 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000559
John McCall9f3059a2009-10-09 21:13:30 +0000560 return Found;
561}
562
John McCallf6c8a4e2009-11-10 07:01:13 +0000563// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000564static bool
Douglas Gregord3a59182010-02-12 05:48:04 +0000565CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
566 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000567
568 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
569
John McCallf6c8a4e2009-11-10 07:01:13 +0000570 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000571 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000572
John McCallf6c8a4e2009-11-10 07:01:13 +0000573 // Perform direct name lookup into the namespaces nominated by the
574 // using directives whose common ancestor is this namespace.
575 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
576 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000577
John McCallf6c8a4e2009-11-10 07:01:13 +0000578 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000579 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000580 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000581
582 R.resolveKind();
583
584 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000585}
586
587static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000588 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000589 return Ctx->isFileContext();
590 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000591}
Douglas Gregored8f2882009-01-30 01:04:22 +0000592
Douglas Gregor66230062010-03-15 14:33:29 +0000593// Find the next outer declaration context from this scope. This
594// routine actually returns the semantic outer context, which may
595// differ from the lexical context (encoded directly in the Scope
596// stack) when we are parsing a member of a class template. In this
597// case, the second element of the pair will be true, to indicate that
598// name lookup should continue searching in this semantic context when
599// it leaves the current template parameter scope.
600static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
601 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
602 DeclContext *Lexical = 0;
603 for (Scope *OuterS = S->getParent(); OuterS;
604 OuterS = OuterS->getParent()) {
605 if (OuterS->getEntity()) {
606 Lexical
607 = static_cast<DeclContext *>(OuterS->getEntity())->getPrimaryContext();
608 break;
609 }
610 }
611
612 // C++ [temp.local]p8:
613 // In the definition of a member of a class template that appears
614 // outside of the namespace containing the class template
615 // definition, the name of a template-parameter hides the name of
616 // a member of this namespace.
617 //
618 // Example:
619 //
620 // namespace N {
621 // class C { };
622 //
623 // template<class T> class B {
624 // void f(T);
625 // };
626 // }
627 //
628 // template<class C> void N::B<C>::f(C) {
629 // C b; // C is the template parameter, not N::C
630 // }
631 //
632 // In this example, the lexical context we return is the
633 // TranslationUnit, while the semantic context is the namespace N.
634 if (!Lexical || !DC || !S->getParent() ||
635 !S->getParent()->isTemplateParamScope())
636 return std::make_pair(Lexical, false);
637
638 // Find the outermost template parameter scope.
639 // For the example, this is the scope for the template parameters of
640 // template<class C>.
641 Scope *OutermostTemplateScope = S->getParent();
642 while (OutermostTemplateScope->getParent() &&
643 OutermostTemplateScope->getParent()->isTemplateParamScope())
644 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregor7f737c02009-09-10 16:57:35 +0000645
Douglas Gregor66230062010-03-15 14:33:29 +0000646 // Find the namespace context in which the original scope occurs. In
647 // the example, this is namespace N.
648 DeclContext *Semantic = DC;
649 while (!Semantic->isFileContext())
650 Semantic = Semantic->getParent();
651
652 // Find the declaration context just outside of the template
653 // parameter scope. This is the context in which the template is
654 // being lexically declaration (a namespace context). In the
655 // example, this is the global scope.
656 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
657 Lexical->Encloses(Semantic))
658 return std::make_pair(Semantic, true);
659
660 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000661}
662
John McCall27b18f82009-11-17 02:14:36 +0000663bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000664 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000665
666 DeclarationName Name = R.getLookupName();
667
Douglas Gregor889ceb72009-02-03 19:21:40 +0000668 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000669 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000670 I = IdResolver.begin(Name),
671 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000672
Douglas Gregor889ceb72009-02-03 19:21:40 +0000673 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000674 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000675 // ...During unqualified name lookup (3.4.1), the names appear as if
676 // they were declared in the nearest enclosing namespace which contains
677 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000678 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000679 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000680 //
681 // For example:
682 // namespace A { int i; }
683 // void foo() {
684 // int i;
685 // {
686 // using namespace A;
687 // ++i; // finds local 'i', A::i appears at global scope
688 // }
689 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000690 //
Douglas Gregor66230062010-03-15 14:33:29 +0000691 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000692 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000693 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000694 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000695 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000696 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000697 Found = true;
698 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000699 }
700 }
John McCall9f3059a2009-10-09 21:13:30 +0000701 if (Found) {
702 R.resolveKind();
703 return true;
704 }
705
Douglas Gregor66230062010-03-15 14:33:29 +0000706 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
707 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
708 S->getParent() && !S->getParent()->isTemplateParamScope()) {
709 // We've just searched the last template parameter scope and
710 // found nothing, so look into the the contexts between the
711 // lexical and semantic declaration contexts returned by
712 // findOuterContext(). This implements the name lookup behavior
713 // of C++ [temp.local]p8.
714 Ctx = OutsideOfTemplateParamDC;
715 OutsideOfTemplateParamDC = 0;
716 }
717
718 if (Ctx) {
719 DeclContext *OuterCtx;
720 bool SearchAfterTemplateScope;
721 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
722 if (SearchAfterTemplateScope)
723 OutsideOfTemplateParamDC = OuterCtx;
724
Douglas Gregor7f737c02009-09-10 16:57:35 +0000725 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
726 Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000727 // We do not directly look into transparent contexts, since
728 // those entities will be found in the nearest enclosing
729 // non-transparent context.
730 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000731 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000732
733 // We do not look directly into function or method contexts,
734 // since all of the local variables and parameters of the
735 // function/method are present within the Scope.
736 if (Ctx->isFunctionOrMethod()) {
737 // If we have an Objective-C instance method, look for ivars
738 // in the corresponding interface.
739 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
740 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
741 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
742 ObjCInterfaceDecl *ClassDeclared;
743 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
744 Name.getAsIdentifierInfo(),
745 ClassDeclared)) {
746 if (R.isAcceptableDecl(Ivar)) {
747 R.addDecl(Ivar);
748 R.resolveKind();
749 return true;
750 }
751 }
752 }
753 }
754
755 continue;
756 }
757
Douglas Gregor7f737c02009-09-10 16:57:35 +0000758 // Perform qualified name lookup into this context.
759 // FIXME: In some cases, we know that every name that could be found by
760 // this qualified name lookup will also be on the identifier chain. For
761 // example, inside a class without any base classes, we never need to
762 // perform qualified lookup because all of the members are on top of the
763 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000764 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000765 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000766 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000767 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000768 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000769
John McCallf6c8a4e2009-11-10 07:01:13 +0000770 // Stop if we ran out of scopes.
771 // FIXME: This really, really shouldn't be happening.
772 if (!S) return false;
773
Douglas Gregor700792c2009-02-05 19:25:20 +0000774 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000775 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000776 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000777 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
778 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000779
John McCallf6c8a4e2009-11-10 07:01:13 +0000780 UnqualUsingDirectiveSet UDirs;
781 UDirs.visitScopeChain(Initial, S);
782 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000783
Douglas Gregor700792c2009-02-05 19:25:20 +0000784 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000785 // Unqualified name lookup in C++ requires looking into scopes
786 // that aren't strictly lexical, and therefore we walk through the
787 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000788
Douglas Gregor889ceb72009-02-03 19:21:40 +0000789 for (; S; S = S->getParent()) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000790 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregor3ce74932010-02-05 07:07:10 +0000791 if (Ctx && Ctx->isTransparentContext())
Douglas Gregorf2270432009-08-24 18:55:03 +0000792 continue;
793
Douglas Gregor889ceb72009-02-03 19:21:40 +0000794 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000795 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000796 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000797 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000798 // We found something. Look for anything else in our scope
799 // with this same name and in an acceptable identifier
800 // namespace, so that we can construct an overload set if we
801 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000802 Found = true;
803 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000804 }
805 }
806
Douglas Gregor66230062010-03-15 14:33:29 +0000807 // If we have a context, and it's not a context stashed in the
808 // template parameter scope for an out-of-line definition, also
809 // look into that context.
810 if (Ctx && !(Found && S && S->isTemplateParamScope())) {
Douglas Gregor3ce74932010-02-05 07:07:10 +0000811 assert(Ctx->isFileContext() &&
812 "We should have been looking only at file context here already.");
813
814 // Look into context considering using-directives.
Douglas Gregord3a59182010-02-12 05:48:04 +0000815 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
Douglas Gregor3ce74932010-02-05 07:07:10 +0000816 Found = true;
817 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000818
John McCall9f3059a2009-10-09 21:13:30 +0000819 if (Found) {
820 R.resolveKind();
821 return true;
822 }
823
Douglas Gregor3ce74932010-02-05 07:07:10 +0000824 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000825 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000826 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000827
John McCall9f3059a2009-10-09 21:13:30 +0000828 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000829}
830
Douglas Gregor34074322009-01-14 22:20:51 +0000831/// @brief Perform unqualified name lookup starting from a given
832/// scope.
833///
834/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
835/// used to find names within the current scope. For example, 'x' in
836/// @code
837/// int x;
838/// int f() {
839/// return x; // unqualified name look finds 'x' in the global scope
840/// }
841/// @endcode
842///
843/// Different lookup criteria can find different names. For example, a
844/// particular scope can have both a struct and a function of the same
845/// name, and each can be found by certain lookup criteria. For more
846/// information about lookup criteria, see the documentation for the
847/// class LookupCriteria.
848///
849/// @param S The scope from which unqualified name lookup will
850/// begin. If the lookup criteria permits, name lookup may also search
851/// in the parent scopes.
852///
853/// @param Name The name of the entity that we are searching for.
854///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000855/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000856/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000857/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000858///
859/// @returns The result of name lookup, which includes zero or more
860/// declarations and possibly additional information used to diagnose
861/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000862bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
863 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +0000864 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000865
John McCall27b18f82009-11-17 02:14:36 +0000866 LookupNameKind NameKind = R.getLookupKind();
867
Douglas Gregor34074322009-01-14 22:20:51 +0000868 if (!getLangOptions().CPlusPlus) {
869 // Unqualified name lookup in C/Objective-C is purely lexical, so
870 // search in the declarations attached to the name.
871
John McCallea305ed2009-12-18 10:40:03 +0000872 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000873 // Find the nearest non-transparent declaration scope.
874 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000875 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000876 static_cast<DeclContext *>(S->getEntity())
877 ->isTransparentContext()))
878 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +0000879 }
880
John McCallea305ed2009-12-18 10:40:03 +0000881 unsigned IDNS = R.getIdentifierNamespace();
882
Douglas Gregor34074322009-01-14 22:20:51 +0000883 // Scan up the scope chain looking for a decl that matches this
884 // identifier that is in the appropriate namespace. This search
885 // should not take long, as shadowing of names is uncommon, and
886 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000887 bool LeftStartingScope = false;
888
Douglas Gregored8f2882009-01-30 01:04:22 +0000889 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000890 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000891 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000892 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000893 if (NameKind == LookupRedeclarationWithLinkage) {
894 // Determine whether this (or a previous) declaration is
895 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000896 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000897 LeftStartingScope = true;
898
899 // If we found something outside of our starting scope that
900 // does not have linkage, skip it.
901 if (LeftStartingScope && !((*I)->hasLinkage()))
902 continue;
903 }
904
John McCall9f3059a2009-10-09 21:13:30 +0000905 R.addDecl(*I);
906
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000907 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000908 // If this declaration has the "overloadable" attribute, we
909 // might have a set of overloaded functions.
910
911 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000912 while (!(S->getFlags() & Scope::DeclScope) ||
913 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000914 S = S->getParent();
915
916 // Find the last declaration in this scope (with the same
917 // name, naturally).
918 IdentifierResolver::iterator LastI = I;
919 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000920 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000921 break;
John McCall9f3059a2009-10-09 21:13:30 +0000922 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000923 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000924 }
925
John McCall9f3059a2009-10-09 21:13:30 +0000926 R.resolveKind();
927
928 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000929 }
Douglas Gregor34074322009-01-14 22:20:51 +0000930 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000931 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000932 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +0000933 return true;
Douglas Gregor34074322009-01-14 22:20:51 +0000934 }
935
936 // If we didn't find a use of this identifier, and if the identifier
937 // corresponds to a compiler builtin, create the decl object for the builtin
938 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +0000939 if (AllowBuiltinCreation)
940 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000941
John McCall9f3059a2009-10-09 21:13:30 +0000942 return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000943}
944
John McCall6538c932009-10-10 05:48:19 +0000945/// @brief Perform qualified name lookup in the namespaces nominated by
946/// using directives by the given context.
947///
948/// C++98 [namespace.qual]p2:
949/// Given X::m (where X is a user-declared namespace), or given ::m
950/// (where X is the global namespace), let S be the set of all
951/// declarations of m in X and in the transitive closure of all
952/// namespaces nominated by using-directives in X and its used
953/// namespaces, except that using-directives are ignored in any
954/// namespace, including X, directly containing one or more
955/// declarations of m. No namespace is searched more than once in
956/// the lookup of a name. If S is the empty set, the program is
957/// ill-formed. Otherwise, if S has exactly one member, or if the
958/// context of the reference is a using-declaration
959/// (namespace.udecl), S is the required set of declarations of
960/// m. Otherwise if the use of m is not one that allows a unique
961/// declaration to be chosen from S, the program is ill-formed.
962/// C++98 [namespace.qual]p5:
963/// During the lookup of a qualified namespace member name, if the
964/// lookup finds more than one declaration of the member, and if one
965/// declaration introduces a class name or enumeration name and the
966/// other declarations either introduce the same object, the same
967/// enumerator or a set of functions, the non-type name hides the
968/// class or enumeration name if and only if the declarations are
969/// from the same namespace; otherwise (the declarations are from
970/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +0000971static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +0000972 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +0000973 assert(StartDC->isFileContext() && "start context is not a file context");
974
975 DeclContext::udir_iterator I = StartDC->using_directives_begin();
976 DeclContext::udir_iterator E = StartDC->using_directives_end();
977
978 if (I == E) return false;
979
980 // We have at least added all these contexts to the queue.
981 llvm::DenseSet<DeclContext*> Visited;
982 Visited.insert(StartDC);
983
984 // We have not yet looked into these namespaces, much less added
985 // their "using-children" to the queue.
986 llvm::SmallVector<NamespaceDecl*, 8> Queue;
987
988 // We have already looked into the initial namespace; seed the queue
989 // with its using-children.
990 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +0000991 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +0000992 if (Visited.insert(ND).second)
993 Queue.push_back(ND);
994 }
995
996 // The easiest way to implement the restriction in [namespace.qual]p5
997 // is to check whether any of the individual results found a tag
998 // and, if so, to declare an ambiguity if the final result is not
999 // a tag.
1000 bool FoundTag = false;
1001 bool FoundNonTag = false;
1002
John McCall5cebab12009-11-18 07:57:50 +00001003 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001004
1005 bool Found = false;
1006 while (!Queue.empty()) {
1007 NamespaceDecl *ND = Queue.back();
1008 Queue.pop_back();
1009
1010 // We go through some convolutions here to avoid copying results
1011 // between LookupResults.
1012 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001013 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001014 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001015
1016 if (FoundDirect) {
1017 // First do any local hiding.
1018 DirectR.resolveKind();
1019
1020 // If the local result is a tag, remember that.
1021 if (DirectR.isSingleTagDecl())
1022 FoundTag = true;
1023 else
1024 FoundNonTag = true;
1025
1026 // Append the local results to the total results if necessary.
1027 if (UseLocal) {
1028 R.addAllDecls(LocalR);
1029 LocalR.clear();
1030 }
1031 }
1032
1033 // If we find names in this namespace, ignore its using directives.
1034 if (FoundDirect) {
1035 Found = true;
1036 continue;
1037 }
1038
1039 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1040 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1041 if (Visited.insert(Nom).second)
1042 Queue.push_back(Nom);
1043 }
1044 }
1045
1046 if (Found) {
1047 if (FoundTag && FoundNonTag)
1048 R.setAmbiguousQualifiedTagHiding();
1049 else
1050 R.resolveKind();
1051 }
1052
1053 return Found;
1054}
1055
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001056/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001057///
1058/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1059/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001060/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001061///
1062/// Different lookup criteria can find different names. For example, a
1063/// particular scope can have both a struct and a function of the same
1064/// name, and each can be found by certain lookup criteria. For more
1065/// information about lookup criteria, see the documentation for the
1066/// class LookupCriteria.
1067///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001068/// \param R captures both the lookup criteria and any lookup results found.
1069///
1070/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001071/// search. If the lookup criteria permits, name lookup may also search
1072/// in the parent contexts or (for C++ classes) base classes.
1073///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001074/// \param InUnqualifiedLookup true if this is qualified name lookup that
1075/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001076///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001077/// \returns true if lookup succeeded, false if it failed.
1078bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1079 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001080 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001081
John McCall27b18f82009-11-17 02:14:36 +00001082 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001083 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001084
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001085 // Make sure that the declaration context is complete.
1086 assert((!isa<TagDecl>(LookupCtx) ||
1087 LookupCtx->isDependentContext() ||
1088 cast<TagDecl>(LookupCtx)->isDefinition() ||
1089 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1090 ->isBeingDefined()) &&
1091 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001092
Douglas Gregor34074322009-01-14 22:20:51 +00001093 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001094 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001095 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001096 if (isa<CXXRecordDecl>(LookupCtx))
1097 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001098 return true;
1099 }
Douglas Gregor34074322009-01-14 22:20:51 +00001100
John McCall6538c932009-10-10 05:48:19 +00001101 // Don't descend into implied contexts for redeclarations.
1102 // C++98 [namespace.qual]p6:
1103 // In a declaration for a namespace member in which the
1104 // declarator-id is a qualified-id, given that the qualified-id
1105 // for the namespace member has the form
1106 // nested-name-specifier unqualified-id
1107 // the unqualified-id shall name a member of the namespace
1108 // designated by the nested-name-specifier.
1109 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001110 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001111 return false;
1112
John McCall27b18f82009-11-17 02:14:36 +00001113 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001114 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001115 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001116
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001117 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001118 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001119 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1120 if (!LookupRec)
John McCall9f3059a2009-10-09 21:13:30 +00001121 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001122
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001123 // If we're performing qualified name lookup into a dependent class,
1124 // then we are actually looking into a current instantiation. If we have any
1125 // dependent base classes, then we either have to delay lookup until
1126 // template instantiation time (at which point all bases will be available)
1127 // or we have to fail.
1128 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1129 LookupRec->hasAnyDependentBases()) {
1130 R.setNotFoundInCurrentInstantiation();
1131 return false;
1132 }
1133
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001134 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001135 CXXBasePaths Paths;
1136 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001137
1138 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001139 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001140 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001141 case LookupOrdinaryName:
1142 case LookupMemberName:
1143 case LookupRedeclarationWithLinkage:
1144 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1145 break;
1146
1147 case LookupTagName:
1148 BaseCallback = &CXXRecordDecl::FindTagMember;
1149 break;
John McCall84d87672009-12-10 09:41:52 +00001150
1151 case LookupUsingDeclName:
1152 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001153
1154 case LookupOperatorName:
1155 case LookupNamespaceName:
1156 case LookupObjCProtocolName:
1157 case LookupObjCImplementationName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001158 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001159 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001160
1161 case LookupNestedNameSpecifierName:
1162 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1163 break;
1164 }
1165
John McCall27b18f82009-11-17 02:14:36 +00001166 if (!LookupRec->lookupInBases(BaseCallback,
1167 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001168 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001169
John McCall553c0792010-01-23 00:46:32 +00001170 R.setNamingClass(LookupRec);
1171
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001172 // C++ [class.member.lookup]p2:
1173 // [...] If the resulting set of declarations are not all from
1174 // sub-objects of the same type, or the set has a nonstatic member
1175 // and includes members from distinct sub-objects, there is an
1176 // ambiguity and the program is ill-formed. Otherwise that set is
1177 // the result of the lookup.
1178 // FIXME: support using declarations!
1179 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001180 int SubobjectNumber = 0;
John McCall401982f2010-01-20 21:53:11 +00001181 AccessSpecifier SubobjectAccess = AS_private;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001182 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001183 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001184 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001185
John McCall401982f2010-01-20 21:53:11 +00001186 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1187 // across all paths.
1188 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1189
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001190 // Determine whether we're looking at a distinct sub-object or not.
1191 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001192 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001193 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1194 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001195 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001196 != Context.getCanonicalType(PathElement.Base->getType())) {
1197 // We found members of the given name in two subobjects of
1198 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001199 R.setAmbiguousBaseSubobjectTypes(Paths);
1200 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001201 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1202 // We have a different subobject of the same type.
1203
1204 // C++ [class.member.lookup]p5:
1205 // A static member, a nested type or an enumerator defined in
1206 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001207 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001208 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001209 if (isa<VarDecl>(FirstDecl) ||
1210 isa<TypeDecl>(FirstDecl) ||
1211 isa<EnumConstantDecl>(FirstDecl))
1212 continue;
1213
1214 if (isa<CXXMethodDecl>(FirstDecl)) {
1215 // Determine whether all of the methods are static.
1216 bool AllMethodsAreStatic = true;
1217 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1218 Func != Path->Decls.second; ++Func) {
1219 if (!isa<CXXMethodDecl>(*Func)) {
1220 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1221 break;
1222 }
1223
1224 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1225 AllMethodsAreStatic = false;
1226 break;
1227 }
1228 }
1229
1230 if (AllMethodsAreStatic)
1231 continue;
1232 }
1233
1234 // We have found a nonstatic member name in multiple, distinct
1235 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001236 R.setAmbiguousBaseSubobjects(Paths);
1237 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001238 }
1239 }
1240
1241 // Lookup in a base class succeeded; return these results.
1242
John McCall9f3059a2009-10-09 21:13:30 +00001243 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001244 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1245 NamedDecl *D = *I;
1246 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1247 D->getAccess());
1248 R.addDecl(D, AS);
1249 }
John McCall9f3059a2009-10-09 21:13:30 +00001250 R.resolveKind();
1251 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001252}
1253
1254/// @brief Performs name lookup for a name that was parsed in the
1255/// source code, and may contain a C++ scope specifier.
1256///
1257/// This routine is a convenience routine meant to be called from
1258/// contexts that receive a name and an optional C++ scope specifier
1259/// (e.g., "N::M::x"). It will then perform either qualified or
1260/// unqualified name lookup (with LookupQualifiedName or LookupName,
1261/// respectively) on the given name and return those results.
1262///
1263/// @param S The scope from which unqualified name lookup will
1264/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001265///
Douglas Gregore861bac2009-08-25 22:51:20 +00001266/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001267///
1268/// @param Name The name of the entity that name lookup will
1269/// search for.
1270///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001271/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001272/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001273/// C library functions (like "malloc") are implicitly declared.
1274///
Douglas Gregore861bac2009-08-25 22:51:20 +00001275/// @param EnteringContext Indicates whether we are going to enter the
1276/// context of the scope-specifier SS (if present).
1277///
John McCall9f3059a2009-10-09 21:13:30 +00001278/// @returns True if any decls were found (but possibly ambiguous)
1279bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001280 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001281 if (SS && SS->isInvalid()) {
1282 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001283 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001284 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001285 }
Mike Stump11289f42009-09-09 15:08:12 +00001286
Douglas Gregore861bac2009-08-25 22:51:20 +00001287 if (SS && SS->isSet()) {
1288 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001289 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001290 // contex, and will perform name lookup in that context.
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001291 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCall9f3059a2009-10-09 21:13:30 +00001292 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001293
John McCall27b18f82009-11-17 02:14:36 +00001294 R.setContextRange(SS->getRange());
1295
1296 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001297 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001298
Douglas Gregore861bac2009-08-25 22:51:20 +00001299 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001300 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001301 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001302 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001303 }
1304
Mike Stump11289f42009-09-09 15:08:12 +00001305 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001306 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001307}
1308
Douglas Gregor889ceb72009-02-03 19:21:40 +00001309
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001310/// @brief Produce a diagnostic describing the ambiguity that resulted
1311/// from name lookup.
1312///
1313/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001314///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001315/// @param Name The name of the entity that name lookup was
1316/// searching for.
1317///
1318/// @param NameLoc The location of the name within the source code.
1319///
1320/// @param LookupRange A source range that provides more
1321/// source-location information concerning the lookup itself. For
1322/// example, this range might highlight a nested-name-specifier that
1323/// precedes the name.
1324///
1325/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001326bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001327 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1328
John McCall27b18f82009-11-17 02:14:36 +00001329 DeclarationName Name = Result.getLookupName();
1330 SourceLocation NameLoc = Result.getNameLoc();
1331 SourceRange LookupRange = Result.getContextRange();
1332
John McCall6538c932009-10-10 05:48:19 +00001333 switch (Result.getAmbiguityKind()) {
1334 case LookupResult::AmbiguousBaseSubobjects: {
1335 CXXBasePaths *Paths = Result.getBasePaths();
1336 QualType SubobjectType = Paths->front().back().Base->getType();
1337 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1338 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1339 << LookupRange;
1340
1341 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1342 while (isa<CXXMethodDecl>(*Found) &&
1343 cast<CXXMethodDecl>(*Found)->isStatic())
1344 ++Found;
1345
1346 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1347
1348 return true;
1349 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001350
John McCall6538c932009-10-10 05:48:19 +00001351 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001352 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1353 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001354
1355 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001356 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001357 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1358 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001359 Path != PathEnd; ++Path) {
1360 Decl *D = *Path->Decls.first;
1361 if (DeclsPrinted.insert(D).second)
1362 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1363 }
1364
Douglas Gregor1c846b02009-01-16 00:38:09 +00001365 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001366 }
1367
John McCall6538c932009-10-10 05:48:19 +00001368 case LookupResult::AmbiguousTagHiding: {
1369 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001370
John McCall6538c932009-10-10 05:48:19 +00001371 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1372
1373 LookupResult::iterator DI, DE = Result.end();
1374 for (DI = Result.begin(); DI != DE; ++DI)
1375 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1376 TagDecls.insert(TD);
1377 Diag(TD->getLocation(), diag::note_hidden_tag);
1378 }
1379
1380 for (DI = Result.begin(); DI != DE; ++DI)
1381 if (!isa<TagDecl>(*DI))
1382 Diag((*DI)->getLocation(), diag::note_hiding_object);
1383
1384 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001385 LookupResult::Filter F = Result.makeFilter();
1386 while (F.hasNext()) {
1387 if (TagDecls.count(F.next()))
1388 F.erase();
1389 }
1390 F.done();
John McCall6538c932009-10-10 05:48:19 +00001391
1392 return true;
1393 }
1394
1395 case LookupResult::AmbiguousReference: {
1396 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001397
John McCall6538c932009-10-10 05:48:19 +00001398 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1399 for (; DI != DE; ++DI)
1400 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001401
John McCall6538c932009-10-10 05:48:19 +00001402 return true;
1403 }
1404 }
1405
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001406 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001407 return true;
1408}
Douglas Gregore254f902009-02-04 00:32:51 +00001409
Mike Stump11289f42009-09-09 15:08:12 +00001410static void
1411addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001412 ASTContext &Context,
1413 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001414 Sema::AssociatedClassSet &AssociatedClasses);
1415
1416static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1417 DeclContext *Ctx) {
1418 if (Ctx->isFileContext())
1419 Namespaces.insert(Ctx);
1420}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001421
Mike Stump11289f42009-09-09 15:08:12 +00001422// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001423// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001424static void
1425addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001426 ASTContext &Context,
1427 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001428 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001429 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001430 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001431 switch (Arg.getKind()) {
1432 case TemplateArgument::Null:
1433 break;
Mike Stump11289f42009-09-09 15:08:12 +00001434
Douglas Gregor197e5f72009-07-08 07:51:57 +00001435 case TemplateArgument::Type:
1436 // [...] the namespaces and classes associated with the types of the
1437 // template arguments provided for template type parameters (excluding
1438 // template template parameters)
1439 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1440 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001441 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001442 break;
Mike Stump11289f42009-09-09 15:08:12 +00001443
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001444 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001445 // [...] the namespaces in which any template template arguments are
1446 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001447 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001448 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001449 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001450 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001451 DeclContext *Ctx = ClassTemplate->getDeclContext();
1452 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1453 AssociatedClasses.insert(EnclosingClass);
1454 // Add the associated namespace for this class.
1455 while (Ctx->isRecord())
1456 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001457 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001458 }
1459 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001460 }
1461
1462 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001463 case TemplateArgument::Integral:
1464 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001465 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001466 // associated namespaces. ]
1467 break;
Mike Stump11289f42009-09-09 15:08:12 +00001468
Douglas Gregor197e5f72009-07-08 07:51:57 +00001469 case TemplateArgument::Pack:
1470 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1471 PEnd = Arg.pack_end();
1472 P != PEnd; ++P)
1473 addAssociatedClassesAndNamespaces(*P, Context,
1474 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001475 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001476 break;
1477 }
1478}
1479
Douglas Gregore254f902009-02-04 00:32:51 +00001480// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001481// argument-dependent lookup with an argument of class type
1482// (C++ [basic.lookup.koenig]p2).
1483static void
1484addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregore254f902009-02-04 00:32:51 +00001485 ASTContext &Context,
1486 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001487 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001488 // C++ [basic.lookup.koenig]p2:
1489 // [...]
1490 // -- If T is a class type (including unions), its associated
1491 // classes are: the class itself; the class of which it is a
1492 // member, if any; and its direct and indirect base
1493 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001494 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001495
1496 // Add the class of which it is a member, if any.
1497 DeclContext *Ctx = Class->getDeclContext();
1498 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1499 AssociatedClasses.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001500 // Add the associated namespace for this class.
1501 while (Ctx->isRecord())
1502 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001503 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001504
Douglas Gregore254f902009-02-04 00:32:51 +00001505 // Add the class itself. If we've already seen this class, we don't
1506 // need to visit base classes.
1507 if (!AssociatedClasses.insert(Class))
1508 return;
1509
Mike Stump11289f42009-09-09 15:08:12 +00001510 // -- If T is a template-id, its associated namespaces and classes are
1511 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001512 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001513 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001514 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001515 // namespaces in which any template template arguments are defined; and
1516 // the classes in which any member templates used as template template
1517 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001518 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001519 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001520 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1521 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1522 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1523 AssociatedClasses.insert(EnclosingClass);
1524 // Add the associated namespace for this class.
1525 while (Ctx->isRecord())
1526 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001527 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001528
Douglas Gregor197e5f72009-07-08 07:51:57 +00001529 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1530 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1531 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1532 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001533 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001534 }
Mike Stump11289f42009-09-09 15:08:12 +00001535
John McCall67da35c2010-02-04 22:26:26 +00001536 // Only recurse into base classes for complete types.
1537 if (!Class->hasDefinition()) {
1538 // FIXME: we might need to instantiate templates here
1539 return;
1540 }
1541
Douglas Gregore254f902009-02-04 00:32:51 +00001542 // Add direct and indirect base classes along with their associated
1543 // namespaces.
1544 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1545 Bases.push_back(Class);
1546 while (!Bases.empty()) {
1547 // Pop this class off the stack.
1548 Class = Bases.back();
1549 Bases.pop_back();
1550
1551 // Visit the base classes.
1552 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1553 BaseEnd = Class->bases_end();
1554 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001555 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001556 // In dependent contexts, we do ADL twice, and the first time around,
1557 // the base type might be a dependent TemplateSpecializationType, or a
1558 // TemplateTypeParmType. If that happens, simply ignore it.
1559 // FIXME: If we want to support export, we probably need to add the
1560 // namespace of the template in a TemplateSpecializationType, or even
1561 // the classes and namespaces of known non-dependent arguments.
1562 if (!BaseType)
1563 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001564 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1565 if (AssociatedClasses.insert(BaseDecl)) {
1566 // Find the associated namespace for this base class.
1567 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1568 while (BaseCtx->isRecord())
1569 BaseCtx = BaseCtx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001570 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001571
1572 // Make sure we visit the bases of this base class.
1573 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1574 Bases.push_back(BaseDecl);
1575 }
1576 }
1577 }
1578}
1579
1580// \brief Add the associated classes and namespaces for
1581// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001582// (C++ [basic.lookup.koenig]p2).
1583static void
1584addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregore254f902009-02-04 00:32:51 +00001585 ASTContext &Context,
1586 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001587 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001588 // C++ [basic.lookup.koenig]p2:
1589 //
1590 // For each argument type T in the function call, there is a set
1591 // of zero or more associated namespaces and a set of zero or more
1592 // associated classes to be considered. The sets of namespaces and
1593 // classes is determined entirely by the types of the function
1594 // arguments (and the namespace of any template template
1595 // argument). Typedef names and using-declarations used to specify
1596 // the types do not contribute to this set. The sets of namespaces
1597 // and classes are determined in the following way:
1598 T = Context.getCanonicalType(T).getUnqualifiedType();
1599
1600 // -- If T is a pointer to U or an array of U, its associated
Mike Stump11289f42009-09-09 15:08:12 +00001601 // namespaces and classes are those associated with U.
Douglas Gregore254f902009-02-04 00:32:51 +00001602 //
1603 // We handle this by unwrapping pointer and array types immediately,
1604 // to avoid unnecessary recursion.
1605 while (true) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001606 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001607 T = Ptr->getPointeeType();
1608 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1609 T = Ptr->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001610 else
Douglas Gregore254f902009-02-04 00:32:51 +00001611 break;
1612 }
1613
1614 // -- If T is a fundamental type, its associated sets of
1615 // namespaces and classes are both empty.
John McCall9dd450b2009-09-21 23:43:11 +00001616 if (T->getAs<BuiltinType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001617 return;
1618
1619 // -- If T is a class type (including unions), its associated
1620 // classes are: the class itself; the class of which it is a
1621 // member, if any; and its direct and indirect base
1622 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001623 // which its associated classes are defined.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001624 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump11289f42009-09-09 15:08:12 +00001625 if (CXXRecordDecl *ClassDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001626 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001627 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1628 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001629 AssociatedClasses);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001630 return;
1631 }
Douglas Gregore254f902009-02-04 00:32:51 +00001632
1633 // -- If T is an enumeration type, its associated namespace is
1634 // the namespace in which it is defined. If it is class
1635 // member, its associated class is the member’s class; else
Mike Stump11289f42009-09-09 15:08:12 +00001636 // it has no associated class.
John McCall9dd450b2009-09-21 23:43:11 +00001637 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001638 EnumDecl *Enum = EnumT->getDecl();
1639
1640 DeclContext *Ctx = Enum->getDeclContext();
1641 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1642 AssociatedClasses.insert(EnclosingClass);
1643
1644 // Add the associated namespace for this class.
1645 while (Ctx->isRecord())
1646 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001647 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001648
1649 return;
1650 }
1651
1652 // -- If T is a function type, its associated namespaces and
1653 // classes are those associated with the function parameter
1654 // types and those associated with the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001655 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001656 // Return type
John McCall9dd450b2009-09-21 23:43:11 +00001657 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregore254f902009-02-04 00:32:51 +00001658 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001659 AssociatedNamespaces, AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001660
John McCall9dd450b2009-09-21 23:43:11 +00001661 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregore254f902009-02-04 00:32:51 +00001662 if (!Proto)
1663 return;
1664
1665 // Argument types
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001666 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001667 ArgEnd = Proto->arg_type_end();
Douglas Gregore254f902009-02-04 00:32:51 +00001668 Arg != ArgEnd; ++Arg)
1669 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallc7e8e792009-08-07 22:18:02 +00001670 AssociatedNamespaces, AssociatedClasses);
Mike Stump11289f42009-09-09 15:08:12 +00001671
Douglas Gregore254f902009-02-04 00:32:51 +00001672 return;
1673 }
1674
1675 // -- If T is a pointer to a member function of a class X, its
1676 // associated namespaces and classes are those associated
1677 // with the function parameter types and return type,
Mike Stump11289f42009-09-09 15:08:12 +00001678 // together with those associated with X.
Douglas Gregore254f902009-02-04 00:32:51 +00001679 //
1680 // -- If T is a pointer to a data member of class X, its
1681 // associated namespaces and classes are those associated
1682 // with the member type together with those associated with
Mike Stump11289f42009-09-09 15:08:12 +00001683 // X.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001684 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001685 // Handle the type that the pointer to member points to.
1686 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1687 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001688 AssociatedNamespaces,
1689 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001690
1691 // Handle the class type into which this points.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001692 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001693 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1694 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001695 AssociatedNamespaces,
1696 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001697
1698 return;
1699 }
1700
1701 // FIXME: What about block pointers?
1702 // FIXME: What about Objective-C message sends?
1703}
1704
1705/// \brief Find the associated classes and namespaces for
1706/// argument-dependent lookup for a call with the given set of
1707/// arguments.
1708///
1709/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001710/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001711/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001712void
Douglas Gregore254f902009-02-04 00:32:51 +00001713Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1714 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001715 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001716 AssociatedNamespaces.clear();
1717 AssociatedClasses.clear();
1718
1719 // C++ [basic.lookup.koenig]p2:
1720 // For each argument type T in the function call, there is a set
1721 // of zero or more associated namespaces and a set of zero or more
1722 // associated classes to be considered. The sets of namespaces and
1723 // classes is determined entirely by the types of the function
1724 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001725 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001726 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1727 Expr *Arg = Args[ArgIdx];
1728
1729 if (Arg->getType() != Context.OverloadTy) {
1730 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001731 AssociatedNamespaces,
1732 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001733 continue;
1734 }
1735
1736 // [...] In addition, if the argument is the name or address of a
1737 // set of overloaded functions and/or function templates, its
1738 // associated classes and namespaces are the union of those
1739 // associated with each of the members of the set: the namespace
1740 // in which the function or function template is defined and the
1741 // classes and namespaces associated with its (non-dependent)
1742 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001743 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001744 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1745 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1746 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001747
John McCalld14a8642009-11-21 08:51:07 +00001748 // TODO: avoid the copies. This should be easy when the cases
1749 // share a storage implementation.
1750 llvm::SmallVector<NamedDecl*, 8> Functions;
1751
1752 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1753 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00001754 else
Douglas Gregore254f902009-02-04 00:32:51 +00001755 continue;
1756
John McCalld14a8642009-11-21 08:51:07 +00001757 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1758 E = Functions.end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001759 // Look through any using declarations to find the underlying function.
1760 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001761
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001762 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1763 if (!FDecl)
1764 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001765
1766 // Add the classes and namespaces associated with the parameter
1767 // types and return type of this function.
1768 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001769 AssociatedNamespaces,
1770 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001771 }
1772 }
1773}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001774
1775/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1776/// an acceptable non-member overloaded operator for a call whose
1777/// arguments have types T1 (and, if non-empty, T2). This routine
1778/// implements the check in C++ [over.match.oper]p3b2 concerning
1779/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001780static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001781IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1782 QualType T1, QualType T2,
1783 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001784 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1785 return true;
1786
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001787 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1788 return true;
1789
John McCall9dd450b2009-09-21 23:43:11 +00001790 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001791 if (Proto->getNumArgs() < 1)
1792 return false;
1793
1794 if (T1->isEnumeralType()) {
1795 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001796 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001797 return true;
1798 }
1799
1800 if (Proto->getNumArgs() < 2)
1801 return false;
1802
1803 if (!T2.isNull() && T2->isEnumeralType()) {
1804 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001805 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001806 return true;
1807 }
1808
1809 return false;
1810}
1811
John McCall5cebab12009-11-18 07:57:50 +00001812NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1813 LookupNameKind NameKind,
1814 RedeclarationKind Redecl) {
1815 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1816 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00001817 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00001818}
1819
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001820/// \brief Find the protocol with the given name, if any.
1821ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001822 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001823 return cast_or_null<ObjCProtocolDecl>(D);
1824}
1825
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001826void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001827 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00001828 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001829 // C++ [over.match.oper]p3:
1830 // -- The set of non-member candidates is the result of the
1831 // unqualified lookup of operator@ in the context of the
1832 // expression according to the usual rules for name lookup in
1833 // unqualified function calls (3.4.2) except that all member
1834 // functions are ignored. However, if no operand has a class
1835 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001836 // that have a first parameter of type T1 or "reference to
1837 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001838 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001839 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001840 // when T2 is an enumeration type, are candidate functions.
1841 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00001842 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1843 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00001844
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001845 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1846
John McCall9f3059a2009-10-09 21:13:30 +00001847 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001848 return;
1849
1850 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1851 Op != OpEnd; ++Op) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001852 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001853 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
John McCall4c4c1df2010-01-26 03:27:55 +00001854 Functions.addDecl(FD, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001855 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor15448f82009-06-27 21:05:07 +00001856 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1857 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001858 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001859 // later?
1860 if (!FunTmpl->getDeclContext()->isRecord())
John McCall4c4c1df2010-01-26 03:27:55 +00001861 Functions.addDecl(FunTmpl, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00001862 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001863 }
1864}
1865
John McCall8fe68082010-01-26 07:16:45 +00001866void ADLResult::insert(NamedDecl *New) {
1867 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1868
1869 // If we haven't yet seen a decl for this key, or the last decl
1870 // was exactly this one, we're done.
1871 if (Old == 0 || Old == New) {
1872 Old = New;
1873 return;
1874 }
1875
1876 // Otherwise, decide which is a more recent redeclaration.
1877 FunctionDecl *OldFD, *NewFD;
1878 if (isa<FunctionTemplateDecl>(New)) {
1879 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1880 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1881 } else {
1882 OldFD = cast<FunctionDecl>(Old);
1883 NewFD = cast<FunctionDecl>(New);
1884 }
1885
1886 FunctionDecl *Cursor = NewFD;
1887 while (true) {
1888 Cursor = Cursor->getPreviousDeclaration();
1889
1890 // If we got to the end without finding OldFD, OldFD is the newer
1891 // declaration; leave things as they are.
1892 if (!Cursor) return;
1893
1894 // If we do find OldFD, then NewFD is newer.
1895 if (Cursor == OldFD) break;
1896
1897 // Otherwise, keep looking.
1898 }
1899
1900 Old = New;
1901}
1902
Sebastian Redlc057f422009-10-23 19:23:15 +00001903void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001904 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00001905 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001906 // Find all of the associated namespaces and classes based on the
1907 // arguments we have.
1908 AssociatedNamespaceSet AssociatedNamespaces;
1909 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00001910 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00001911 AssociatedNamespaces,
1912 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001913
Sebastian Redlc057f422009-10-23 19:23:15 +00001914 QualType T1, T2;
1915 if (Operator) {
1916 T1 = Args[0]->getType();
1917 if (NumArgs >= 2)
1918 T2 = Args[1]->getType();
1919 }
1920
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001921 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001922 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1923 // and let Y be the lookup set produced by argument dependent
1924 // lookup (defined as follows). If X contains [...] then Y is
1925 // empty. Otherwise Y is the set of declarations found in the
1926 // namespaces associated with the argument types as described
1927 // below. The set of declarations found by the lookup of the name
1928 // is the union of X and Y.
1929 //
1930 // Here, we compute Y and add its members to the overloaded
1931 // candidate set.
1932 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001933 NSEnd = AssociatedNamespaces.end();
1934 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001935 // When considering an associated namespace, the lookup is the
1936 // same as the lookup performed when the associated namespace is
1937 // used as a qualifier (3.4.3.2) except that:
1938 //
1939 // -- Any using-directives in the associated namespace are
1940 // ignored.
1941 //
John McCallc7e8e792009-08-07 22:18:02 +00001942 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001943 // associated classes are visible within their respective
1944 // namespaces even if they are not visible during an ordinary
1945 // lookup (11.4).
1946 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00001947 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00001948 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00001949 // If the only declaration here is an ordinary friend, consider
1950 // it only if it was declared in an associated classes.
1951 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00001952 DeclContext *LexDC = D->getLexicalDeclContext();
1953 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1954 continue;
1955 }
Mike Stump11289f42009-09-09 15:08:12 +00001956
John McCall91f61fc2010-01-26 06:04:06 +00001957 if (isa<UsingShadowDecl>(D))
1958 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00001959
John McCall91f61fc2010-01-26 06:04:06 +00001960 if (isa<FunctionDecl>(D)) {
1961 if (Operator &&
1962 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
1963 T1, T2, Context))
1964 continue;
John McCall8fe68082010-01-26 07:16:45 +00001965 } else if (!isa<FunctionTemplateDecl>(D))
1966 continue;
1967
1968 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00001969 }
1970 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001971}
Douglas Gregor2d435302009-12-30 17:04:44 +00001972
1973//----------------------------------------------------------------------------
1974// Search for all visible declarations.
1975//----------------------------------------------------------------------------
1976VisibleDeclConsumer::~VisibleDeclConsumer() { }
1977
1978namespace {
1979
1980class ShadowContextRAII;
1981
1982class VisibleDeclsRecord {
1983public:
1984 /// \brief An entry in the shadow map, which is optimized to store a
1985 /// single declaration (the common case) but can also store a list
1986 /// of declarations.
1987 class ShadowMapEntry {
1988 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1989
1990 /// \brief Contains either the solitary NamedDecl * or a vector
1991 /// of declarations.
1992 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1993
1994 public:
1995 ShadowMapEntry() : DeclOrVector() { }
1996
1997 void Add(NamedDecl *ND);
1998 void Destroy();
1999
2000 // Iteration.
2001 typedef NamedDecl **iterator;
2002 iterator begin();
2003 iterator end();
2004 };
2005
2006private:
2007 /// \brief A mapping from declaration names to the declarations that have
2008 /// this name within a particular scope.
2009 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2010
2011 /// \brief A list of shadow maps, which is used to model name hiding.
2012 std::list<ShadowMap> ShadowMaps;
2013
2014 /// \brief The declaration contexts we have already visited.
2015 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2016
2017 friend class ShadowContextRAII;
2018
2019public:
2020 /// \brief Determine whether we have already visited this context
2021 /// (and, if not, note that we are going to visit that context now).
2022 bool visitedContext(DeclContext *Ctx) {
2023 return !VisitedContexts.insert(Ctx);
2024 }
2025
2026 /// \brief Determine whether the given declaration is hidden in the
2027 /// current scope.
2028 ///
2029 /// \returns the declaration that hides the given declaration, or
2030 /// NULL if no such declaration exists.
2031 NamedDecl *checkHidden(NamedDecl *ND);
2032
2033 /// \brief Add a declaration to the current shadow map.
2034 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2035};
2036
2037/// \brief RAII object that records when we've entered a shadow context.
2038class ShadowContextRAII {
2039 VisibleDeclsRecord &Visible;
2040
2041 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2042
2043public:
2044 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2045 Visible.ShadowMaps.push_back(ShadowMap());
2046 }
2047
2048 ~ShadowContextRAII() {
2049 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2050 EEnd = Visible.ShadowMaps.back().end();
2051 E != EEnd;
2052 ++E)
2053 E->second.Destroy();
2054
2055 Visible.ShadowMaps.pop_back();
2056 }
2057};
2058
2059} // end anonymous namespace
2060
2061void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2062 if (DeclOrVector.isNull()) {
2063 // 0 - > 1 elements: just set the single element information.
2064 DeclOrVector = ND;
2065 return;
2066 }
2067
2068 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2069 // 1 -> 2 elements: create the vector of results and push in the
2070 // existing declaration.
2071 DeclVector *Vec = new DeclVector;
2072 Vec->push_back(PrevND);
2073 DeclOrVector = Vec;
2074 }
2075
2076 // Add the new element to the end of the vector.
2077 DeclOrVector.get<DeclVector*>()->push_back(ND);
2078}
2079
2080void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2081 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2082 delete Vec;
2083 DeclOrVector = ((NamedDecl *)0);
2084 }
2085}
2086
2087VisibleDeclsRecord::ShadowMapEntry::iterator
2088VisibleDeclsRecord::ShadowMapEntry::begin() {
2089 if (DeclOrVector.isNull())
2090 return 0;
2091
2092 if (DeclOrVector.dyn_cast<NamedDecl *>())
2093 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2094
2095 return DeclOrVector.get<DeclVector *>()->begin();
2096}
2097
2098VisibleDeclsRecord::ShadowMapEntry::iterator
2099VisibleDeclsRecord::ShadowMapEntry::end() {
2100 if (DeclOrVector.isNull())
2101 return 0;
2102
2103 if (DeclOrVector.dyn_cast<NamedDecl *>())
2104 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2105
2106 return DeclOrVector.get<DeclVector *>()->end();
2107}
2108
2109NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002110 // Look through using declarations.
2111 ND = ND->getUnderlyingDecl();
2112
Douglas Gregor2d435302009-12-30 17:04:44 +00002113 unsigned IDNS = ND->getIdentifierNamespace();
2114 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2115 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2116 SM != SMEnd; ++SM) {
2117 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2118 if (Pos == SM->end())
2119 continue;
2120
2121 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2122 IEnd = Pos->second.end();
2123 I != IEnd; ++I) {
2124 // A tag declaration does not hide a non-tag declaration.
2125 if ((*I)->getIdentifierNamespace() == Decl::IDNS_Tag &&
2126 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2127 Decl::IDNS_ObjCProtocol)))
2128 continue;
2129
2130 // Protocols are in distinct namespaces from everything else.
2131 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2132 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2133 (*I)->getIdentifierNamespace() != IDNS)
2134 continue;
2135
Douglas Gregor09bbc652010-01-14 15:47:35 +00002136 // Functions and function templates in the same scope overload
2137 // rather than hide. FIXME: Look for hiding based on function
2138 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002139 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002140 ND->isFunctionOrFunctionTemplate() &&
2141 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002142 continue;
2143
Douglas Gregor2d435302009-12-30 17:04:44 +00002144 // We've found a declaration that hides this one.
2145 return *I;
2146 }
2147 }
2148
2149 return 0;
2150}
2151
2152static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2153 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002154 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002155 VisibleDeclConsumer &Consumer,
2156 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002157 if (!Ctx)
2158 return;
2159
Douglas Gregor2d435302009-12-30 17:04:44 +00002160 // Make sure we don't visit the same context twice.
2161 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2162 return;
2163
2164 // Enumerate all of the results in this context.
2165 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2166 CurCtx = CurCtx->getNextContext()) {
2167 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2168 DEnd = CurCtx->decls_end();
2169 D != DEnd; ++D) {
2170 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2171 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002172 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002173 Visited.add(ND);
2174 }
2175
2176 // Visit transparent contexts inside this context.
2177 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2178 if (InnerCtx->isTransparentContext())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002179 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002180 Consumer, Visited);
2181 }
2182 }
2183 }
2184
2185 // Traverse using directives for qualified name lookup.
2186 if (QualifiedNameLookup) {
2187 ShadowContextRAII Shadow(Visited);
2188 DeclContext::udir_iterator I, E;
2189 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2190 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002191 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002192 }
2193 }
2194
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002195 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002196 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002197 if (!Record->hasDefinition())
2198 return;
2199
Douglas Gregor2d435302009-12-30 17:04:44 +00002200 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2201 BEnd = Record->bases_end();
2202 B != BEnd; ++B) {
2203 QualType BaseType = B->getType();
2204
2205 // Don't look into dependent bases, because name lookup can't look
2206 // there anyway.
2207 if (BaseType->isDependentType())
2208 continue;
2209
2210 const RecordType *Record = BaseType->getAs<RecordType>();
2211 if (!Record)
2212 continue;
2213
2214 // FIXME: It would be nice to be able to determine whether referencing
2215 // a particular member would be ambiguous. For example, given
2216 //
2217 // struct A { int member; };
2218 // struct B { int member; };
2219 // struct C : A, B { };
2220 //
2221 // void f(C *c) { c->### }
2222 //
2223 // accessing 'member' would result in an ambiguity. However, we
2224 // could be smart enough to qualify the member with the base
2225 // class, e.g.,
2226 //
2227 // c->B::member
2228 //
2229 // or
2230 //
2231 // c->A::member
2232
2233 // Find results in this base class (and its bases).
2234 ShadowContextRAII Shadow(Visited);
2235 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002236 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002237 }
2238 }
2239
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002240 // Traverse the contexts of Objective-C classes.
2241 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2242 // Traverse categories.
2243 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2244 Category; Category = Category->getNextClassCategory()) {
2245 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002246 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2247 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002248 }
2249
2250 // Traverse protocols.
2251 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2252 E = IFace->protocol_end(); I != E; ++I) {
2253 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002254 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2255 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002256 }
2257
2258 // Traverse the superclass.
2259 if (IFace->getSuperClass()) {
2260 ShadowContextRAII Shadow(Visited);
2261 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002262 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002263 }
2264 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2265 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2266 E = Protocol->protocol_end(); I != E; ++I) {
2267 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002268 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2269 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002270 }
2271 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2272 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2273 E = Category->protocol_end(); I != E; ++I) {
2274 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002275 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2276 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002277 }
2278 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002279}
2280
2281static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2282 UnqualUsingDirectiveSet &UDirs,
2283 VisibleDeclConsumer &Consumer,
2284 VisibleDeclsRecord &Visited) {
2285 if (!S)
2286 return;
2287
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002288 if (!S->getEntity() || !S->getParent() ||
2289 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2290 // Walk through the declarations in this Scope.
2291 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2292 D != DEnd; ++D) {
2293 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2294 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002295 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002296 Visited.add(ND);
2297 }
2298 }
2299 }
2300
Douglas Gregor66230062010-03-15 14:33:29 +00002301 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002302 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002303 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002304 // Look into this scope's declaration context, along with any of its
2305 // parent lookup contexts (e.g., enclosing classes), up to the point
2306 // where we hit the context stored in the next outer scope.
2307 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002308 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor2d435302009-12-30 17:04:44 +00002309
2310 for (DeclContext *Ctx = Entity; Ctx && Ctx->getPrimaryContext() != OuterCtx;
2311 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002312 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2313 if (Method->isInstanceMethod()) {
2314 // For instance methods, look for ivars in the method's interface.
2315 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2316 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002317 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2318 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2319 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002320 }
2321
2322 // We've already performed all of the name lookup that we need
2323 // to for Objective-C methods; the next context will be the
2324 // outer scope.
2325 break;
2326 }
2327
Douglas Gregor2d435302009-12-30 17:04:44 +00002328 if (Ctx->isFunctionOrMethod())
2329 continue;
2330
2331 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002332 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002333 }
2334 } else if (!S->getParent()) {
2335 // Look into the translation unit scope. We walk through the translation
2336 // unit's declaration context, because the Scope itself won't have all of
2337 // the declarations if we loaded a precompiled header.
2338 // FIXME: We would like the translation unit's Scope object to point to the
2339 // translation unit, so we don't need this special "if" branch. However,
2340 // doing so would force the normal C++ name-lookup code to look into the
2341 // translation unit decl when the IdentifierInfo chains would suffice.
2342 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002343 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002344 Entity = Result.getSema().Context.getTranslationUnitDecl();
2345 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002346 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002347 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002348
2349 if (Entity) {
2350 // Lookup visible declarations in any namespaces found by using
2351 // directives.
2352 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2353 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2354 for (; UI != UEnd; ++UI)
2355 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002356 Result, /*QualifiedNameLookup=*/false,
2357 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002358 }
2359
2360 // Lookup names in the parent scope.
2361 ShadowContextRAII Shadow(Visited);
2362 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2363}
2364
2365void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2366 VisibleDeclConsumer &Consumer) {
2367 // Determine the set of using directives available during
2368 // unqualified name lookup.
2369 Scope *Initial = S;
2370 UnqualUsingDirectiveSet UDirs;
2371 if (getLangOptions().CPlusPlus) {
2372 // Find the first namespace or translation-unit scope.
2373 while (S && !isNamespaceOrTranslationUnitScope(S))
2374 S = S->getParent();
2375
2376 UDirs.visitScopeChain(Initial, S);
2377 }
2378 UDirs.done();
2379
2380 // Look for visible declarations.
2381 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2382 VisibleDeclsRecord Visited;
2383 ShadowContextRAII Shadow(Visited);
2384 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2385}
2386
2387void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2388 VisibleDeclConsumer &Consumer) {
2389 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2390 VisibleDeclsRecord Visited;
2391 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002392 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2393 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002394}
2395
2396//----------------------------------------------------------------------------
2397// Typo correction
2398//----------------------------------------------------------------------------
2399
2400namespace {
2401class TypoCorrectionConsumer : public VisibleDeclConsumer {
2402 /// \brief The name written that is a typo in the source.
2403 llvm::StringRef Typo;
2404
2405 /// \brief The results found that have the smallest edit distance
2406 /// found (so far) with the typo name.
2407 llvm::SmallVector<NamedDecl *, 4> BestResults;
2408
2409 /// \brief The best edit distance found so far.
2410 unsigned BestEditDistance;
2411
2412public:
2413 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2414 : Typo(Typo->getName()) { }
2415
Douglas Gregor09bbc652010-01-14 15:47:35 +00002416 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002417
2418 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2419 iterator begin() const { return BestResults.begin(); }
2420 iterator end() const { return BestResults.end(); }
2421 bool empty() const { return BestResults.empty(); }
2422
2423 unsigned getBestEditDistance() const { return BestEditDistance; }
2424};
2425
2426}
2427
Douglas Gregor09bbc652010-01-14 15:47:35 +00002428void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2429 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002430 // Don't consider hidden names for typo correction.
2431 if (Hiding)
2432 return;
2433
2434 // Only consider entities with identifiers for names, ignoring
2435 // special names (constructors, overloaded operators, selectors,
2436 // etc.).
2437 IdentifierInfo *Name = ND->getIdentifier();
2438 if (!Name)
2439 return;
2440
2441 // Compute the edit distance between the typo and the name of this
2442 // entity. If this edit distance is not worse than the best edit
2443 // distance we've seen so far, add it to the list of results.
2444 unsigned ED = Typo.edit_distance(Name->getName());
2445 if (!BestResults.empty()) {
2446 if (ED < BestEditDistance) {
2447 // This result is better than any we've seen before; clear out
2448 // the previous results.
2449 BestResults.clear();
2450 BestEditDistance = ED;
2451 } else if (ED > BestEditDistance) {
2452 // This result is worse than the best results we've seen so far;
2453 // ignore it.
2454 return;
2455 }
2456 } else
2457 BestEditDistance = ED;
2458
2459 BestResults.push_back(ND);
2460}
2461
2462/// \brief Try to "correct" a typo in the source code by finding
2463/// visible declarations whose names are similar to the name that was
2464/// present in the source code.
2465///
2466/// \param Res the \c LookupResult structure that contains the name
2467/// that was present in the source code along with the name-lookup
2468/// criteria used to search for the name. On success, this structure
2469/// will contain the results of name lookup.
2470///
2471/// \param S the scope in which name lookup occurs.
2472///
2473/// \param SS the nested-name-specifier that precedes the name we're
2474/// looking for, if present.
2475///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002476/// \param MemberContext if non-NULL, the context in which to look for
2477/// a member access expression.
2478///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002479/// \param EnteringContext whether we're entering the context described by
2480/// the nested-name-specifier SS.
2481///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002482/// \param OPT when non-NULL, the search for visible declarations will
2483/// also walk the protocols in the qualified interfaces of \p OPT.
2484///
Douglas Gregor2d435302009-12-30 17:04:44 +00002485/// \returns true if the typo was corrected, in which case the \p Res
2486/// structure will contain the results of name lookup for the
2487/// corrected name. Otherwise, returns false.
2488bool Sema::CorrectTypo(LookupResult &Res, Scope *S, const CXXScopeSpec *SS,
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002489 DeclContext *MemberContext, bool EnteringContext,
2490 const ObjCObjectPointerType *OPT) {
Ted Kremeneke51136e2010-01-06 00:23:04 +00002491 if (Diags.hasFatalErrorOccurred())
2492 return false;
Ted Kremenek54516822010-02-02 02:07:01 +00002493
2494 // Provide a stop gap for files that are just seriously broken. Trying
2495 // to correct all typos can turn into a HUGE performance penalty, causing
2496 // some files to take minutes to get rejected by the parser.
2497 // FIXME: Is this the right solution?
2498 if (TyposCorrected == 20)
2499 return false;
2500 ++TyposCorrected;
Ted Kremeneke51136e2010-01-06 00:23:04 +00002501
Douglas Gregor2d435302009-12-30 17:04:44 +00002502 // We only attempt to correct typos for identifiers.
2503 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2504 if (!Typo)
2505 return false;
2506
2507 // If the scope specifier itself was invalid, don't try to correct
2508 // typos.
2509 if (SS && SS->isInvalid())
2510 return false;
2511
2512 // Never try to correct typos during template deduction or
2513 // instantiation.
2514 if (!ActiveTemplateInstantiations.empty())
2515 return false;
2516
2517 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002518 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002519 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002520
2521 // Look in qualified interfaces.
2522 if (OPT) {
2523 for (ObjCObjectPointerType::qual_iterator
2524 I = OPT->qual_begin(), E = OPT->qual_end();
2525 I != E; ++I)
2526 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2527 }
2528 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002529 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2530 if (!DC)
2531 return false;
2532
2533 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2534 } else {
2535 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2536 }
2537
2538 if (Consumer.empty())
2539 return false;
2540
2541 // Only allow a single, closest name in the result set (it's okay to
2542 // have overloads of that name, though).
2543 TypoCorrectionConsumer::iterator I = Consumer.begin();
2544 DeclarationName BestName = (*I)->getDeclName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002545
2546 // If we've found an Objective-C ivar or property, don't perform
2547 // name lookup again; we'll just return the result directly.
2548 NamedDecl *FoundBest = 0;
2549 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I))
2550 FoundBest = *I;
Douglas Gregor2d435302009-12-30 17:04:44 +00002551 ++I;
2552 for(TypoCorrectionConsumer::iterator IEnd = Consumer.end(); I != IEnd; ++I) {
2553 if (BestName != (*I)->getDeclName())
2554 return false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002555
2556 // FIXME: If there are both ivars and properties of the same name,
2557 // don't return both because the callee can't handle two
2558 // results. We really need to separate ivar lookup from property
2559 // lookup to avoid this problem.
2560 FoundBest = 0;
Douglas Gregor2d435302009-12-30 17:04:44 +00002561 }
2562
2563 // BestName is the closest viable name to what the user
2564 // typed. However, to make sure that we don't pick something that's
2565 // way off, make sure that the user typed at least 3 characters for
2566 // each correction.
2567 unsigned ED = Consumer.getBestEditDistance();
2568 if (ED == 0 || (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
2569 return false;
2570
2571 // Perform name lookup again with the name we chose, and declare
2572 // success if we found something that was not ambiguous.
2573 Res.clear();
2574 Res.setLookupName(BestName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002575
2576 // If we found an ivar or property, add that result; no further
2577 // lookup is required.
2578 if (FoundBest)
2579 Res.addDecl(FoundBest);
2580 // If we're looking into the context of a member, perform qualified
2581 // name lookup on the best name.
2582 else if (MemberContext)
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002583 LookupQualifiedName(Res, MemberContext);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002584 // Perform lookup as if we had just parsed the best name.
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002585 else
2586 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2587 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00002588
2589 if (Res.isAmbiguous()) {
2590 Res.suppressDiagnostics();
2591 return false;
2592 }
2593
2594 return Res.getResultKind() != LookupResult::NotFound;
Douglas Gregor2d435302009-12-30 17:04:44 +00002595}