blob: ddce4a4c23db43e177fdd5101110f84a2888d36b [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 McCall9f3059a2009-10-09 21:13:30 +0000407 CXXBasePaths::paths_iterator I, E;
408 DeclContext::lookup_iterator DI, DE;
409 for (I = P.begin(), E = P.end(); I != E; ++I)
410 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
411 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000412}
413
John McCall5cebab12009-11-18 07:57:50 +0000414void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000415 Paths = new CXXBasePaths;
416 Paths->swap(P);
417 addDeclsFromBasePaths(*Paths);
418 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000419 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000420}
421
John McCall5cebab12009-11-18 07:57:50 +0000422void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000423 Paths = new CXXBasePaths;
424 Paths->swap(P);
425 addDeclsFromBasePaths(*Paths);
426 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000427 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000428}
429
John McCall5cebab12009-11-18 07:57:50 +0000430void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000431 Out << Decls.size() << " result(s)";
432 if (isAmbiguous()) Out << ", ambiguous";
433 if (Paths) Out << ", base paths present";
434
435 for (iterator I = begin(), E = end(); I != E; ++I) {
436 Out << "\n";
437 (*I)->print(Out, 2);
438 }
439}
440
441// Adds all qualifying matches for a name within a decl context to the
442// given lookup result. Returns true if any matches were found.
John McCall5cebab12009-11-18 07:57:50 +0000443static bool LookupDirect(LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000444 bool Found = false;
445
John McCallf6c8a4e2009-11-10 07:01:13 +0000446 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000447 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000448 NamedDecl *D = *I;
449 if (R.isAcceptableDecl(D)) {
450 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000451 Found = true;
452 }
453 }
John McCall9f3059a2009-10-09 21:13:30 +0000454
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000455 if (R.getLookupName().getNameKind()
456 == DeclarationName::CXXConversionFunctionName &&
457 !R.getLookupName().getCXXNameType()->isDependentType() &&
458 isa<CXXRecordDecl>(DC)) {
459 // C++ [temp.mem]p6:
460 // A specialization of a conversion function template is not found by
461 // name lookup. Instead, any conversion function templates visible in the
462 // context of the use are considered. [...]
463 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregor3c96a462010-01-12 01:17:50 +0000464 if (!Record->isDefinition())
465 return Found;
466
John McCallad371252010-01-20 00:46:10 +0000467 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
468 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
469 UEnd = Unresolved->end(); U != UEnd; ++U) {
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000470 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
471 if (!ConvTemplate)
472 continue;
473
474 // When we're performing lookup for the purposes of redeclaration, just
475 // add the conversion function template. When we deduce template
476 // arguments for specializations, we'll end up unifying the return
477 // type of the new declaration with the type of the function template.
478 if (R.isForRedeclaration()) {
479 R.addDecl(ConvTemplate);
480 Found = true;
481 continue;
482 }
483
484 // C++ [temp.mem]p6:
485 // [...] For each such operator, if argument deduction succeeds
486 // (14.9.2.3), the resulting specialization is used as if found by
487 // name lookup.
488 //
489 // When referencing a conversion function for any purpose other than
490 // a redeclaration (such that we'll be building an expression with the
491 // result), perform template argument deduction and place the
492 // specialization into the result set. We do this to avoid forcing all
493 // callers to perform special deduction for conversion functions.
494 Sema::TemplateDeductionInfo Info(R.getSema().Context);
495 FunctionDecl *Specialization = 0;
496
497 const FunctionProtoType *ConvProto
498 = ConvTemplate->getTemplatedDecl()->getType()
499 ->getAs<FunctionProtoType>();
500 assert(ConvProto && "Nonsensical conversion function template type");
501
502 // Compute the type of the function that we would expect the conversion
503 // function to have, if it were to match the name given.
504 // FIXME: Calling convention!
505 QualType ExpectedType
506 = R.getSema().Context.getFunctionType(
507 R.getLookupName().getCXXNameType(),
508 0, 0, ConvProto->isVariadic(),
509 ConvProto->getTypeQuals(),
510 false, false, 0, 0,
511 ConvProto->getNoReturnAttr());
512
513 // Perform template argument deduction against the type that we would
514 // expect the function to have.
515 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
516 Specialization, Info)
517 == Sema::TDK_Success) {
518 R.addDecl(Specialization);
519 Found = true;
520 }
521 }
522 }
523
John McCall9f3059a2009-10-09 21:13:30 +0000524 return Found;
525}
526
John McCallf6c8a4e2009-11-10 07:01:13 +0000527// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000528static bool
John McCall5cebab12009-11-18 07:57:50 +0000529CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCall27b18f82009-11-17 02:14:36 +0000530 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000531
532 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
533
John McCallf6c8a4e2009-11-10 07:01:13 +0000534 // Perform direct name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000535 bool Found = LookupDirect(R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000536
John McCallf6c8a4e2009-11-10 07:01:13 +0000537 // Perform direct name lookup into the namespaces nominated by the
538 // using directives whose common ancestor is this namespace.
539 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
540 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000541
John McCallf6c8a4e2009-11-10 07:01:13 +0000542 for (; UI != UEnd; ++UI)
John McCall27b18f82009-11-17 02:14:36 +0000543 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000544 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000545
546 R.resolveKind();
547
548 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000549}
550
551static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000552 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000553 return Ctx->isFileContext();
554 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000555}
Douglas Gregored8f2882009-01-30 01:04:22 +0000556
Douglas Gregor7f737c02009-09-10 16:57:35 +0000557// Find the next outer declaration context corresponding to this scope.
558static DeclContext *findOuterContext(Scope *S) {
559 for (S = S->getParent(); S; S = S->getParent())
560 if (S->getEntity())
561 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
562
563 return 0;
564}
565
John McCall27b18f82009-11-17 02:14:36 +0000566bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000567 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000568
569 DeclarationName Name = R.getLookupName();
570
Douglas Gregor889ceb72009-02-03 19:21:40 +0000571 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000572 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000573 I = IdResolver.begin(Name),
574 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000575
Douglas Gregor889ceb72009-02-03 19:21:40 +0000576 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000577 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000578 // ...During unqualified name lookup (3.4.1), the names appear as if
579 // they were declared in the nearest enclosing namespace which contains
580 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000581 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000582 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000583 //
584 // For example:
585 // namespace A { int i; }
586 // void foo() {
587 // int i;
588 // {
589 // using namespace A;
590 // ++i; // finds local 'i', A::i appears at global scope
591 // }
592 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000593 //
Douglas Gregor700792c2009-02-05 19:25:20 +0000594 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000595 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000596 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000597 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000598 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000599 Found = true;
600 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000601 }
602 }
John McCall9f3059a2009-10-09 21:13:30 +0000603 if (Found) {
604 R.resolveKind();
605 return true;
606 }
607
Douglas Gregor700792c2009-02-05 19:25:20 +0000608 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregor7f737c02009-09-10 16:57:35 +0000609 DeclContext *OuterCtx = findOuterContext(S);
610 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
611 Ctx = Ctx->getLookupParent()) {
Douglas Gregora64c1e52009-12-08 15:38:36 +0000612 // We do not directly look into function or method contexts
613 // (since all local variables are found via the identifier
614 // changes) or in transparent contexts (since those entities
615 // will be found in the nearest enclosing non-transparent
616 // context).
617 if (Ctx->isFunctionOrMethod() || Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000618 continue;
619
620 // Perform qualified name lookup into this context.
621 // FIXME: In some cases, we know that every name that could be found by
622 // this qualified name lookup will also be on the identifier chain. For
623 // example, inside a class without any base classes, we never need to
624 // perform qualified lookup because all of the members are on top of the
625 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000626 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000627 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000628 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000629 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000630 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000631
John McCallf6c8a4e2009-11-10 07:01:13 +0000632 // Stop if we ran out of scopes.
633 // FIXME: This really, really shouldn't be happening.
634 if (!S) return false;
635
Douglas Gregor700792c2009-02-05 19:25:20 +0000636 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000637 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000638 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000639 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
640 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000641
John McCallf6c8a4e2009-11-10 07:01:13 +0000642 UnqualUsingDirectiveSet UDirs;
643 UDirs.visitScopeChain(Initial, S);
644 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000645
Douglas Gregor700792c2009-02-05 19:25:20 +0000646 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000647 // Unqualified name lookup in C++ requires looking into scopes
648 // that aren't strictly lexical, and therefore we walk through the
649 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000650
Douglas Gregor889ceb72009-02-03 19:21:40 +0000651 for (; S; S = S->getParent()) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000652 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregor88f3eb82010-01-11 22:40:45 +0000653 if (!Ctx || Ctx->isTransparentContext())
Douglas Gregorf2270432009-08-24 18:55:03 +0000654 continue;
655
Douglas Gregor700792c2009-02-05 19:25:20 +0000656 assert(Ctx && Ctx->isFileContext() &&
657 "We should have been looking only at file context here already.");
Douglas Gregor889ceb72009-02-03 19:21:40 +0000658
659 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000660 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000661 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000662 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000663 // We found something. Look for anything else in our scope
664 // with this same name and in an acceptable identifier
665 // namespace, so that we can construct an overload set if we
666 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000667 Found = true;
668 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000669 }
670 }
671
Douglas Gregor700792c2009-02-05 19:25:20 +0000672 // Look into context considering using-directives.
John McCall27b18f82009-11-17 02:14:36 +0000673 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
John McCall9f3059a2009-10-09 21:13:30 +0000674 Found = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000675
John McCall9f3059a2009-10-09 21:13:30 +0000676 if (Found) {
677 R.resolveKind();
678 return true;
679 }
680
John McCall27b18f82009-11-17 02:14:36 +0000681 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000682 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000683 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000684
John McCall9f3059a2009-10-09 21:13:30 +0000685 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000686}
687
Douglas Gregor34074322009-01-14 22:20:51 +0000688/// @brief Perform unqualified name lookup starting from a given
689/// scope.
690///
691/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
692/// used to find names within the current scope. For example, 'x' in
693/// @code
694/// int x;
695/// int f() {
696/// return x; // unqualified name look finds 'x' in the global scope
697/// }
698/// @endcode
699///
700/// Different lookup criteria can find different names. For example, a
701/// particular scope can have both a struct and a function of the same
702/// name, and each can be found by certain lookup criteria. For more
703/// information about lookup criteria, see the documentation for the
704/// class LookupCriteria.
705///
706/// @param S The scope from which unqualified name lookup will
707/// begin. If the lookup criteria permits, name lookup may also search
708/// in the parent scopes.
709///
710/// @param Name The name of the entity that we are searching for.
711///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000712/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000713/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000714/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000715///
716/// @returns The result of name lookup, which includes zero or more
717/// declarations and possibly additional information used to diagnose
718/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000719bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
720 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +0000721 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000722
John McCall27b18f82009-11-17 02:14:36 +0000723 LookupNameKind NameKind = R.getLookupKind();
724
Douglas Gregor34074322009-01-14 22:20:51 +0000725 if (!getLangOptions().CPlusPlus) {
726 // Unqualified name lookup in C/Objective-C is purely lexical, so
727 // search in the declarations attached to the name.
728
John McCallea305ed2009-12-18 10:40:03 +0000729 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000730 // Find the nearest non-transparent declaration scope.
731 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000732 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000733 static_cast<DeclContext *>(S->getEntity())
734 ->isTransparentContext()))
735 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +0000736 }
737
John McCallea305ed2009-12-18 10:40:03 +0000738 unsigned IDNS = R.getIdentifierNamespace();
739
Douglas Gregor34074322009-01-14 22:20:51 +0000740 // Scan up the scope chain looking for a decl that matches this
741 // identifier that is in the appropriate namespace. This search
742 // should not take long, as shadowing of names is uncommon, and
743 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000744 bool LeftStartingScope = false;
745
Douglas Gregored8f2882009-01-30 01:04:22 +0000746 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000747 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000748 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000749 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000750 if (NameKind == LookupRedeclarationWithLinkage) {
751 // Determine whether this (or a previous) declaration is
752 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000753 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000754 LeftStartingScope = true;
755
756 // If we found something outside of our starting scope that
757 // does not have linkage, skip it.
758 if (LeftStartingScope && !((*I)->hasLinkage()))
759 continue;
760 }
761
John McCall9f3059a2009-10-09 21:13:30 +0000762 R.addDecl(*I);
763
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000764 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000765 // If this declaration has the "overloadable" attribute, we
766 // might have a set of overloaded functions.
767
768 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000769 while (!(S->getFlags() & Scope::DeclScope) ||
770 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000771 S = S->getParent();
772
773 // Find the last declaration in this scope (with the same
774 // name, naturally).
775 IdentifierResolver::iterator LastI = I;
776 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000777 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000778 break;
John McCall9f3059a2009-10-09 21:13:30 +0000779 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000780 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000781 }
782
John McCall9f3059a2009-10-09 21:13:30 +0000783 R.resolveKind();
784
785 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000786 }
Douglas Gregor34074322009-01-14 22:20:51 +0000787 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000788 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000789 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +0000790 return true;
Douglas Gregor34074322009-01-14 22:20:51 +0000791 }
792
793 // If we didn't find a use of this identifier, and if the identifier
794 // corresponds to a compiler builtin, create the decl object for the builtin
795 // now, injecting it into translation unit scope, and return it.
Mike Stump11289f42009-09-09 15:08:12 +0000796 if (NameKind == LookupOrdinaryName ||
Douglas Gregoreddf4332009-02-24 20:03:32 +0000797 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor34074322009-01-14 22:20:51 +0000798 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000799 if (II && AllowBuiltinCreation) {
Douglas Gregor34074322009-01-14 22:20:51 +0000800 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000801 if (unsigned BuiltinID = II->getBuiltinID()) {
802 // In C++, we don't have any predefined library functions like
803 // 'malloc'. Instead, we'll just error.
Mike Stump11289f42009-09-09 15:08:12 +0000804 if (getLangOptions().CPlusPlus &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000805 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCall9f3059a2009-10-09 21:13:30 +0000806 return false;
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000807
John McCall9f3059a2009-10-09 21:13:30 +0000808 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCall27b18f82009-11-17 02:14:36 +0000809 S, R.isForRedeclaration(),
810 R.getNameLoc());
John McCall9f3059a2009-10-09 21:13:30 +0000811 if (D) R.addDecl(D);
812 return (D != NULL);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000813 }
Douglas Gregor34074322009-01-14 22:20:51 +0000814 }
Douglas Gregor34074322009-01-14 22:20:51 +0000815 }
John McCall9f3059a2009-10-09 21:13:30 +0000816 return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000817}
818
John McCall6538c932009-10-10 05:48:19 +0000819/// @brief Perform qualified name lookup in the namespaces nominated by
820/// using directives by the given context.
821///
822/// C++98 [namespace.qual]p2:
823/// Given X::m (where X is a user-declared namespace), or given ::m
824/// (where X is the global namespace), let S be the set of all
825/// declarations of m in X and in the transitive closure of all
826/// namespaces nominated by using-directives in X and its used
827/// namespaces, except that using-directives are ignored in any
828/// namespace, including X, directly containing one or more
829/// declarations of m. No namespace is searched more than once in
830/// the lookup of a name. If S is the empty set, the program is
831/// ill-formed. Otherwise, if S has exactly one member, or if the
832/// context of the reference is a using-declaration
833/// (namespace.udecl), S is the required set of declarations of
834/// m. Otherwise if the use of m is not one that allows a unique
835/// declaration to be chosen from S, the program is ill-formed.
836/// C++98 [namespace.qual]p5:
837/// During the lookup of a qualified namespace member name, if the
838/// lookup finds more than one declaration of the member, and if one
839/// declaration introduces a class name or enumeration name and the
840/// other declarations either introduce the same object, the same
841/// enumerator or a set of functions, the non-type name hides the
842/// class or enumeration name if and only if the declarations are
843/// from the same namespace; otherwise (the declarations are from
844/// different namespaces), the program is ill-formed.
John McCall5cebab12009-11-18 07:57:50 +0000845static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +0000846 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +0000847 assert(StartDC->isFileContext() && "start context is not a file context");
848
849 DeclContext::udir_iterator I = StartDC->using_directives_begin();
850 DeclContext::udir_iterator E = StartDC->using_directives_end();
851
852 if (I == E) return false;
853
854 // We have at least added all these contexts to the queue.
855 llvm::DenseSet<DeclContext*> Visited;
856 Visited.insert(StartDC);
857
858 // We have not yet looked into these namespaces, much less added
859 // their "using-children" to the queue.
860 llvm::SmallVector<NamespaceDecl*, 8> Queue;
861
862 // We have already looked into the initial namespace; seed the queue
863 // with its using-children.
864 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +0000865 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +0000866 if (Visited.insert(ND).second)
867 Queue.push_back(ND);
868 }
869
870 // The easiest way to implement the restriction in [namespace.qual]p5
871 // is to check whether any of the individual results found a tag
872 // and, if so, to declare an ambiguity if the final result is not
873 // a tag.
874 bool FoundTag = false;
875 bool FoundNonTag = false;
876
John McCall5cebab12009-11-18 07:57:50 +0000877 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +0000878
879 bool Found = false;
880 while (!Queue.empty()) {
881 NamespaceDecl *ND = Queue.back();
882 Queue.pop_back();
883
884 // We go through some convolutions here to avoid copying results
885 // between LookupResults.
886 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +0000887 LookupResult &DirectR = UseLocal ? LocalR : R;
John McCall27b18f82009-11-17 02:14:36 +0000888 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +0000889
890 if (FoundDirect) {
891 // First do any local hiding.
892 DirectR.resolveKind();
893
894 // If the local result is a tag, remember that.
895 if (DirectR.isSingleTagDecl())
896 FoundTag = true;
897 else
898 FoundNonTag = true;
899
900 // Append the local results to the total results if necessary.
901 if (UseLocal) {
902 R.addAllDecls(LocalR);
903 LocalR.clear();
904 }
905 }
906
907 // If we find names in this namespace, ignore its using directives.
908 if (FoundDirect) {
909 Found = true;
910 continue;
911 }
912
913 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
914 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
915 if (Visited.insert(Nom).second)
916 Queue.push_back(Nom);
917 }
918 }
919
920 if (Found) {
921 if (FoundTag && FoundNonTag)
922 R.setAmbiguousQualifiedTagHiding();
923 else
924 R.resolveKind();
925 }
926
927 return Found;
928}
929
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000930/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +0000931///
932/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
933/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000934/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +0000935///
936/// Different lookup criteria can find different names. For example, a
937/// particular scope can have both a struct and a function of the same
938/// name, and each can be found by certain lookup criteria. For more
939/// information about lookup criteria, see the documentation for the
940/// class LookupCriteria.
941///
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000942/// \param R captures both the lookup criteria and any lookup results found.
943///
944/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +0000945/// search. If the lookup criteria permits, name lookup may also search
946/// in the parent contexts or (for C++ classes) base classes.
947///
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000948/// \param InUnqualifiedLookup true if this is qualified name lookup that
949/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +0000950///
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000951/// \returns true if lookup succeeded, false if it failed.
952bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
953 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +0000954 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +0000955
John McCall27b18f82009-11-17 02:14:36 +0000956 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +0000957 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000958
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000959 // Make sure that the declaration context is complete.
960 assert((!isa<TagDecl>(LookupCtx) ||
961 LookupCtx->isDependentContext() ||
962 cast<TagDecl>(LookupCtx)->isDefinition() ||
963 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
964 ->isBeingDefined()) &&
965 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +0000966
Douglas Gregor34074322009-01-14 22:20:51 +0000967 // Perform qualified name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000968 if (LookupDirect(R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +0000969 R.resolveKind();
970 return true;
971 }
Douglas Gregor34074322009-01-14 22:20:51 +0000972
John McCall6538c932009-10-10 05:48:19 +0000973 // Don't descend into implied contexts for redeclarations.
974 // C++98 [namespace.qual]p6:
975 // In a declaration for a namespace member in which the
976 // declarator-id is a qualified-id, given that the qualified-id
977 // for the namespace member has the form
978 // nested-name-specifier unqualified-id
979 // the unqualified-id shall name a member of the namespace
980 // designated by the nested-name-specifier.
981 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +0000982 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +0000983 return false;
984
John McCall27b18f82009-11-17 02:14:36 +0000985 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +0000986 if (LookupCtx->isFileContext())
John McCall27b18f82009-11-17 02:14:36 +0000987 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +0000988
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000989 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +0000990 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000991 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
992 if (!LookupRec)
John McCall9f3059a2009-10-09 21:13:30 +0000993 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000994
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000995 // If we're performing qualified name lookup into a dependent class,
996 // then we are actually looking into a current instantiation. If we have any
997 // dependent base classes, then we either have to delay lookup until
998 // template instantiation time (at which point all bases will be available)
999 // or we have to fail.
1000 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1001 LookupRec->hasAnyDependentBases()) {
1002 R.setNotFoundInCurrentInstantiation();
1003 return false;
1004 }
1005
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001006 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001007 CXXBasePaths Paths;
1008 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001009
1010 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001011 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001012 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001013 case LookupOrdinaryName:
1014 case LookupMemberName:
1015 case LookupRedeclarationWithLinkage:
1016 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1017 break;
1018
1019 case LookupTagName:
1020 BaseCallback = &CXXRecordDecl::FindTagMember;
1021 break;
John McCall84d87672009-12-10 09:41:52 +00001022
1023 case LookupUsingDeclName:
1024 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001025
1026 case LookupOperatorName:
1027 case LookupNamespaceName:
1028 case LookupObjCProtocolName:
1029 case LookupObjCImplementationName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001030 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001031 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001032
1033 case LookupNestedNameSpecifierName:
1034 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1035 break;
1036 }
1037
John McCall27b18f82009-11-17 02:14:36 +00001038 if (!LookupRec->lookupInBases(BaseCallback,
1039 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001040 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001041
1042 // C++ [class.member.lookup]p2:
1043 // [...] If the resulting set of declarations are not all from
1044 // sub-objects of the same type, or the set has a nonstatic member
1045 // and includes members from distinct sub-objects, there is an
1046 // ambiguity and the program is ill-formed. Otherwise that set is
1047 // the result of the lookup.
1048 // FIXME: support using declarations!
1049 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001050 int SubobjectNumber = 0;
John McCall401982f2010-01-20 21:53:11 +00001051 AccessSpecifier SubobjectAccess = AS_private;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001052 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001053 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001054 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001055
John McCall401982f2010-01-20 21:53:11 +00001056 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1057 // across all paths.
1058 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1059
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001060 // Determine whether we're looking at a distinct sub-object or not.
1061 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001062 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001063 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1064 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001065 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001066 != Context.getCanonicalType(PathElement.Base->getType())) {
1067 // We found members of the given name in two subobjects of
1068 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001069 R.setAmbiguousBaseSubobjectTypes(Paths);
1070 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001071 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1072 // We have a different subobject of the same type.
1073
1074 // C++ [class.member.lookup]p5:
1075 // A static member, a nested type or an enumerator defined in
1076 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001077 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001078 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001079 if (isa<VarDecl>(FirstDecl) ||
1080 isa<TypeDecl>(FirstDecl) ||
1081 isa<EnumConstantDecl>(FirstDecl))
1082 continue;
1083
1084 if (isa<CXXMethodDecl>(FirstDecl)) {
1085 // Determine whether all of the methods are static.
1086 bool AllMethodsAreStatic = true;
1087 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1088 Func != Path->Decls.second; ++Func) {
1089 if (!isa<CXXMethodDecl>(*Func)) {
1090 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1091 break;
1092 }
1093
1094 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1095 AllMethodsAreStatic = false;
1096 break;
1097 }
1098 }
1099
1100 if (AllMethodsAreStatic)
1101 continue;
1102 }
1103
1104 // We have found a nonstatic member name in multiple, distinct
1105 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001106 R.setAmbiguousBaseSubobjects(Paths);
1107 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001108 }
1109 }
1110
1111 // Lookup in a base class succeeded; return these results.
1112
John McCall9f3059a2009-10-09 21:13:30 +00001113 DeclContext::lookup_iterator I, E;
1114 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I)
John McCall401982f2010-01-20 21:53:11 +00001115 R.addDecl(*I, std::max(SubobjectAccess, (*I)->getAccess()));
John McCall9f3059a2009-10-09 21:13:30 +00001116 R.resolveKind();
1117 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001118}
1119
1120/// @brief Performs name lookup for a name that was parsed in the
1121/// source code, and may contain a C++ scope specifier.
1122///
1123/// This routine is a convenience routine meant to be called from
1124/// contexts that receive a name and an optional C++ scope specifier
1125/// (e.g., "N::M::x"). It will then perform either qualified or
1126/// unqualified name lookup (with LookupQualifiedName or LookupName,
1127/// respectively) on the given name and return those results.
1128///
1129/// @param S The scope from which unqualified name lookup will
1130/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001131///
Douglas Gregore861bac2009-08-25 22:51:20 +00001132/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001133///
1134/// @param Name The name of the entity that name lookup will
1135/// search for.
1136///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001137/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001138/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001139/// C library functions (like "malloc") are implicitly declared.
1140///
Douglas Gregore861bac2009-08-25 22:51:20 +00001141/// @param EnteringContext Indicates whether we are going to enter the
1142/// context of the scope-specifier SS (if present).
1143///
John McCall9f3059a2009-10-09 21:13:30 +00001144/// @returns True if any decls were found (but possibly ambiguous)
1145bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001146 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001147 if (SS && SS->isInvalid()) {
1148 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001149 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001150 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001151 }
Mike Stump11289f42009-09-09 15:08:12 +00001152
Douglas Gregore861bac2009-08-25 22:51:20 +00001153 if (SS && SS->isSet()) {
1154 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001155 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001156 // contex, and will perform name lookup in that context.
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001157 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCall9f3059a2009-10-09 21:13:30 +00001158 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001159
John McCall27b18f82009-11-17 02:14:36 +00001160 R.setContextRange(SS->getRange());
1161
1162 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001163 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001164
Douglas Gregore861bac2009-08-25 22:51:20 +00001165 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001166 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001167 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001168 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001169 }
1170
Mike Stump11289f42009-09-09 15:08:12 +00001171 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001172 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001173}
1174
Douglas Gregor889ceb72009-02-03 19:21:40 +00001175
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001176/// @brief Produce a diagnostic describing the ambiguity that resulted
1177/// from name lookup.
1178///
1179/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001180///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001181/// @param Name The name of the entity that name lookup was
1182/// searching for.
1183///
1184/// @param NameLoc The location of the name within the source code.
1185///
1186/// @param LookupRange A source range that provides more
1187/// source-location information concerning the lookup itself. For
1188/// example, this range might highlight a nested-name-specifier that
1189/// precedes the name.
1190///
1191/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001192bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001193 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1194
John McCall27b18f82009-11-17 02:14:36 +00001195 DeclarationName Name = Result.getLookupName();
1196 SourceLocation NameLoc = Result.getNameLoc();
1197 SourceRange LookupRange = Result.getContextRange();
1198
John McCall6538c932009-10-10 05:48:19 +00001199 switch (Result.getAmbiguityKind()) {
1200 case LookupResult::AmbiguousBaseSubobjects: {
1201 CXXBasePaths *Paths = Result.getBasePaths();
1202 QualType SubobjectType = Paths->front().back().Base->getType();
1203 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1204 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1205 << LookupRange;
1206
1207 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1208 while (isa<CXXMethodDecl>(*Found) &&
1209 cast<CXXMethodDecl>(*Found)->isStatic())
1210 ++Found;
1211
1212 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1213
1214 return true;
1215 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001216
John McCall6538c932009-10-10 05:48:19 +00001217 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001218 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1219 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001220
1221 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001222 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001223 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1224 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001225 Path != PathEnd; ++Path) {
1226 Decl *D = *Path->Decls.first;
1227 if (DeclsPrinted.insert(D).second)
1228 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1229 }
1230
Douglas Gregor1c846b02009-01-16 00:38:09 +00001231 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001232 }
1233
John McCall6538c932009-10-10 05:48:19 +00001234 case LookupResult::AmbiguousTagHiding: {
1235 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001236
John McCall6538c932009-10-10 05:48:19 +00001237 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1238
1239 LookupResult::iterator DI, DE = Result.end();
1240 for (DI = Result.begin(); DI != DE; ++DI)
1241 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1242 TagDecls.insert(TD);
1243 Diag(TD->getLocation(), diag::note_hidden_tag);
1244 }
1245
1246 for (DI = Result.begin(); DI != DE; ++DI)
1247 if (!isa<TagDecl>(*DI))
1248 Diag((*DI)->getLocation(), diag::note_hiding_object);
1249
1250 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001251 LookupResult::Filter F = Result.makeFilter();
1252 while (F.hasNext()) {
1253 if (TagDecls.count(F.next()))
1254 F.erase();
1255 }
1256 F.done();
John McCall6538c932009-10-10 05:48:19 +00001257
1258 return true;
1259 }
1260
1261 case LookupResult::AmbiguousReference: {
1262 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001263
John McCall6538c932009-10-10 05:48:19 +00001264 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1265 for (; DI != DE; ++DI)
1266 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001267
John McCall6538c932009-10-10 05:48:19 +00001268 return true;
1269 }
1270 }
1271
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001272 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001273 return true;
1274}
Douglas Gregore254f902009-02-04 00:32:51 +00001275
Mike Stump11289f42009-09-09 15:08:12 +00001276static void
1277addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001278 ASTContext &Context,
1279 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001280 Sema::AssociatedClassSet &AssociatedClasses);
1281
1282static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1283 DeclContext *Ctx) {
1284 if (Ctx->isFileContext())
1285 Namespaces.insert(Ctx);
1286}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001287
Mike Stump11289f42009-09-09 15:08:12 +00001288// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001289// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001290static void
1291addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001292 ASTContext &Context,
1293 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001294 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001295 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001296 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001297 switch (Arg.getKind()) {
1298 case TemplateArgument::Null:
1299 break;
Mike Stump11289f42009-09-09 15:08:12 +00001300
Douglas Gregor197e5f72009-07-08 07:51:57 +00001301 case TemplateArgument::Type:
1302 // [...] the namespaces and classes associated with the types of the
1303 // template arguments provided for template type parameters (excluding
1304 // template template parameters)
1305 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1306 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001307 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001308 break;
Mike Stump11289f42009-09-09 15:08:12 +00001309
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001310 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001311 // [...] the namespaces in which any template template arguments are
1312 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001313 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001314 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001315 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001316 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001317 DeclContext *Ctx = ClassTemplate->getDeclContext();
1318 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1319 AssociatedClasses.insert(EnclosingClass);
1320 // Add the associated namespace for this class.
1321 while (Ctx->isRecord())
1322 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001323 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001324 }
1325 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001326 }
1327
1328 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001329 case TemplateArgument::Integral:
1330 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001331 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001332 // associated namespaces. ]
1333 break;
Mike Stump11289f42009-09-09 15:08:12 +00001334
Douglas Gregor197e5f72009-07-08 07:51:57 +00001335 case TemplateArgument::Pack:
1336 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1337 PEnd = Arg.pack_end();
1338 P != PEnd; ++P)
1339 addAssociatedClassesAndNamespaces(*P, Context,
1340 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001341 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001342 break;
1343 }
1344}
1345
Douglas Gregore254f902009-02-04 00:32:51 +00001346// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001347// argument-dependent lookup with an argument of class type
1348// (C++ [basic.lookup.koenig]p2).
1349static void
1350addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregore254f902009-02-04 00:32:51 +00001351 ASTContext &Context,
1352 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001353 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001354 // C++ [basic.lookup.koenig]p2:
1355 // [...]
1356 // -- If T is a class type (including unions), its associated
1357 // classes are: the class itself; the class of which it is a
1358 // member, if any; and its direct and indirect base
1359 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001360 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001361
1362 // Add the class of which it is a member, if any.
1363 DeclContext *Ctx = Class->getDeclContext();
1364 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1365 AssociatedClasses.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001366 // Add the associated namespace for this class.
1367 while (Ctx->isRecord())
1368 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001369 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001370
Douglas Gregore254f902009-02-04 00:32:51 +00001371 // Add the class itself. If we've already seen this class, we don't
1372 // need to visit base classes.
1373 if (!AssociatedClasses.insert(Class))
1374 return;
1375
Mike Stump11289f42009-09-09 15:08:12 +00001376 // -- If T is a template-id, its associated namespaces and classes are
1377 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001378 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001379 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001380 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001381 // namespaces in which any template template arguments are defined; and
1382 // the classes in which any member templates used as template template
1383 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001384 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001385 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001386 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1387 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1388 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1389 AssociatedClasses.insert(EnclosingClass);
1390 // Add the associated namespace for this class.
1391 while (Ctx->isRecord())
1392 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001393 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001394
Douglas Gregor197e5f72009-07-08 07:51:57 +00001395 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1396 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1397 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1398 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001399 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001400 }
Mike Stump11289f42009-09-09 15:08:12 +00001401
Douglas Gregore254f902009-02-04 00:32:51 +00001402 // Add direct and indirect base classes along with their associated
1403 // namespaces.
1404 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1405 Bases.push_back(Class);
1406 while (!Bases.empty()) {
1407 // Pop this class off the stack.
1408 Class = Bases.back();
1409 Bases.pop_back();
1410
1411 // Visit the base classes.
1412 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1413 BaseEnd = Class->bases_end();
1414 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001415 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001416 // In dependent contexts, we do ADL twice, and the first time around,
1417 // the base type might be a dependent TemplateSpecializationType, or a
1418 // TemplateTypeParmType. If that happens, simply ignore it.
1419 // FIXME: If we want to support export, we probably need to add the
1420 // namespace of the template in a TemplateSpecializationType, or even
1421 // the classes and namespaces of known non-dependent arguments.
1422 if (!BaseType)
1423 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001424 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1425 if (AssociatedClasses.insert(BaseDecl)) {
1426 // Find the associated namespace for this base class.
1427 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1428 while (BaseCtx->isRecord())
1429 BaseCtx = BaseCtx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001430 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001431
1432 // Make sure we visit the bases of this base class.
1433 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1434 Bases.push_back(BaseDecl);
1435 }
1436 }
1437 }
1438}
1439
1440// \brief Add the associated classes and namespaces for
1441// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001442// (C++ [basic.lookup.koenig]p2).
1443static void
1444addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregore254f902009-02-04 00:32:51 +00001445 ASTContext &Context,
1446 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001447 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001448 // C++ [basic.lookup.koenig]p2:
1449 //
1450 // For each argument type T in the function call, there is a set
1451 // of zero or more associated namespaces and a set of zero or more
1452 // associated classes to be considered. The sets of namespaces and
1453 // classes is determined entirely by the types of the function
1454 // arguments (and the namespace of any template template
1455 // argument). Typedef names and using-declarations used to specify
1456 // the types do not contribute to this set. The sets of namespaces
1457 // and classes are determined in the following way:
1458 T = Context.getCanonicalType(T).getUnqualifiedType();
1459
1460 // -- If T is a pointer to U or an array of U, its associated
Mike Stump11289f42009-09-09 15:08:12 +00001461 // namespaces and classes are those associated with U.
Douglas Gregore254f902009-02-04 00:32:51 +00001462 //
1463 // We handle this by unwrapping pointer and array types immediately,
1464 // to avoid unnecessary recursion.
1465 while (true) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001466 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001467 T = Ptr->getPointeeType();
1468 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1469 T = Ptr->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001470 else
Douglas Gregore254f902009-02-04 00:32:51 +00001471 break;
1472 }
1473
1474 // -- If T is a fundamental type, its associated sets of
1475 // namespaces and classes are both empty.
John McCall9dd450b2009-09-21 23:43:11 +00001476 if (T->getAs<BuiltinType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001477 return;
1478
1479 // -- If T is a class type (including unions), its associated
1480 // classes are: the class itself; the class of which it is a
1481 // member, if any; and its direct and indirect base
1482 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001483 // which its associated classes are defined.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001484 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump11289f42009-09-09 15:08:12 +00001485 if (CXXRecordDecl *ClassDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001486 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001487 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1488 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001489 AssociatedClasses);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001490 return;
1491 }
Douglas Gregore254f902009-02-04 00:32:51 +00001492
1493 // -- If T is an enumeration type, its associated namespace is
1494 // the namespace in which it is defined. If it is class
1495 // member, its associated class is the member’s class; else
Mike Stump11289f42009-09-09 15:08:12 +00001496 // it has no associated class.
John McCall9dd450b2009-09-21 23:43:11 +00001497 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001498 EnumDecl *Enum = EnumT->getDecl();
1499
1500 DeclContext *Ctx = Enum->getDeclContext();
1501 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1502 AssociatedClasses.insert(EnclosingClass);
1503
1504 // Add the associated namespace for this class.
1505 while (Ctx->isRecord())
1506 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001507 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001508
1509 return;
1510 }
1511
1512 // -- If T is a function type, its associated namespaces and
1513 // classes are those associated with the function parameter
1514 // types and those associated with the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001515 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001516 // Return type
John McCall9dd450b2009-09-21 23:43:11 +00001517 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregore254f902009-02-04 00:32:51 +00001518 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001519 AssociatedNamespaces, AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001520
John McCall9dd450b2009-09-21 23:43:11 +00001521 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregore254f902009-02-04 00:32:51 +00001522 if (!Proto)
1523 return;
1524
1525 // Argument types
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001526 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001527 ArgEnd = Proto->arg_type_end();
Douglas Gregore254f902009-02-04 00:32:51 +00001528 Arg != ArgEnd; ++Arg)
1529 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallc7e8e792009-08-07 22:18:02 +00001530 AssociatedNamespaces, AssociatedClasses);
Mike Stump11289f42009-09-09 15:08:12 +00001531
Douglas Gregore254f902009-02-04 00:32:51 +00001532 return;
1533 }
1534
1535 // -- If T is a pointer to a member function of a class X, its
1536 // associated namespaces and classes are those associated
1537 // with the function parameter types and return type,
Mike Stump11289f42009-09-09 15:08:12 +00001538 // together with those associated with X.
Douglas Gregore254f902009-02-04 00:32:51 +00001539 //
1540 // -- If T is a pointer to a data member of class X, its
1541 // associated namespaces and classes are those associated
1542 // with the member type together with those associated with
Mike Stump11289f42009-09-09 15:08:12 +00001543 // X.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001544 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001545 // Handle the type that the pointer to member points to.
1546 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1547 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001548 AssociatedNamespaces,
1549 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001550
1551 // Handle the class type into which this points.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001552 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001553 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1554 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001555 AssociatedNamespaces,
1556 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001557
1558 return;
1559 }
1560
1561 // FIXME: What about block pointers?
1562 // FIXME: What about Objective-C message sends?
1563}
1564
1565/// \brief Find the associated classes and namespaces for
1566/// argument-dependent lookup for a call with the given set of
1567/// arguments.
1568///
1569/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001570/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001571/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001572void
Douglas Gregore254f902009-02-04 00:32:51 +00001573Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1574 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001575 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001576 AssociatedNamespaces.clear();
1577 AssociatedClasses.clear();
1578
1579 // C++ [basic.lookup.koenig]p2:
1580 // For each argument type T in the function call, there is a set
1581 // of zero or more associated namespaces and a set of zero or more
1582 // associated classes to be considered. The sets of namespaces and
1583 // classes is determined entirely by the types of the function
1584 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001585 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001586 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1587 Expr *Arg = Args[ArgIdx];
1588
1589 if (Arg->getType() != Context.OverloadTy) {
1590 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001591 AssociatedNamespaces,
1592 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001593 continue;
1594 }
1595
1596 // [...] In addition, if the argument is the name or address of a
1597 // set of overloaded functions and/or function templates, its
1598 // associated classes and namespaces are the union of those
1599 // associated with each of the members of the set: the namespace
1600 // in which the function or function template is defined and the
1601 // classes and namespaces associated with its (non-dependent)
1602 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001603 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001604 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1605 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1606 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001607
John McCalld14a8642009-11-21 08:51:07 +00001608 // TODO: avoid the copies. This should be easy when the cases
1609 // share a storage implementation.
1610 llvm::SmallVector<NamedDecl*, 8> Functions;
1611
1612 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1613 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00001614 else
Douglas Gregore254f902009-02-04 00:32:51 +00001615 continue;
1616
John McCalld14a8642009-11-21 08:51:07 +00001617 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1618 E = Functions.end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001619 // Look through any using declarations to find the underlying function.
1620 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001621
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001622 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1623 if (!FDecl)
1624 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001625
1626 // Add the classes and namespaces associated with the parameter
1627 // types and return type of this function.
1628 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001629 AssociatedNamespaces,
1630 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001631 }
1632 }
1633}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001634
1635/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1636/// an acceptable non-member overloaded operator for a call whose
1637/// arguments have types T1 (and, if non-empty, T2). This routine
1638/// implements the check in C++ [over.match.oper]p3b2 concerning
1639/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001640static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001641IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1642 QualType T1, QualType T2,
1643 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001644 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1645 return true;
1646
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001647 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1648 return true;
1649
John McCall9dd450b2009-09-21 23:43:11 +00001650 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001651 if (Proto->getNumArgs() < 1)
1652 return false;
1653
1654 if (T1->isEnumeralType()) {
1655 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001656 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001657 return true;
1658 }
1659
1660 if (Proto->getNumArgs() < 2)
1661 return false;
1662
1663 if (!T2.isNull() && T2->isEnumeralType()) {
1664 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001665 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001666 return true;
1667 }
1668
1669 return false;
1670}
1671
John McCall5cebab12009-11-18 07:57:50 +00001672NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1673 LookupNameKind NameKind,
1674 RedeclarationKind Redecl) {
1675 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1676 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00001677 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00001678}
1679
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001680/// \brief Find the protocol with the given name, if any.
1681ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001682 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001683 return cast_or_null<ObjCProtocolDecl>(D);
1684}
1685
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001686void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001687 QualType T1, QualType T2,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001688 FunctionSet &Functions) {
1689 // C++ [over.match.oper]p3:
1690 // -- The set of non-member candidates is the result of the
1691 // unqualified lookup of operator@ in the context of the
1692 // expression according to the usual rules for name lookup in
1693 // unqualified function calls (3.4.2) except that all member
1694 // functions are ignored. However, if no operand has a class
1695 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001696 // that have a first parameter of type T1 or "reference to
1697 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001698 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001699 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001700 // when T2 is an enumeration type, are candidate functions.
1701 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00001702 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1703 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00001704
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001705 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1706
John McCall9f3059a2009-10-09 21:13:30 +00001707 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001708 return;
1709
1710 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1711 Op != OpEnd; ++Op) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001712 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001713 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1714 Functions.insert(FD); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001715 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor15448f82009-06-27 21:05:07 +00001716 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1717 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001718 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001719 // later?
1720 if (!FunTmpl->getDeclContext()->isRecord())
1721 Functions.insert(FunTmpl);
1722 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001723 }
1724}
1725
John McCallc7e8e792009-08-07 22:18:02 +00001726static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1727 Decl *D) {
1728 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1729 Functions.insert(Func);
1730 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1731 Functions.insert(FunTmpl);
1732}
1733
Sebastian Redlc057f422009-10-23 19:23:15 +00001734void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001735 Expr **Args, unsigned NumArgs,
1736 FunctionSet &Functions) {
1737 // Find all of the associated namespaces and classes based on the
1738 // arguments we have.
1739 AssociatedNamespaceSet AssociatedNamespaces;
1740 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00001741 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00001742 AssociatedNamespaces,
1743 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001744
Sebastian Redlc057f422009-10-23 19:23:15 +00001745 QualType T1, T2;
1746 if (Operator) {
1747 T1 = Args[0]->getType();
1748 if (NumArgs >= 2)
1749 T2 = Args[1]->getType();
1750 }
1751
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001752 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001753 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1754 // and let Y be the lookup set produced by argument dependent
1755 // lookup (defined as follows). If X contains [...] then Y is
1756 // empty. Otherwise Y is the set of declarations found in the
1757 // namespaces associated with the argument types as described
1758 // below. The set of declarations found by the lookup of the name
1759 // is the union of X and Y.
1760 //
1761 // Here, we compute Y and add its members to the overloaded
1762 // candidate set.
1763 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001764 NSEnd = AssociatedNamespaces.end();
1765 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001766 // When considering an associated namespace, the lookup is the
1767 // same as the lookup performed when the associated namespace is
1768 // used as a qualifier (3.4.3.2) except that:
1769 //
1770 // -- Any using-directives in the associated namespace are
1771 // ignored.
1772 //
John McCallc7e8e792009-08-07 22:18:02 +00001773 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001774 // associated classes are visible within their respective
1775 // namespaces even if they are not visible during an ordinary
1776 // lookup (11.4).
1777 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00001778 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCallc7e8e792009-08-07 22:18:02 +00001779 Decl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00001780 // If the only declaration here is an ordinary friend, consider
1781 // it only if it was declared in an associated classes.
1782 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00001783 DeclContext *LexDC = D->getLexicalDeclContext();
1784 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1785 continue;
1786 }
Mike Stump11289f42009-09-09 15:08:12 +00001787
Sebastian Redlc057f422009-10-23 19:23:15 +00001788 FunctionDecl *Fn;
1789 if (!Operator || !(Fn = dyn_cast<FunctionDecl>(D)) ||
1790 IsAcceptableNonMemberOperatorCandidate(Fn, T1, T2, Context))
1791 CollectFunctionDecl(Functions, D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00001792 }
1793 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001794}
Douglas Gregor2d435302009-12-30 17:04:44 +00001795
1796//----------------------------------------------------------------------------
1797// Search for all visible declarations.
1798//----------------------------------------------------------------------------
1799VisibleDeclConsumer::~VisibleDeclConsumer() { }
1800
1801namespace {
1802
1803class ShadowContextRAII;
1804
1805class VisibleDeclsRecord {
1806public:
1807 /// \brief An entry in the shadow map, which is optimized to store a
1808 /// single declaration (the common case) but can also store a list
1809 /// of declarations.
1810 class ShadowMapEntry {
1811 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1812
1813 /// \brief Contains either the solitary NamedDecl * or a vector
1814 /// of declarations.
1815 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1816
1817 public:
1818 ShadowMapEntry() : DeclOrVector() { }
1819
1820 void Add(NamedDecl *ND);
1821 void Destroy();
1822
1823 // Iteration.
1824 typedef NamedDecl **iterator;
1825 iterator begin();
1826 iterator end();
1827 };
1828
1829private:
1830 /// \brief A mapping from declaration names to the declarations that have
1831 /// this name within a particular scope.
1832 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
1833
1834 /// \brief A list of shadow maps, which is used to model name hiding.
1835 std::list<ShadowMap> ShadowMaps;
1836
1837 /// \brief The declaration contexts we have already visited.
1838 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
1839
1840 friend class ShadowContextRAII;
1841
1842public:
1843 /// \brief Determine whether we have already visited this context
1844 /// (and, if not, note that we are going to visit that context now).
1845 bool visitedContext(DeclContext *Ctx) {
1846 return !VisitedContexts.insert(Ctx);
1847 }
1848
1849 /// \brief Determine whether the given declaration is hidden in the
1850 /// current scope.
1851 ///
1852 /// \returns the declaration that hides the given declaration, or
1853 /// NULL if no such declaration exists.
1854 NamedDecl *checkHidden(NamedDecl *ND);
1855
1856 /// \brief Add a declaration to the current shadow map.
1857 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
1858};
1859
1860/// \brief RAII object that records when we've entered a shadow context.
1861class ShadowContextRAII {
1862 VisibleDeclsRecord &Visible;
1863
1864 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
1865
1866public:
1867 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
1868 Visible.ShadowMaps.push_back(ShadowMap());
1869 }
1870
1871 ~ShadowContextRAII() {
1872 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
1873 EEnd = Visible.ShadowMaps.back().end();
1874 E != EEnd;
1875 ++E)
1876 E->second.Destroy();
1877
1878 Visible.ShadowMaps.pop_back();
1879 }
1880};
1881
1882} // end anonymous namespace
1883
1884void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
1885 if (DeclOrVector.isNull()) {
1886 // 0 - > 1 elements: just set the single element information.
1887 DeclOrVector = ND;
1888 return;
1889 }
1890
1891 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
1892 // 1 -> 2 elements: create the vector of results and push in the
1893 // existing declaration.
1894 DeclVector *Vec = new DeclVector;
1895 Vec->push_back(PrevND);
1896 DeclOrVector = Vec;
1897 }
1898
1899 // Add the new element to the end of the vector.
1900 DeclOrVector.get<DeclVector*>()->push_back(ND);
1901}
1902
1903void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
1904 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
1905 delete Vec;
1906 DeclOrVector = ((NamedDecl *)0);
1907 }
1908}
1909
1910VisibleDeclsRecord::ShadowMapEntry::iterator
1911VisibleDeclsRecord::ShadowMapEntry::begin() {
1912 if (DeclOrVector.isNull())
1913 return 0;
1914
1915 if (DeclOrVector.dyn_cast<NamedDecl *>())
1916 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
1917
1918 return DeclOrVector.get<DeclVector *>()->begin();
1919}
1920
1921VisibleDeclsRecord::ShadowMapEntry::iterator
1922VisibleDeclsRecord::ShadowMapEntry::end() {
1923 if (DeclOrVector.isNull())
1924 return 0;
1925
1926 if (DeclOrVector.dyn_cast<NamedDecl *>())
1927 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
1928
1929 return DeclOrVector.get<DeclVector *>()->end();
1930}
1931
1932NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00001933 // Look through using declarations.
1934 ND = ND->getUnderlyingDecl();
1935
Douglas Gregor2d435302009-12-30 17:04:44 +00001936 unsigned IDNS = ND->getIdentifierNamespace();
1937 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
1938 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
1939 SM != SMEnd; ++SM) {
1940 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
1941 if (Pos == SM->end())
1942 continue;
1943
1944 for (ShadowMapEntry::iterator I = Pos->second.begin(),
1945 IEnd = Pos->second.end();
1946 I != IEnd; ++I) {
1947 // A tag declaration does not hide a non-tag declaration.
1948 if ((*I)->getIdentifierNamespace() == Decl::IDNS_Tag &&
1949 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
1950 Decl::IDNS_ObjCProtocol)))
1951 continue;
1952
1953 // Protocols are in distinct namespaces from everything else.
1954 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
1955 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
1956 (*I)->getIdentifierNamespace() != IDNS)
1957 continue;
1958
Douglas Gregor09bbc652010-01-14 15:47:35 +00001959 // Functions and function templates in the same scope overload
1960 // rather than hide. FIXME: Look for hiding based on function
1961 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00001962 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00001963 ND->isFunctionOrFunctionTemplate() &&
1964 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00001965 continue;
1966
Douglas Gregor2d435302009-12-30 17:04:44 +00001967 // We've found a declaration that hides this one.
1968 return *I;
1969 }
1970 }
1971
1972 return 0;
1973}
1974
1975static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
1976 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00001977 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00001978 VisibleDeclConsumer &Consumer,
1979 VisibleDeclsRecord &Visited) {
1980 // Make sure we don't visit the same context twice.
1981 if (Visited.visitedContext(Ctx->getPrimaryContext()))
1982 return;
1983
1984 // Enumerate all of the results in this context.
1985 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
1986 CurCtx = CurCtx->getNextContext()) {
1987 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
1988 DEnd = CurCtx->decls_end();
1989 D != DEnd; ++D) {
1990 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
1991 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00001992 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00001993 Visited.add(ND);
1994 }
1995
1996 // Visit transparent contexts inside this context.
1997 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
1998 if (InnerCtx->isTransparentContext())
Douglas Gregor09bbc652010-01-14 15:47:35 +00001999 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002000 Consumer, Visited);
2001 }
2002 }
2003 }
2004
2005 // Traverse using directives for qualified name lookup.
2006 if (QualifiedNameLookup) {
2007 ShadowContextRAII Shadow(Visited);
2008 DeclContext::udir_iterator I, E;
2009 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2010 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002011 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002012 }
2013 }
2014
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002015 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002016 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
2017 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2018 BEnd = Record->bases_end();
2019 B != BEnd; ++B) {
2020 QualType BaseType = B->getType();
2021
2022 // Don't look into dependent bases, because name lookup can't look
2023 // there anyway.
2024 if (BaseType->isDependentType())
2025 continue;
2026
2027 const RecordType *Record = BaseType->getAs<RecordType>();
2028 if (!Record)
2029 continue;
2030
2031 // FIXME: It would be nice to be able to determine whether referencing
2032 // a particular member would be ambiguous. For example, given
2033 //
2034 // struct A { int member; };
2035 // struct B { int member; };
2036 // struct C : A, B { };
2037 //
2038 // void f(C *c) { c->### }
2039 //
2040 // accessing 'member' would result in an ambiguity. However, we
2041 // could be smart enough to qualify the member with the base
2042 // class, e.g.,
2043 //
2044 // c->B::member
2045 //
2046 // or
2047 //
2048 // c->A::member
2049
2050 // Find results in this base class (and its bases).
2051 ShadowContextRAII Shadow(Visited);
2052 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002053 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002054 }
2055 }
2056
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002057 // Traverse the contexts of Objective-C classes.
2058 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2059 // Traverse categories.
2060 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2061 Category; Category = Category->getNextClassCategory()) {
2062 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002063 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2064 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002065 }
2066
2067 // Traverse protocols.
2068 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2069 E = IFace->protocol_end(); I != E; ++I) {
2070 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002071 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2072 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002073 }
2074
2075 // Traverse the superclass.
2076 if (IFace->getSuperClass()) {
2077 ShadowContextRAII Shadow(Visited);
2078 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002079 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002080 }
2081 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2082 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2083 E = Protocol->protocol_end(); I != E; ++I) {
2084 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002085 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2086 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002087 }
2088 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2089 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2090 E = Category->protocol_end(); I != E; ++I) {
2091 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002092 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2093 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002094 }
2095 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002096}
2097
2098static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2099 UnqualUsingDirectiveSet &UDirs,
2100 VisibleDeclConsumer &Consumer,
2101 VisibleDeclsRecord &Visited) {
2102 if (!S)
2103 return;
2104
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002105 if (!S->getEntity() || !S->getParent() ||
2106 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2107 // Walk through the declarations in this Scope.
2108 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2109 D != DEnd; ++D) {
2110 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2111 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002112 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002113 Visited.add(ND);
2114 }
2115 }
2116 }
2117
Douglas Gregor2d435302009-12-30 17:04:44 +00002118 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002119 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002120 // Look into this scope's declaration context, along with any of its
2121 // parent lookup contexts (e.g., enclosing classes), up to the point
2122 // where we hit the context stored in the next outer scope.
2123 Entity = (DeclContext *)S->getEntity();
2124 DeclContext *OuterCtx = findOuterContext(S);
2125
2126 for (DeclContext *Ctx = Entity; Ctx && Ctx->getPrimaryContext() != OuterCtx;
2127 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002128 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2129 if (Method->isInstanceMethod()) {
2130 // For instance methods, look for ivars in the method's interface.
2131 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2132 Result.getNameLoc(), Sema::LookupMemberName);
2133 ObjCInterfaceDecl *IFace = Method->getClassInterface();
2134 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002135 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002136 }
2137
2138 // We've already performed all of the name lookup that we need
2139 // to for Objective-C methods; the next context will be the
2140 // outer scope.
2141 break;
2142 }
2143
Douglas Gregor2d435302009-12-30 17:04:44 +00002144 if (Ctx->isFunctionOrMethod())
2145 continue;
2146
2147 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002148 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002149 }
2150 } else if (!S->getParent()) {
2151 // Look into the translation unit scope. We walk through the translation
2152 // unit's declaration context, because the Scope itself won't have all of
2153 // the declarations if we loaded a precompiled header.
2154 // FIXME: We would like the translation unit's Scope object to point to the
2155 // translation unit, so we don't need this special "if" branch. However,
2156 // doing so would force the normal C++ name-lookup code to look into the
2157 // translation unit decl when the IdentifierInfo chains would suffice.
2158 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002159 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002160 Entity = Result.getSema().Context.getTranslationUnitDecl();
2161 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002162 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002163 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002164
2165 if (Entity) {
2166 // Lookup visible declarations in any namespaces found by using
2167 // directives.
2168 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2169 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2170 for (; UI != UEnd; ++UI)
2171 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002172 Result, /*QualifiedNameLookup=*/false,
2173 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002174 }
2175
2176 // Lookup names in the parent scope.
2177 ShadowContextRAII Shadow(Visited);
2178 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2179}
2180
2181void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2182 VisibleDeclConsumer &Consumer) {
2183 // Determine the set of using directives available during
2184 // unqualified name lookup.
2185 Scope *Initial = S;
2186 UnqualUsingDirectiveSet UDirs;
2187 if (getLangOptions().CPlusPlus) {
2188 // Find the first namespace or translation-unit scope.
2189 while (S && !isNamespaceOrTranslationUnitScope(S))
2190 S = S->getParent();
2191
2192 UDirs.visitScopeChain(Initial, S);
2193 }
2194 UDirs.done();
2195
2196 // Look for visible declarations.
2197 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2198 VisibleDeclsRecord Visited;
2199 ShadowContextRAII Shadow(Visited);
2200 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2201}
2202
2203void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2204 VisibleDeclConsumer &Consumer) {
2205 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2206 VisibleDeclsRecord Visited;
2207 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002208 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2209 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002210}
2211
2212//----------------------------------------------------------------------------
2213// Typo correction
2214//----------------------------------------------------------------------------
2215
2216namespace {
2217class TypoCorrectionConsumer : public VisibleDeclConsumer {
2218 /// \brief The name written that is a typo in the source.
2219 llvm::StringRef Typo;
2220
2221 /// \brief The results found that have the smallest edit distance
2222 /// found (so far) with the typo name.
2223 llvm::SmallVector<NamedDecl *, 4> BestResults;
2224
2225 /// \brief The best edit distance found so far.
2226 unsigned BestEditDistance;
2227
2228public:
2229 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2230 : Typo(Typo->getName()) { }
2231
Douglas Gregor09bbc652010-01-14 15:47:35 +00002232 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002233
2234 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2235 iterator begin() const { return BestResults.begin(); }
2236 iterator end() const { return BestResults.end(); }
2237 bool empty() const { return BestResults.empty(); }
2238
2239 unsigned getBestEditDistance() const { return BestEditDistance; }
2240};
2241
2242}
2243
Douglas Gregor09bbc652010-01-14 15:47:35 +00002244void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2245 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002246 // Don't consider hidden names for typo correction.
2247 if (Hiding)
2248 return;
2249
2250 // Only consider entities with identifiers for names, ignoring
2251 // special names (constructors, overloaded operators, selectors,
2252 // etc.).
2253 IdentifierInfo *Name = ND->getIdentifier();
2254 if (!Name)
2255 return;
2256
2257 // Compute the edit distance between the typo and the name of this
2258 // entity. If this edit distance is not worse than the best edit
2259 // distance we've seen so far, add it to the list of results.
2260 unsigned ED = Typo.edit_distance(Name->getName());
2261 if (!BestResults.empty()) {
2262 if (ED < BestEditDistance) {
2263 // This result is better than any we've seen before; clear out
2264 // the previous results.
2265 BestResults.clear();
2266 BestEditDistance = ED;
2267 } else if (ED > BestEditDistance) {
2268 // This result is worse than the best results we've seen so far;
2269 // ignore it.
2270 return;
2271 }
2272 } else
2273 BestEditDistance = ED;
2274
2275 BestResults.push_back(ND);
2276}
2277
2278/// \brief Try to "correct" a typo in the source code by finding
2279/// visible declarations whose names are similar to the name that was
2280/// present in the source code.
2281///
2282/// \param Res the \c LookupResult structure that contains the name
2283/// that was present in the source code along with the name-lookup
2284/// criteria used to search for the name. On success, this structure
2285/// will contain the results of name lookup.
2286///
2287/// \param S the scope in which name lookup occurs.
2288///
2289/// \param SS the nested-name-specifier that precedes the name we're
2290/// looking for, if present.
2291///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002292/// \param MemberContext if non-NULL, the context in which to look for
2293/// a member access expression.
2294///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002295/// \param EnteringContext whether we're entering the context described by
2296/// the nested-name-specifier SS.
2297///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002298/// \param OPT when non-NULL, the search for visible declarations will
2299/// also walk the protocols in the qualified interfaces of \p OPT.
2300///
Douglas Gregor2d435302009-12-30 17:04:44 +00002301/// \returns true if the typo was corrected, in which case the \p Res
2302/// structure will contain the results of name lookup for the
2303/// corrected name. Otherwise, returns false.
2304bool Sema::CorrectTypo(LookupResult &Res, Scope *S, const CXXScopeSpec *SS,
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002305 DeclContext *MemberContext, bool EnteringContext,
2306 const ObjCObjectPointerType *OPT) {
Ted Kremeneke51136e2010-01-06 00:23:04 +00002307
2308 if (Diags.hasFatalErrorOccurred())
2309 return false;
2310
Douglas Gregor2d435302009-12-30 17:04:44 +00002311 // We only attempt to correct typos for identifiers.
2312 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2313 if (!Typo)
2314 return false;
2315
2316 // If the scope specifier itself was invalid, don't try to correct
2317 // typos.
2318 if (SS && SS->isInvalid())
2319 return false;
2320
2321 // Never try to correct typos during template deduction or
2322 // instantiation.
2323 if (!ActiveTemplateInstantiations.empty())
2324 return false;
2325
2326 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002327 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002328 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002329
2330 // Look in qualified interfaces.
2331 if (OPT) {
2332 for (ObjCObjectPointerType::qual_iterator
2333 I = OPT->qual_begin(), E = OPT->qual_end();
2334 I != E; ++I)
2335 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2336 }
2337 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002338 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2339 if (!DC)
2340 return false;
2341
2342 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2343 } else {
2344 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2345 }
2346
2347 if (Consumer.empty())
2348 return false;
2349
2350 // Only allow a single, closest name in the result set (it's okay to
2351 // have overloads of that name, though).
2352 TypoCorrectionConsumer::iterator I = Consumer.begin();
2353 DeclarationName BestName = (*I)->getDeclName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002354
2355 // If we've found an Objective-C ivar or property, don't perform
2356 // name lookup again; we'll just return the result directly.
2357 NamedDecl *FoundBest = 0;
2358 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I))
2359 FoundBest = *I;
Douglas Gregor2d435302009-12-30 17:04:44 +00002360 ++I;
2361 for(TypoCorrectionConsumer::iterator IEnd = Consumer.end(); I != IEnd; ++I) {
2362 if (BestName != (*I)->getDeclName())
2363 return false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002364
2365 // FIXME: If there are both ivars and properties of the same name,
2366 // don't return both because the callee can't handle two
2367 // results. We really need to separate ivar lookup from property
2368 // lookup to avoid this problem.
2369 FoundBest = 0;
Douglas Gregor2d435302009-12-30 17:04:44 +00002370 }
2371
2372 // BestName is the closest viable name to what the user
2373 // typed. However, to make sure that we don't pick something that's
2374 // way off, make sure that the user typed at least 3 characters for
2375 // each correction.
2376 unsigned ED = Consumer.getBestEditDistance();
2377 if (ED == 0 || (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
2378 return false;
2379
2380 // Perform name lookup again with the name we chose, and declare
2381 // success if we found something that was not ambiguous.
2382 Res.clear();
2383 Res.setLookupName(BestName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002384
2385 // If we found an ivar or property, add that result; no further
2386 // lookup is required.
2387 if (FoundBest)
2388 Res.addDecl(FoundBest);
2389 // If we're looking into the context of a member, perform qualified
2390 // name lookup on the best name.
2391 else if (MemberContext)
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002392 LookupQualifiedName(Res, MemberContext);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002393 // Perform lookup as if we had just parsed the best name.
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002394 else
2395 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2396 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00002397
2398 if (Res.isAmbiguous()) {
2399 Res.suppressDiagnostics();
2400 return false;
2401 }
2402
2403 return Res.getResultKind() != LookupResult::NotFound;
Douglas Gregor2d435302009-12-30 17:04:44 +00002404}