blob: f6ae4e147f79bc6e8a208d0062003a80c6b9e2d6 [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"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000020#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000021#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor34074322009-01-14 22:20:51 +000023#include "clang/Parse/DeclSpec.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
26#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000027#include "llvm/ADT/SmallPtrSet.h"
John McCall6538c932009-10-10 05:48:19 +000028#include "llvm/Support/ErrorHandling.h"
Douglas Gregor1c846b02009-01-16 00:38:09 +000029#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000030#include <vector>
31#include <iterator>
32#include <utility>
33#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000034
35using namespace clang;
36
John McCallf6c8a4e2009-11-10 07:01:13 +000037namespace {
38 class UnqualUsingEntry {
39 const DeclContext *Nominated;
40 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000041
John McCallf6c8a4e2009-11-10 07:01:13 +000042 public:
43 UnqualUsingEntry(const DeclContext *Nominated,
44 const DeclContext *CommonAncestor)
45 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
46 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000047
John McCallf6c8a4e2009-11-10 07:01:13 +000048 const DeclContext *getCommonAncestor() const {
49 return CommonAncestor;
50 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000051
John McCallf6c8a4e2009-11-10 07:01:13 +000052 const DeclContext *getNominatedNamespace() const {
53 return Nominated;
54 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000055
John McCallf6c8a4e2009-11-10 07:01:13 +000056 // Sort by the pointer value of the common ancestor.
57 struct Comparator {
58 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
59 return L.getCommonAncestor() < R.getCommonAncestor();
60 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000061
John McCallf6c8a4e2009-11-10 07:01:13 +000062 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
63 return E.getCommonAncestor() < DC;
64 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000065
John McCallf6c8a4e2009-11-10 07:01:13 +000066 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
67 return DC < E.getCommonAncestor();
68 }
69 };
70 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000071
John McCallf6c8a4e2009-11-10 07:01:13 +000072 /// A collection of using directives, as used by C++ unqualified
73 /// lookup.
74 class UnqualUsingDirectiveSet {
75 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000076
John McCallf6c8a4e2009-11-10 07:01:13 +000077 ListTy list;
78 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000079
John McCallf6c8a4e2009-11-10 07:01:13 +000080 public:
81 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000082
John McCallf6c8a4e2009-11-10 07:01:13 +000083 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
84 // C++ [namespace.udir]p1:
85 // During unqualified name lookup, the names appear as if they
86 // were declared in the nearest enclosing namespace which contains
87 // both the using-directive and the nominated namespace.
88 DeclContext *InnermostFileDC
89 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
90 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000091
John McCallf6c8a4e2009-11-10 07:01:13 +000092 for (; S; S = S->getParent()) {
93 if (!(S->getFlags() & Scope::DeclScope))
94 continue;
Douglas Gregor889ceb72009-02-03 19:21:40 +000095
John McCallf6c8a4e2009-11-10 07:01:13 +000096 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
97 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
98 visit(Ctx, EffectiveDC);
99 } else {
100 Scope::udir_iterator I = S->using_directives_begin(),
101 End = S->using_directives_end();
102
103 for (; I != End; ++I)
104 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
105 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000106 }
107 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000108
109 // Visits a context and collect all of its using directives
110 // recursively. Treats all using directives as if they were
111 // declared in the context.
112 //
113 // A given context is only every visited once, so it is important
114 // that contexts be visited from the inside out in order to get
115 // the effective DCs right.
116 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
117 if (!visited.insert(DC))
118 return;
119
120 addUsingDirectives(DC, EffectiveDC);
121 }
122
123 // Visits a using directive and collects all of its using
124 // directives recursively. Treats all using directives as if they
125 // were declared in the effective DC.
126 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
127 DeclContext *NS = UD->getNominatedNamespace();
128 if (!visited.insert(NS))
129 return;
130
131 addUsingDirective(UD, EffectiveDC);
132 addUsingDirectives(NS, EffectiveDC);
133 }
134
135 // Adds all the using directives in a context (and those nominated
136 // by its using directives, transitively) as if they appeared in
137 // the given effective context.
138 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
139 llvm::SmallVector<DeclContext*,4> queue;
140 while (true) {
141 DeclContext::udir_iterator I, End;
142 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
143 UsingDirectiveDecl *UD = *I;
144 DeclContext *NS = UD->getNominatedNamespace();
145 if (visited.insert(NS)) {
146 addUsingDirective(UD, EffectiveDC);
147 queue.push_back(NS);
148 }
149 }
150
151 if (queue.empty())
152 return;
153
154 DC = queue.back();
155 queue.pop_back();
156 }
157 }
158
159 // Add a using directive as if it had been declared in the given
160 // context. This helps implement C++ [namespace.udir]p3:
161 // The using-directive is transitive: if a scope contains a
162 // using-directive that nominates a second namespace that itself
163 // contains using-directives, the effect is as if the
164 // using-directives from the second namespace also appeared in
165 // the first.
166 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
167 // Find the common ancestor between the effective context and
168 // the nominated namespace.
169 DeclContext *Common = UD->getNominatedNamespace();
170 while (!Common->Encloses(EffectiveDC))
171 Common = Common->getParent();
172
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 {
190 return std::equal_range(begin(), end(), DC,
191 UnqualUsingEntry::Comparator());
192 }
193 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000194}
195
Douglas Gregor889ceb72009-02-03 19:21:40 +0000196// Retrieve the set of identifier namespaces that correspond to a
197// specific kind of name lookup.
Mike Stump11289f42009-09-09 15:08:12 +0000198inline unsigned
199getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
Douglas Gregor889ceb72009-02-03 19:21:40 +0000200 bool CPlusPlus) {
201 unsigned IDNS = 0;
202 switch (NameKind) {
203 case Sema::LookupOrdinaryName:
Douglas Gregor94eabf32009-02-04 16:44:47 +0000204 case Sema::LookupOperatorName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000205 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206 IDNS = Decl::IDNS_Ordinary;
207 if (CPlusPlus)
208 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
209 break;
210
211 case Sema::LookupTagName:
212 IDNS = Decl::IDNS_Tag;
213 break;
214
215 case Sema::LookupMemberName:
216 IDNS = Decl::IDNS_Member;
217 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000218 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000219 break;
220
221 case Sema::LookupNestedNameSpecifierName:
222 case Sema::LookupNamespaceName:
223 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
224 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000225
Douglas Gregor79947a22009-04-24 00:11:27 +0000226 case Sema::LookupObjCProtocolName:
227 IDNS = Decl::IDNS_ObjCProtocol;
228 break;
229
230 case Sema::LookupObjCImplementationName:
231 IDNS = Decl::IDNS_ObjCImplementation;
232 break;
233
234 case Sema::LookupObjCCategoryImplName:
235 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000236 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000237 }
238 return IDNS;
239}
240
John McCall9f3059a2009-10-09 21:13:30 +0000241// Necessary because CXXBasePaths is not complete in Sema.h
242void Sema::LookupResult::deletePaths(CXXBasePaths *Paths) {
243 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000244}
245
John McCall9f3059a2009-10-09 21:13:30 +0000246void Sema::LookupResult::resolveKind() {
247 unsigned N = Decls.size();
Douglas Gregorf23311d2009-01-17 01:13:24 +0000248
John McCall9f3059a2009-10-09 21:13:30 +0000249 // Fast case: no possible ambiguity.
250 if (N <= 1) return;
251
John McCall6538c932009-10-10 05:48:19 +0000252 // Don't do any extra resolution if we've already resolved as ambiguous.
253 if (Kind == Ambiguous) return;
254
John McCall9f3059a2009-10-09 21:13:30 +0000255 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
256
257 bool Ambiguous = false;
258 bool HasTag = false, HasFunction = false, HasNonFunction = false;
259
260 unsigned UniqueTagIndex = 0;
261
262 unsigned I = 0;
263 while (I < N) {
264 NamedDecl *D = Decls[I];
265 assert(D == D->getUnderlyingDecl());
266
267 NamedDecl *CanonD = cast<NamedDecl>(D->getCanonicalDecl());
268 if (!Unique.insert(CanonD)) {
269 // If it's not unique, pull something off the back (and
270 // continue at this index).
271 Decls[I] = Decls[--N];
272 } else if (isa<UnresolvedUsingDecl>(D)) {
273 // FIXME: proper support for UnresolvedUsingDecls.
274 Decls[I] = Decls[--N];
275 } else {
276 // Otherwise, do some decl type analysis and then continue.
277 if (isa<TagDecl>(D)) {
278 if (HasTag)
279 Ambiguous = true;
280 UniqueTagIndex = I;
281 HasTag = true;
282 } else if (D->isFunctionOrFunctionTemplate()) {
283 HasFunction = true;
284 } else {
285 if (HasNonFunction)
286 Ambiguous = true;
287 HasNonFunction = true;
288 }
289 I++;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000290 }
Mike Stump11289f42009-09-09 15:08:12 +0000291 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000292
John McCall9f3059a2009-10-09 21:13:30 +0000293 // C++ [basic.scope.hiding]p2:
294 // A class name or enumeration name can be hidden by the name of
295 // an object, function, or enumerator declared in the same
296 // scope. If a class or enumeration name and an object, function,
297 // or enumerator are declared in the same scope (in any order)
298 // with the same name, the class or enumeration name is hidden
299 // wherever the object, function, or enumerator name is visible.
300 // But it's still an error if there are distinct tag types found,
301 // even if they're not visible. (ref?)
302 if (HasTag && !Ambiguous && (HasFunction || HasNonFunction))
303 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000304
John McCall9f3059a2009-10-09 21:13:30 +0000305 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000306
John McCall9f3059a2009-10-09 21:13:30 +0000307 if (HasFunction && HasNonFunction)
308 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000309
John McCall9f3059a2009-10-09 21:13:30 +0000310 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000311 setAmbiguous(LookupResult::AmbiguousReference);
John McCall9f3059a2009-10-09 21:13:30 +0000312 else if (N > 1)
John McCall6538c932009-10-10 05:48:19 +0000313 Kind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000314 else
John McCall6538c932009-10-10 05:48:19 +0000315 Kind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000316}
317
318/// @brief Converts the result of name lookup into a single (possible
319/// NULL) pointer to a declaration.
320///
321/// The resulting declaration will either be the declaration we found
322/// (if only a single declaration was found), an
323/// OverloadedFunctionDecl (if an overloaded function was found), or
324/// NULL (if no declaration was found). This conversion must not be
Mike Stump11289f42009-09-09 15:08:12 +0000325/// used anywhere where name lookup could result in an ambiguity.
Douglas Gregor34074322009-01-14 22:20:51 +0000326///
327/// The OverloadedFunctionDecl conversion is meant as a stop-gap
328/// solution, since it causes the OverloadedFunctionDecl to be
329/// leaked. FIXME: Eventually, there will be a better way to iterate
330/// over the set of overloaded functions returned by name lookup.
John McCall9f3059a2009-10-09 21:13:30 +0000331NamedDecl *Sema::LookupResult::getAsSingleDecl(ASTContext &C) const {
332 size_t size = Decls.size();
333 if (size == 0) return 0;
334 if (size == 1) return *begin();
Douglas Gregor34074322009-01-14 22:20:51 +0000335
John McCall9f3059a2009-10-09 21:13:30 +0000336 if (isAmbiguous()) return 0;
Douglas Gregor34074322009-01-14 22:20:51 +0000337
John McCall9f3059a2009-10-09 21:13:30 +0000338 iterator I = begin(), E = end();
Douglas Gregor34074322009-01-14 22:20:51 +0000339
John McCall9f3059a2009-10-09 21:13:30 +0000340 OverloadedFunctionDecl *Ovl
341 = OverloadedFunctionDecl::Create(C, (*I)->getDeclContext(),
342 (*I)->getDeclName());
343 for (; I != E; ++I) {
344 NamedDecl *ND = *I;
345 assert(ND->getUnderlyingDecl() == ND
346 && "decls in lookup result should have redirections stripped");
347 assert(ND->isFunctionOrFunctionTemplate());
348 if (isa<FunctionDecl>(ND))
349 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000350 else
John McCall9f3059a2009-10-09 21:13:30 +0000351 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
352 // FIXME: UnresolvedUsingDecls.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000353 }
John McCall9f3059a2009-10-09 21:13:30 +0000354
355 return Ovl;
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000356}
357
John McCall9f3059a2009-10-09 21:13:30 +0000358void Sema::LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
359 CXXBasePaths::paths_iterator I, E;
360 DeclContext::lookup_iterator DI, DE;
361 for (I = P.begin(), E = P.end(); I != E; ++I)
362 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
363 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000364}
365
John McCall9f3059a2009-10-09 21:13:30 +0000366void Sema::LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
367 Paths = new CXXBasePaths;
368 Paths->swap(P);
369 addDeclsFromBasePaths(*Paths);
370 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000371 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000372}
373
John McCall9f3059a2009-10-09 21:13:30 +0000374void Sema::LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
375 Paths = new CXXBasePaths;
376 Paths->swap(P);
377 addDeclsFromBasePaths(*Paths);
378 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000379 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000380}
381
382void Sema::LookupResult::print(llvm::raw_ostream &Out) {
383 Out << Decls.size() << " result(s)";
384 if (isAmbiguous()) Out << ", ambiguous";
385 if (Paths) Out << ", base paths present";
386
387 for (iterator I = begin(), E = end(); I != E; ++I) {
388 Out << "\n";
389 (*I)->print(Out, 2);
390 }
391}
392
393// Adds all qualifying matches for a name within a decl context to the
394// given lookup result. Returns true if any matches were found.
John McCallf6c8a4e2009-11-10 07:01:13 +0000395static bool LookupDirect(Sema::LookupResult &R,
396 const DeclContext *DC,
John McCall9f3059a2009-10-09 21:13:30 +0000397 DeclarationName Name,
398 Sema::LookupNameKind NameKind,
399 unsigned IDNS) {
400 bool Found = false;
401
John McCallf6c8a4e2009-11-10 07:01:13 +0000402 DeclContext::lookup_const_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000403 for (llvm::tie(I, E) = DC->lookup(Name); I != E; ++I)
404 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS))
405 R.addDecl(*I), Found = true;
406
407 return Found;
408}
409
John McCallf6c8a4e2009-11-10 07:01:13 +0000410// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000411static bool
412CppNamespaceLookup(Sema::LookupResult &R, ASTContext &Context, DeclContext *NS,
Douglas Gregor700792c2009-02-05 19:25:20 +0000413 DeclarationName Name, Sema::LookupNameKind NameKind,
John McCallf6c8a4e2009-11-10 07:01:13 +0000414 unsigned IDNS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000415
416 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
417
John McCallf6c8a4e2009-11-10 07:01:13 +0000418 // Perform direct name lookup into the LookupCtx.
John McCall9f3059a2009-10-09 21:13:30 +0000419 bool Found = LookupDirect(R, NS, Name, NameKind, IDNS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000420
John McCallf6c8a4e2009-11-10 07:01:13 +0000421 // Perform direct name lookup into the namespaces nominated by the
422 // using directives whose common ancestor is this namespace.
423 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
424 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000425
John McCallf6c8a4e2009-11-10 07:01:13 +0000426 for (; UI != UEnd; ++UI)
427 if (LookupDirect(R, UI->getNominatedNamespace(), Name, NameKind, IDNS))
428 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000429
430 R.resolveKind();
431
432 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000433}
434
435static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000436 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000437 return Ctx->isFileContext();
438 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000439}
Douglas Gregored8f2882009-01-30 01:04:22 +0000440
Douglas Gregor7f737c02009-09-10 16:57:35 +0000441// Find the next outer declaration context corresponding to this scope.
442static DeclContext *findOuterContext(Scope *S) {
443 for (S = S->getParent(); S; S = S->getParent())
444 if (S->getEntity())
445 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
446
447 return 0;
448}
449
John McCall9f3059a2009-10-09 21:13:30 +0000450bool
451Sema::CppLookupName(LookupResult &R, Scope *S, DeclarationName Name,
Douglas Gregor889ceb72009-02-03 19:21:40 +0000452 LookupNameKind NameKind, bool RedeclarationOnly) {
453 assert(getLangOptions().CPlusPlus &&
454 "Can perform only C++ lookup");
Mike Stump11289f42009-09-09 15:08:12 +0000455 unsigned IDNS
Douglas Gregor2ada0482009-02-04 17:27:36 +0000456 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
John McCallaa74a0c2009-08-28 07:59:38 +0000457
458 // If we're testing for redeclarations, also look in the friend namespaces.
459 if (RedeclarationOnly) {
460 if (IDNS & Decl::IDNS_Tag) IDNS |= Decl::IDNS_TagFriend;
461 if (IDNS & Decl::IDNS_Ordinary) IDNS |= Decl::IDNS_OrdinaryFriend;
462 }
463
Douglas Gregor889ceb72009-02-03 19:21:40 +0000464 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000465 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000466 I = IdResolver.begin(Name),
467 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000468
Douglas Gregor889ceb72009-02-03 19:21:40 +0000469 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000470 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000471 // ...During unqualified name lookup (3.4.1), the names appear as if
472 // they were declared in the nearest enclosing namespace which contains
473 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000474 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000475 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000476 //
477 // For example:
478 // namespace A { int i; }
479 // void foo() {
480 // int i;
481 // {
482 // using namespace A;
483 // ++i; // finds local 'i', A::i appears at global scope
484 // }
485 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000486 //
Douglas Gregor700792c2009-02-05 19:25:20 +0000487 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000488 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000489 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000490 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000491 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
John McCall9f3059a2009-10-09 21:13:30 +0000492 Found = true;
493 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000494 }
495 }
John McCall9f3059a2009-10-09 21:13:30 +0000496 if (Found) {
497 R.resolveKind();
498 return true;
499 }
500
Douglas Gregor700792c2009-02-05 19:25:20 +0000501 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregor7f737c02009-09-10 16:57:35 +0000502 DeclContext *OuterCtx = findOuterContext(S);
503 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
504 Ctx = Ctx->getLookupParent()) {
505 if (Ctx->isFunctionOrMethod())
506 continue;
507
508 // Perform qualified name lookup into this context.
509 // FIXME: In some cases, we know that every name that could be found by
510 // this qualified name lookup will also be on the identifier chain. For
511 // example, inside a class without any base classes, we never need to
512 // perform qualified lookup because all of the members are on top of the
513 // identifier chain.
John McCall9f3059a2009-10-09 21:13:30 +0000514 if (LookupQualifiedName(R, Ctx, Name, NameKind, RedeclarationOnly))
515 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000516 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000517 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000518 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000519
John McCallf6c8a4e2009-11-10 07:01:13 +0000520 // Stop if we ran out of scopes.
521 // FIXME: This really, really shouldn't be happening.
522 if (!S) return false;
523
Douglas Gregor700792c2009-02-05 19:25:20 +0000524 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000525 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000526 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000527 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
528 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000529
John McCallf6c8a4e2009-11-10 07:01:13 +0000530 UnqualUsingDirectiveSet UDirs;
531 UDirs.visitScopeChain(Initial, S);
532 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000533
Douglas Gregor700792c2009-02-05 19:25:20 +0000534 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000535 // Unqualified name lookup in C++ requires looking into scopes
536 // that aren't strictly lexical, and therefore we walk through the
537 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000538
Douglas Gregor889ceb72009-02-03 19:21:40 +0000539 for (; S; S = S->getParent()) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000540 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregorf2270432009-08-24 18:55:03 +0000541 if (Ctx->isTransparentContext())
542 continue;
543
Douglas Gregor700792c2009-02-05 19:25:20 +0000544 assert(Ctx && Ctx->isFileContext() &&
545 "We should have been looking only at file context here already.");
Douglas Gregor889ceb72009-02-03 19:21:40 +0000546
547 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000548 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000549 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000550 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
551 // We found something. Look for anything else in our scope
552 // with this same name and in an acceptable identifier
553 // namespace, so that we can construct an overload set if we
554 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000555 Found = true;
556 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000557 }
558 }
559
Douglas Gregor700792c2009-02-05 19:25:20 +0000560 // Look into context considering using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000561 if (CppNamespaceLookup(R, Context, Ctx, Name, NameKind, IDNS, UDirs))
John McCall9f3059a2009-10-09 21:13:30 +0000562 Found = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000563
John McCall9f3059a2009-10-09 21:13:30 +0000564 if (Found) {
565 R.resolveKind();
566 return true;
567 }
568
569 if (RedeclarationOnly && !Ctx->isTransparentContext())
570 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000571 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000572
John McCall9f3059a2009-10-09 21:13:30 +0000573 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000574}
575
Douglas Gregor34074322009-01-14 22:20:51 +0000576/// @brief Perform unqualified name lookup starting from a given
577/// scope.
578///
579/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
580/// used to find names within the current scope. For example, 'x' in
581/// @code
582/// int x;
583/// int f() {
584/// return x; // unqualified name look finds 'x' in the global scope
585/// }
586/// @endcode
587///
588/// Different lookup criteria can find different names. For example, a
589/// particular scope can have both a struct and a function of the same
590/// name, and each can be found by certain lookup criteria. For more
591/// information about lookup criteria, see the documentation for the
592/// class LookupCriteria.
593///
594/// @param S The scope from which unqualified name lookup will
595/// begin. If the lookup criteria permits, name lookup may also search
596/// in the parent scopes.
597///
598/// @param Name The name of the entity that we are searching for.
599///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000600/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000601/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000602/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000603///
604/// @returns The result of name lookup, which includes zero or more
605/// declarations and possibly additional information used to diagnose
606/// ambiguities.
John McCall9f3059a2009-10-09 21:13:30 +0000607bool Sema::LookupName(LookupResult &R, Scope *S, DeclarationName Name,
608 LookupNameKind NameKind, bool RedeclarationOnly,
609 bool AllowBuiltinCreation, SourceLocation Loc) {
610 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000611
612 if (!getLangOptions().CPlusPlus) {
613 // Unqualified name lookup in C/Objective-C is purely lexical, so
614 // search in the declarations attached to the name.
Douglas Gregored8f2882009-01-30 01:04:22 +0000615 unsigned IDNS = 0;
616 switch (NameKind) {
617 case Sema::LookupOrdinaryName:
618 IDNS = Decl::IDNS_Ordinary;
619 break;
Douglas Gregor34074322009-01-14 22:20:51 +0000620
Douglas Gregored8f2882009-01-30 01:04:22 +0000621 case Sema::LookupTagName:
622 IDNS = Decl::IDNS_Tag;
623 break;
624
625 case Sema::LookupMemberName:
626 IDNS = Decl::IDNS_Member;
627 break;
628
Douglas Gregor94eabf32009-02-04 16:44:47 +0000629 case Sema::LookupOperatorName:
Douglas Gregored8f2882009-01-30 01:04:22 +0000630 case Sema::LookupNestedNameSpecifierName:
631 case Sema::LookupNamespaceName:
632 assert(false && "C does not perform these kinds of name lookup");
633 break;
Douglas Gregoreddf4332009-02-24 20:03:32 +0000634
635 case Sema::LookupRedeclarationWithLinkage:
636 // Find the nearest non-transparent declaration scope.
637 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000638 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000639 static_cast<DeclContext *>(S->getEntity())
640 ->isTransparentContext()))
641 S = S->getParent();
642 IDNS = Decl::IDNS_Ordinary;
643 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000644
Douglas Gregor79947a22009-04-24 00:11:27 +0000645 case Sema::LookupObjCProtocolName:
646 IDNS = Decl::IDNS_ObjCProtocol;
647 break;
648
649 case Sema::LookupObjCImplementationName:
650 IDNS = Decl::IDNS_ObjCImplementation;
651 break;
Mike Stump11289f42009-09-09 15:08:12 +0000652
Douglas Gregor79947a22009-04-24 00:11:27 +0000653 case Sema::LookupObjCCategoryImplName:
654 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000655 break;
Douglas Gregored8f2882009-01-30 01:04:22 +0000656 }
657
Douglas Gregor34074322009-01-14 22:20:51 +0000658 // Scan up the scope chain looking for a decl that matches this
659 // identifier that is in the appropriate namespace. This search
660 // should not take long, as shadowing of names is uncommon, and
661 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000662 bool LeftStartingScope = false;
663
Douglas Gregored8f2882009-01-30 01:04:22 +0000664 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000665 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000666 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000667 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000668 if (NameKind == LookupRedeclarationWithLinkage) {
669 // Determine whether this (or a previous) declaration is
670 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000671 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000672 LeftStartingScope = true;
673
674 // If we found something outside of our starting scope that
675 // does not have linkage, skip it.
676 if (LeftStartingScope && !((*I)->hasLinkage()))
677 continue;
678 }
679
John McCall9f3059a2009-10-09 21:13:30 +0000680 R.addDecl(*I);
681
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000682 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000683 // If this declaration has the "overloadable" attribute, we
684 // might have a set of overloaded functions.
685
686 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000687 while (!(S->getFlags() & Scope::DeclScope) ||
688 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000689 S = S->getParent();
690
691 // Find the last declaration in this scope (with the same
692 // name, naturally).
693 IdentifierResolver::iterator LastI = I;
694 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000695 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000696 break;
John McCall9f3059a2009-10-09 21:13:30 +0000697 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000698 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000699 }
700
John McCall9f3059a2009-10-09 21:13:30 +0000701 R.resolveKind();
702
703 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000704 }
Douglas Gregor34074322009-01-14 22:20:51 +0000705 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000706 // Perform C++ unqualified name lookup.
John McCall9f3059a2009-10-09 21:13:30 +0000707 if (CppLookupName(R, S, Name, NameKind, RedeclarationOnly))
708 return true;
Douglas Gregor34074322009-01-14 22:20:51 +0000709 }
710
711 // If we didn't find a use of this identifier, and if the identifier
712 // corresponds to a compiler builtin, create the decl object for the builtin
713 // now, injecting it into translation unit scope, and return it.
Mike Stump11289f42009-09-09 15:08:12 +0000714 if (NameKind == LookupOrdinaryName ||
Douglas Gregoreddf4332009-02-24 20:03:32 +0000715 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor34074322009-01-14 22:20:51 +0000716 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000717 if (II && AllowBuiltinCreation) {
Douglas Gregor34074322009-01-14 22:20:51 +0000718 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000719 if (unsigned BuiltinID = II->getBuiltinID()) {
720 // In C++, we don't have any predefined library functions like
721 // 'malloc'. Instead, we'll just error.
Mike Stump11289f42009-09-09 15:08:12 +0000722 if (getLangOptions().CPlusPlus &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000723 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCall9f3059a2009-10-09 21:13:30 +0000724 return false;
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000725
John McCall9f3059a2009-10-09 21:13:30 +0000726 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
727 S, RedeclarationOnly, Loc);
728 if (D) R.addDecl(D);
729 return (D != NULL);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000730 }
Douglas Gregor34074322009-01-14 22:20:51 +0000731 }
Douglas Gregor34074322009-01-14 22:20:51 +0000732 }
John McCall9f3059a2009-10-09 21:13:30 +0000733 return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000734}
735
John McCall6538c932009-10-10 05:48:19 +0000736/// @brief Perform qualified name lookup in the namespaces nominated by
737/// using directives by the given context.
738///
739/// C++98 [namespace.qual]p2:
740/// Given X::m (where X is a user-declared namespace), or given ::m
741/// (where X is the global namespace), let S be the set of all
742/// declarations of m in X and in the transitive closure of all
743/// namespaces nominated by using-directives in X and its used
744/// namespaces, except that using-directives are ignored in any
745/// namespace, including X, directly containing one or more
746/// declarations of m. No namespace is searched more than once in
747/// the lookup of a name. If S is the empty set, the program is
748/// ill-formed. Otherwise, if S has exactly one member, or if the
749/// context of the reference is a using-declaration
750/// (namespace.udecl), S is the required set of declarations of
751/// m. Otherwise if the use of m is not one that allows a unique
752/// declaration to be chosen from S, the program is ill-formed.
753/// C++98 [namespace.qual]p5:
754/// During the lookup of a qualified namespace member name, if the
755/// lookup finds more than one declaration of the member, and if one
756/// declaration introduces a class name or enumeration name and the
757/// other declarations either introduce the same object, the same
758/// enumerator or a set of functions, the non-type name hides the
759/// class or enumeration name if and only if the declarations are
760/// from the same namespace; otherwise (the declarations are from
761/// different namespaces), the program is ill-formed.
762static bool LookupQualifiedNameInUsingDirectives(Sema::LookupResult &R,
763 DeclContext *StartDC,
764 DeclarationName Name,
765 Sema::LookupNameKind NameKind,
766 unsigned IDNS) {
767 assert(StartDC->isFileContext() && "start context is not a file context");
768
769 DeclContext::udir_iterator I = StartDC->using_directives_begin();
770 DeclContext::udir_iterator E = StartDC->using_directives_end();
771
772 if (I == E) return false;
773
774 // We have at least added all these contexts to the queue.
775 llvm::DenseSet<DeclContext*> Visited;
776 Visited.insert(StartDC);
777
778 // We have not yet looked into these namespaces, much less added
779 // their "using-children" to the queue.
780 llvm::SmallVector<NamespaceDecl*, 8> Queue;
781
782 // We have already looked into the initial namespace; seed the queue
783 // with its using-children.
784 for (; I != E; ++I) {
785 NamespaceDecl *ND = (*I)->getNominatedNamespace();
786 if (Visited.insert(ND).second)
787 Queue.push_back(ND);
788 }
789
790 // The easiest way to implement the restriction in [namespace.qual]p5
791 // is to check whether any of the individual results found a tag
792 // and, if so, to declare an ambiguity if the final result is not
793 // a tag.
794 bool FoundTag = false;
795 bool FoundNonTag = false;
796
797 Sema::LookupResult LocalR;
798
799 bool Found = false;
800 while (!Queue.empty()) {
801 NamespaceDecl *ND = Queue.back();
802 Queue.pop_back();
803
804 // We go through some convolutions here to avoid copying results
805 // between LookupResults.
806 bool UseLocal = !R.empty();
807 Sema::LookupResult &DirectR = UseLocal ? LocalR : R;
808 bool FoundDirect = LookupDirect(DirectR, ND, Name, NameKind, IDNS);
809
810 if (FoundDirect) {
811 // First do any local hiding.
812 DirectR.resolveKind();
813
814 // If the local result is a tag, remember that.
815 if (DirectR.isSingleTagDecl())
816 FoundTag = true;
817 else
818 FoundNonTag = true;
819
820 // Append the local results to the total results if necessary.
821 if (UseLocal) {
822 R.addAllDecls(LocalR);
823 LocalR.clear();
824 }
825 }
826
827 // If we find names in this namespace, ignore its using directives.
828 if (FoundDirect) {
829 Found = true;
830 continue;
831 }
832
833 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
834 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
835 if (Visited.insert(Nom).second)
836 Queue.push_back(Nom);
837 }
838 }
839
840 if (Found) {
841 if (FoundTag && FoundNonTag)
842 R.setAmbiguousQualifiedTagHiding();
843 else
844 R.resolveKind();
845 }
846
847 return Found;
848}
849
Douglas Gregor34074322009-01-14 22:20:51 +0000850/// @brief Perform qualified name lookup into a given context.
851///
852/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
853/// names when the context of those names is explicit specified, e.g.,
854/// "std::vector" or "x->member".
855///
856/// Different lookup criteria can find different names. For example, a
857/// particular scope can have both a struct and a function of the same
858/// name, and each can be found by certain lookup criteria. For more
859/// information about lookup criteria, see the documentation for the
860/// class LookupCriteria.
861///
862/// @param LookupCtx The context in which qualified name lookup will
863/// search. If the lookup criteria permits, name lookup may also search
864/// in the parent contexts or (for C++ classes) base classes.
865///
866/// @param Name The name of the entity that we are searching for.
867///
868/// @param Criteria The criteria that this routine will use to
869/// determine which names are visible and which names will be
870/// found. Note that name lookup will find a name that is visible by
871/// the given criteria, but the entity itself may not be semantically
872/// correct or even the kind of entity expected based on the
873/// lookup. For example, searching for a nested-name-specifier name
874/// might result in an EnumDecl, which is visible but is not permitted
875/// as a nested-name-specifier in C++03.
876///
877/// @returns The result of name lookup, which includes zero or more
878/// declarations and possibly additional information used to diagnose
879/// ambiguities.
John McCall9f3059a2009-10-09 21:13:30 +0000880bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
881 DeclarationName Name, LookupNameKind NameKind,
882 bool RedeclarationOnly) {
Douglas Gregor34074322009-01-14 22:20:51 +0000883 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +0000884
885 if (!Name)
John McCall9f3059a2009-10-09 21:13:30 +0000886 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000887
Douglas Gregor34074322009-01-14 22:20:51 +0000888 // If we're performing qualified name lookup (e.g., lookup into a
889 // struct), find fields as part of ordinary name lookup.
Douglas Gregored8f2882009-01-30 01:04:22 +0000890 unsigned IDNS
Mike Stump11289f42009-09-09 15:08:12 +0000891 = getIdentifierNamespacesFromLookupNameKind(NameKind,
Douglas Gregored8f2882009-01-30 01:04:22 +0000892 getLangOptions().CPlusPlus);
893 if (NameKind == LookupOrdinaryName)
894 IDNS |= Decl::IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000895
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000896 // Make sure that the declaration context is complete.
897 assert((!isa<TagDecl>(LookupCtx) ||
898 LookupCtx->isDependentContext() ||
899 cast<TagDecl>(LookupCtx)->isDefinition() ||
900 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
901 ->isBeingDefined()) &&
902 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +0000903
Douglas Gregor34074322009-01-14 22:20:51 +0000904 // Perform qualified name lookup into the LookupCtx.
John McCall9f3059a2009-10-09 21:13:30 +0000905 if (LookupDirect(R, LookupCtx, Name, NameKind, IDNS)) {
906 R.resolveKind();
907 return true;
908 }
Douglas Gregor34074322009-01-14 22:20:51 +0000909
John McCall6538c932009-10-10 05:48:19 +0000910 // Don't descend into implied contexts for redeclarations.
911 // C++98 [namespace.qual]p6:
912 // In a declaration for a namespace member in which the
913 // declarator-id is a qualified-id, given that the qualified-id
914 // for the namespace member has the form
915 // nested-name-specifier unqualified-id
916 // the unqualified-id shall name a member of the namespace
917 // designated by the nested-name-specifier.
918 // See also [class.mfct]p5 and [class.static.data]p2.
919 if (RedeclarationOnly)
920 return false;
921
922 // If this is a namespace, look it up in
923 if (LookupCtx->isFileContext())
924 return LookupQualifiedNameInUsingDirectives(R, LookupCtx, Name, NameKind,
925 IDNS);
926
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000927 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +0000928 // classes, we're done.
John McCall6538c932009-10-10 05:48:19 +0000929 if (!isa<CXXRecordDecl>(LookupCtx))
John McCall9f3059a2009-10-09 21:13:30 +0000930 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000931
932 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +0000933 CXXRecordDecl *LookupRec = cast<CXXRecordDecl>(LookupCtx);
934 CXXBasePaths Paths;
935 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000936
937 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +0000938 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
939 switch (NameKind) {
940 case LookupOrdinaryName:
941 case LookupMemberName:
942 case LookupRedeclarationWithLinkage:
943 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
944 break;
945
946 case LookupTagName:
947 BaseCallback = &CXXRecordDecl::FindTagMember;
948 break;
949
950 case LookupOperatorName:
951 case LookupNamespaceName:
952 case LookupObjCProtocolName:
953 case LookupObjCImplementationName:
954 case LookupObjCCategoryImplName:
955 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +0000956 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000957
958 case LookupNestedNameSpecifierName:
959 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
960 break;
961 }
962
963 if (!LookupRec->lookupInBases(BaseCallback, Name.getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +0000964 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000965
966 // C++ [class.member.lookup]p2:
967 // [...] If the resulting set of declarations are not all from
968 // sub-objects of the same type, or the set has a nonstatic member
969 // and includes members from distinct sub-objects, there is an
970 // ambiguity and the program is ill-formed. Otherwise that set is
971 // the result of the lookup.
972 // FIXME: support using declarations!
973 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +0000974 int SubobjectNumber = 0;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000975 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000976 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000977 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000978
979 // Determine whether we're looking at a distinct sub-object or not.
980 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +0000981 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000982 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
983 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +0000984 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000985 != Context.getCanonicalType(PathElement.Base->getType())) {
986 // We found members of the given name in two subobjects of
987 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +0000988 R.setAmbiguousBaseSubobjectTypes(Paths);
989 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000990 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
991 // We have a different subobject of the same type.
992
993 // C++ [class.member.lookup]p5:
994 // A static member, a nested type or an enumerator defined in
995 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +0000996 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000997 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000998 if (isa<VarDecl>(FirstDecl) ||
999 isa<TypeDecl>(FirstDecl) ||
1000 isa<EnumConstantDecl>(FirstDecl))
1001 continue;
1002
1003 if (isa<CXXMethodDecl>(FirstDecl)) {
1004 // Determine whether all of the methods are static.
1005 bool AllMethodsAreStatic = true;
1006 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1007 Func != Path->Decls.second; ++Func) {
1008 if (!isa<CXXMethodDecl>(*Func)) {
1009 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1010 break;
1011 }
1012
1013 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1014 AllMethodsAreStatic = false;
1015 break;
1016 }
1017 }
1018
1019 if (AllMethodsAreStatic)
1020 continue;
1021 }
1022
1023 // We have found a nonstatic member name in multiple, distinct
1024 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001025 R.setAmbiguousBaseSubobjects(Paths);
1026 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001027 }
1028 }
1029
1030 // Lookup in a base class succeeded; return these results.
1031
John McCall9f3059a2009-10-09 21:13:30 +00001032 DeclContext::lookup_iterator I, E;
1033 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I)
1034 R.addDecl(*I);
1035 R.resolveKind();
1036 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001037}
1038
1039/// @brief Performs name lookup for a name that was parsed in the
1040/// source code, and may contain a C++ scope specifier.
1041///
1042/// This routine is a convenience routine meant to be called from
1043/// contexts that receive a name and an optional C++ scope specifier
1044/// (e.g., "N::M::x"). It will then perform either qualified or
1045/// unqualified name lookup (with LookupQualifiedName or LookupName,
1046/// respectively) on the given name and return those results.
1047///
1048/// @param S The scope from which unqualified name lookup will
1049/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001050///
Douglas Gregore861bac2009-08-25 22:51:20 +00001051/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001052///
1053/// @param Name The name of the entity that name lookup will
1054/// search for.
1055///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001056/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001057/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001058/// C library functions (like "malloc") are implicitly declared.
1059///
Douglas Gregore861bac2009-08-25 22:51:20 +00001060/// @param EnteringContext Indicates whether we are going to enter the
1061/// context of the scope-specifier SS (if present).
1062///
John McCall9f3059a2009-10-09 21:13:30 +00001063/// @returns True if any decls were found (but possibly ambiguous)
1064bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
1065 DeclarationName Name, LookupNameKind NameKind,
1066 bool RedeclarationOnly, bool AllowBuiltinCreation,
1067 SourceLocation Loc,
1068 bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001069 if (SS && SS->isInvalid()) {
1070 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001071 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001072 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001073 }
Mike Stump11289f42009-09-09 15:08:12 +00001074
Douglas Gregore861bac2009-08-25 22:51:20 +00001075 if (SS && SS->isSet()) {
1076 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001077 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001078 // contex, and will perform name lookup in that context.
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001079 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCall9f3059a2009-10-09 21:13:30 +00001080 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001081
John McCall9f3059a2009-10-09 21:13:30 +00001082 return LookupQualifiedName(R, DC, Name, NameKind, RedeclarationOnly);
Douglas Gregor52537682009-03-19 00:18:19 +00001083 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001084
Douglas Gregore861bac2009-08-25 22:51:20 +00001085 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001086 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001087 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001088 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001089 }
1090
Mike Stump11289f42009-09-09 15:08:12 +00001091 // Perform unqualified name lookup starting in the given scope.
John McCall9f3059a2009-10-09 21:13:30 +00001092 return LookupName(R, S, Name, NameKind, RedeclarationOnly,
1093 AllowBuiltinCreation, Loc);
Douglas Gregor34074322009-01-14 22:20:51 +00001094}
1095
Douglas Gregor889ceb72009-02-03 19:21:40 +00001096
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001097/// @brief Produce a diagnostic describing the ambiguity that resulted
1098/// from name lookup.
1099///
1100/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001101///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001102/// @param Name The name of the entity that name lookup was
1103/// searching for.
1104///
1105/// @param NameLoc The location of the name within the source code.
1106///
1107/// @param LookupRange A source range that provides more
1108/// source-location information concerning the lookup itself. For
1109/// example, this range might highlight a nested-name-specifier that
1110/// precedes the name.
1111///
1112/// @returns true
1113bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
Mike Stump11289f42009-09-09 15:08:12 +00001114 SourceLocation NameLoc,
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001115 SourceRange LookupRange) {
1116 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1117
John McCall6538c932009-10-10 05:48:19 +00001118 switch (Result.getAmbiguityKind()) {
1119 case LookupResult::AmbiguousBaseSubobjects: {
1120 CXXBasePaths *Paths = Result.getBasePaths();
1121 QualType SubobjectType = Paths->front().back().Base->getType();
1122 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1123 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1124 << LookupRange;
1125
1126 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1127 while (isa<CXXMethodDecl>(*Found) &&
1128 cast<CXXMethodDecl>(*Found)->isStatic())
1129 ++Found;
1130
1131 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1132
1133 return true;
1134 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001135
John McCall6538c932009-10-10 05:48:19 +00001136 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001137 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1138 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001139
1140 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001141 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001142 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1143 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001144 Path != PathEnd; ++Path) {
1145 Decl *D = *Path->Decls.first;
1146 if (DeclsPrinted.insert(D).second)
1147 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1148 }
1149
Douglas Gregor1c846b02009-01-16 00:38:09 +00001150 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001151 }
1152
John McCall6538c932009-10-10 05:48:19 +00001153 case LookupResult::AmbiguousTagHiding: {
1154 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001155
John McCall6538c932009-10-10 05:48:19 +00001156 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1157
1158 LookupResult::iterator DI, DE = Result.end();
1159 for (DI = Result.begin(); DI != DE; ++DI)
1160 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1161 TagDecls.insert(TD);
1162 Diag(TD->getLocation(), diag::note_hidden_tag);
1163 }
1164
1165 for (DI = Result.begin(); DI != DE; ++DI)
1166 if (!isa<TagDecl>(*DI))
1167 Diag((*DI)->getLocation(), diag::note_hiding_object);
1168
1169 // For recovery purposes, go ahead and implement the hiding.
1170 Result.hideDecls(TagDecls);
1171
1172 return true;
1173 }
1174
1175 case LookupResult::AmbiguousReference: {
1176 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001177
John McCall6538c932009-10-10 05:48:19 +00001178 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1179 for (; DI != DE; ++DI)
1180 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001181
John McCall6538c932009-10-10 05:48:19 +00001182 return true;
1183 }
1184 }
1185
1186 llvm::llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001187 return true;
1188}
Douglas Gregore254f902009-02-04 00:32:51 +00001189
Mike Stump11289f42009-09-09 15:08:12 +00001190static void
1191addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001192 ASTContext &Context,
1193 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001194 Sema::AssociatedClassSet &AssociatedClasses);
1195
1196static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1197 DeclContext *Ctx) {
1198 if (Ctx->isFileContext())
1199 Namespaces.insert(Ctx);
1200}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001201
Mike Stump11289f42009-09-09 15:08:12 +00001202// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001203// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001204static void
1205addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001206 ASTContext &Context,
1207 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001208 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001209 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001210 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001211 switch (Arg.getKind()) {
1212 case TemplateArgument::Null:
1213 break;
Mike Stump11289f42009-09-09 15:08:12 +00001214
Douglas Gregor197e5f72009-07-08 07:51:57 +00001215 case TemplateArgument::Type:
1216 // [...] the namespaces and classes associated with the types of the
1217 // template arguments provided for template type parameters (excluding
1218 // template template parameters)
1219 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1220 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001221 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001222 break;
Mike Stump11289f42009-09-09 15:08:12 +00001223
Douglas Gregor197e5f72009-07-08 07:51:57 +00001224 case TemplateArgument::Declaration:
Mike Stump11289f42009-09-09 15:08:12 +00001225 // [...] the namespaces in which any template template arguments are
1226 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001227 // template template arguments are defined.
Mike Stump11289f42009-09-09 15:08:12 +00001228 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor197e5f72009-07-08 07:51:57 +00001229 = dyn_cast<ClassTemplateDecl>(Arg.getAsDecl())) {
1230 DeclContext *Ctx = ClassTemplate->getDeclContext();
1231 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1232 AssociatedClasses.insert(EnclosingClass);
1233 // Add the associated namespace for this class.
1234 while (Ctx->isRecord())
1235 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001236 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001237 }
1238 break;
Mike Stump11289f42009-09-09 15:08:12 +00001239
Douglas Gregor197e5f72009-07-08 07:51:57 +00001240 case TemplateArgument::Integral:
1241 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001242 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001243 // associated namespaces. ]
1244 break;
Mike Stump11289f42009-09-09 15:08:12 +00001245
Douglas Gregor197e5f72009-07-08 07:51:57 +00001246 case TemplateArgument::Pack:
1247 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1248 PEnd = Arg.pack_end();
1249 P != PEnd; ++P)
1250 addAssociatedClassesAndNamespaces(*P, Context,
1251 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001252 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001253 break;
1254 }
1255}
1256
Douglas Gregore254f902009-02-04 00:32:51 +00001257// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001258// argument-dependent lookup with an argument of class type
1259// (C++ [basic.lookup.koenig]p2).
1260static void
1261addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregore254f902009-02-04 00:32:51 +00001262 ASTContext &Context,
1263 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001264 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001265 // C++ [basic.lookup.koenig]p2:
1266 // [...]
1267 // -- If T is a class type (including unions), its associated
1268 // classes are: the class itself; the class of which it is a
1269 // member, if any; and its direct and indirect base
1270 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001271 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001272
1273 // Add the class of which it is a member, if any.
1274 DeclContext *Ctx = Class->getDeclContext();
1275 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1276 AssociatedClasses.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001277 // Add the associated namespace for this class.
1278 while (Ctx->isRecord())
1279 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001280 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001281
Douglas Gregore254f902009-02-04 00:32:51 +00001282 // Add the class itself. If we've already seen this class, we don't
1283 // need to visit base classes.
1284 if (!AssociatedClasses.insert(Class))
1285 return;
1286
Mike Stump11289f42009-09-09 15:08:12 +00001287 // -- If T is a template-id, its associated namespaces and classes are
1288 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001289 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001290 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001291 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001292 // namespaces in which any template template arguments are defined; and
1293 // the classes in which any member templates used as template template
1294 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001295 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001296 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001297 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1298 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1299 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1300 AssociatedClasses.insert(EnclosingClass);
1301 // Add the associated namespace for this class.
1302 while (Ctx->isRecord())
1303 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001304 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001305
Douglas Gregor197e5f72009-07-08 07:51:57 +00001306 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1307 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1308 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1309 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001310 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001311 }
Mike Stump11289f42009-09-09 15:08:12 +00001312
Douglas Gregore254f902009-02-04 00:32:51 +00001313 // Add direct and indirect base classes along with their associated
1314 // namespaces.
1315 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1316 Bases.push_back(Class);
1317 while (!Bases.empty()) {
1318 // Pop this class off the stack.
1319 Class = Bases.back();
1320 Bases.pop_back();
1321
1322 // Visit the base classes.
1323 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1324 BaseEnd = Class->bases_end();
1325 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001326 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001327 // In dependent contexts, we do ADL twice, and the first time around,
1328 // the base type might be a dependent TemplateSpecializationType, or a
1329 // TemplateTypeParmType. If that happens, simply ignore it.
1330 // FIXME: If we want to support export, we probably need to add the
1331 // namespace of the template in a TemplateSpecializationType, or even
1332 // the classes and namespaces of known non-dependent arguments.
1333 if (!BaseType)
1334 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001335 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1336 if (AssociatedClasses.insert(BaseDecl)) {
1337 // Find the associated namespace for this base class.
1338 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1339 while (BaseCtx->isRecord())
1340 BaseCtx = BaseCtx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001341 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001342
1343 // Make sure we visit the bases of this base class.
1344 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1345 Bases.push_back(BaseDecl);
1346 }
1347 }
1348 }
1349}
1350
1351// \brief Add the associated classes and namespaces for
1352// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001353// (C++ [basic.lookup.koenig]p2).
1354static void
1355addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregore254f902009-02-04 00:32:51 +00001356 ASTContext &Context,
1357 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001358 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001359 // C++ [basic.lookup.koenig]p2:
1360 //
1361 // For each argument type T in the function call, there is a set
1362 // of zero or more associated namespaces and a set of zero or more
1363 // associated classes to be considered. The sets of namespaces and
1364 // classes is determined entirely by the types of the function
1365 // arguments (and the namespace of any template template
1366 // argument). Typedef names and using-declarations used to specify
1367 // the types do not contribute to this set. The sets of namespaces
1368 // and classes are determined in the following way:
1369 T = Context.getCanonicalType(T).getUnqualifiedType();
1370
1371 // -- If T is a pointer to U or an array of U, its associated
Mike Stump11289f42009-09-09 15:08:12 +00001372 // namespaces and classes are those associated with U.
Douglas Gregore254f902009-02-04 00:32:51 +00001373 //
1374 // We handle this by unwrapping pointer and array types immediately,
1375 // to avoid unnecessary recursion.
1376 while (true) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001377 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001378 T = Ptr->getPointeeType();
1379 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1380 T = Ptr->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001381 else
Douglas Gregore254f902009-02-04 00:32:51 +00001382 break;
1383 }
1384
1385 // -- If T is a fundamental type, its associated sets of
1386 // namespaces and classes are both empty.
John McCall9dd450b2009-09-21 23:43:11 +00001387 if (T->getAs<BuiltinType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001388 return;
1389
1390 // -- If T is a class type (including unions), its associated
1391 // classes are: the class itself; the class of which it is a
1392 // member, if any; and its direct and indirect base
1393 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001394 // which its associated classes are defined.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001395 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump11289f42009-09-09 15:08:12 +00001396 if (CXXRecordDecl *ClassDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001397 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001398 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1399 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001400 AssociatedClasses);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001401 return;
1402 }
Douglas Gregore254f902009-02-04 00:32:51 +00001403
1404 // -- If T is an enumeration type, its associated namespace is
1405 // the namespace in which it is defined. If it is class
1406 // member, its associated class is the member’s class; else
Mike Stump11289f42009-09-09 15:08:12 +00001407 // it has no associated class.
John McCall9dd450b2009-09-21 23:43:11 +00001408 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001409 EnumDecl *Enum = EnumT->getDecl();
1410
1411 DeclContext *Ctx = Enum->getDeclContext();
1412 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1413 AssociatedClasses.insert(EnclosingClass);
1414
1415 // Add the associated namespace for this class.
1416 while (Ctx->isRecord())
1417 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001418 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001419
1420 return;
1421 }
1422
1423 // -- If T is a function type, its associated namespaces and
1424 // classes are those associated with the function parameter
1425 // types and those associated with the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001426 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001427 // Return type
John McCall9dd450b2009-09-21 23:43:11 +00001428 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregore254f902009-02-04 00:32:51 +00001429 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001430 AssociatedNamespaces, AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001431
John McCall9dd450b2009-09-21 23:43:11 +00001432 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregore254f902009-02-04 00:32:51 +00001433 if (!Proto)
1434 return;
1435
1436 // Argument types
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001437 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001438 ArgEnd = Proto->arg_type_end();
Douglas Gregore254f902009-02-04 00:32:51 +00001439 Arg != ArgEnd; ++Arg)
1440 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallc7e8e792009-08-07 22:18:02 +00001441 AssociatedNamespaces, AssociatedClasses);
Mike Stump11289f42009-09-09 15:08:12 +00001442
Douglas Gregore254f902009-02-04 00:32:51 +00001443 return;
1444 }
1445
1446 // -- If T is a pointer to a member function of a class X, its
1447 // associated namespaces and classes are those associated
1448 // with the function parameter types and return type,
Mike Stump11289f42009-09-09 15:08:12 +00001449 // together with those associated with X.
Douglas Gregore254f902009-02-04 00:32:51 +00001450 //
1451 // -- If T is a pointer to a data member of class X, its
1452 // associated namespaces and classes are those associated
1453 // with the member type together with those associated with
Mike Stump11289f42009-09-09 15:08:12 +00001454 // X.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001455 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001456 // Handle the type that the pointer to member points to.
1457 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1458 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001459 AssociatedNamespaces,
1460 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001461
1462 // Handle the class type into which this points.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001463 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001464 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1465 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001466 AssociatedNamespaces,
1467 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001468
1469 return;
1470 }
1471
1472 // FIXME: What about block pointers?
1473 // FIXME: What about Objective-C message sends?
1474}
1475
1476/// \brief Find the associated classes and namespaces for
1477/// argument-dependent lookup for a call with the given set of
1478/// arguments.
1479///
1480/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001481/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001482/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001483void
Douglas Gregore254f902009-02-04 00:32:51 +00001484Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1485 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001486 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001487 AssociatedNamespaces.clear();
1488 AssociatedClasses.clear();
1489
1490 // C++ [basic.lookup.koenig]p2:
1491 // For each argument type T in the function call, there is a set
1492 // of zero or more associated namespaces and a set of zero or more
1493 // associated classes to be considered. The sets of namespaces and
1494 // classes is determined entirely by the types of the function
1495 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001496 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001497 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1498 Expr *Arg = Args[ArgIdx];
1499
1500 if (Arg->getType() != Context.OverloadTy) {
1501 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001502 AssociatedNamespaces,
1503 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001504 continue;
1505 }
1506
1507 // [...] In addition, if the argument is the name or address of a
1508 // set of overloaded functions and/or function templates, its
1509 // associated classes and namespaces are the union of those
1510 // associated with each of the members of the set: the namespace
1511 // in which the function or function template is defined and the
1512 // classes and namespaces associated with its (non-dependent)
1513 // parameter types and return type.
1514 DeclRefExpr *DRE = 0;
Douglas Gregorbe759252009-07-08 10:57:20 +00001515 TemplateIdRefExpr *TIRE = 0;
1516 Arg = Arg->IgnoreParens();
Douglas Gregore254f902009-02-04 00:32:51 +00001517 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorbe759252009-07-08 10:57:20 +00001518 if (unaryOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregore254f902009-02-04 00:32:51 +00001519 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
Douglas Gregorbe759252009-07-08 10:57:20 +00001520 TIRE = dyn_cast<TemplateIdRefExpr>(unaryOp->getSubExpr());
1521 }
1522 } else {
Douglas Gregore254f902009-02-04 00:32:51 +00001523 DRE = dyn_cast<DeclRefExpr>(Arg);
Douglas Gregorbe759252009-07-08 10:57:20 +00001524 TIRE = dyn_cast<TemplateIdRefExpr>(Arg);
1525 }
Mike Stump11289f42009-09-09 15:08:12 +00001526
Douglas Gregorbe759252009-07-08 10:57:20 +00001527 OverloadedFunctionDecl *Ovl = 0;
1528 if (DRE)
1529 Ovl = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1530 else if (TIRE)
Douglas Gregoraa87ebc2009-07-29 18:26:50 +00001531 Ovl = TIRE->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001532 if (!Ovl)
1533 continue;
1534
1535 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1536 FuncEnd = Ovl->function_end();
1537 Func != FuncEnd; ++Func) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001538 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func);
1539 if (!FDecl)
1540 FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001541
1542 // Add the namespace in which this function was defined. Note
1543 // that, if this is a member function, we do *not* consider the
1544 // enclosing namespace of its class.
1545 DeclContext *Ctx = FDecl->getDeclContext();
John McCallc7e8e792009-08-07 22:18:02 +00001546 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001547
1548 // Add the classes and namespaces associated with the parameter
1549 // types and return type of this function.
1550 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001551 AssociatedNamespaces,
1552 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001553 }
1554 }
1555}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001556
1557/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1558/// an acceptable non-member overloaded operator for a call whose
1559/// arguments have types T1 (and, if non-empty, T2). This routine
1560/// implements the check in C++ [over.match.oper]p3b2 concerning
1561/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001562static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001563IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1564 QualType T1, QualType T2,
1565 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001566 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1567 return true;
1568
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001569 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1570 return true;
1571
John McCall9dd450b2009-09-21 23:43:11 +00001572 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001573 if (Proto->getNumArgs() < 1)
1574 return false;
1575
1576 if (T1->isEnumeralType()) {
1577 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1578 if (Context.getCanonicalType(T1).getUnqualifiedType()
1579 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1580 return true;
1581 }
1582
1583 if (Proto->getNumArgs() < 2)
1584 return false;
1585
1586 if (!T2.isNull() && T2->isEnumeralType()) {
1587 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1588 if (Context.getCanonicalType(T2).getUnqualifiedType()
1589 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1590 return true;
1591 }
1592
1593 return false;
1594}
1595
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001596/// \brief Find the protocol with the given name, if any.
1597ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001598 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001599 return cast_or_null<ObjCProtocolDecl>(D);
1600}
1601
Douglas Gregor79947a22009-04-24 00:11:27 +00001602/// \brief Find the Objective-C category implementation with the given
1603/// name, if any.
1604ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001605 Decl *D = LookupSingleName(TUScope, II, LookupObjCCategoryImplName);
Douglas Gregor79947a22009-04-24 00:11:27 +00001606 return cast_or_null<ObjCCategoryImplDecl>(D);
1607}
1608
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001609void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001610 QualType T1, QualType T2,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001611 FunctionSet &Functions) {
1612 // C++ [over.match.oper]p3:
1613 // -- The set of non-member candidates is the result of the
1614 // unqualified lookup of operator@ in the context of the
1615 // expression according to the usual rules for name lookup in
1616 // unqualified function calls (3.4.2) except that all member
1617 // functions are ignored. However, if no operand has a class
1618 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001619 // that have a first parameter of type T1 or "reference to
1620 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001621 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001622 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001623 // when T2 is an enumeration type, are candidate functions.
1624 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall9f3059a2009-10-09 21:13:30 +00001625 LookupResult Operators;
1626 LookupName(Operators, S, OpName, LookupOperatorName);
Mike Stump11289f42009-09-09 15:08:12 +00001627
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001628 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1629
John McCall9f3059a2009-10-09 21:13:30 +00001630 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001631 return;
1632
1633 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1634 Op != OpEnd; ++Op) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001635 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001636 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1637 Functions.insert(FD); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001638 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor15448f82009-06-27 21:05:07 +00001639 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1640 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001641 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001642 // later?
1643 if (!FunTmpl->getDeclContext()->isRecord())
1644 Functions.insert(FunTmpl);
1645 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001646 }
1647}
1648
John McCallc7e8e792009-08-07 22:18:02 +00001649static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1650 Decl *D) {
1651 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1652 Functions.insert(Func);
1653 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1654 Functions.insert(FunTmpl);
1655}
1656
Sebastian Redlc057f422009-10-23 19:23:15 +00001657void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001658 Expr **Args, unsigned NumArgs,
1659 FunctionSet &Functions) {
1660 // Find all of the associated namespaces and classes based on the
1661 // arguments we have.
1662 AssociatedNamespaceSet AssociatedNamespaces;
1663 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00001664 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00001665 AssociatedNamespaces,
1666 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001667
Sebastian Redlc057f422009-10-23 19:23:15 +00001668 QualType T1, T2;
1669 if (Operator) {
1670 T1 = Args[0]->getType();
1671 if (NumArgs >= 2)
1672 T2 = Args[1]->getType();
1673 }
1674
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001675 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001676 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1677 // and let Y be the lookup set produced by argument dependent
1678 // lookup (defined as follows). If X contains [...] then Y is
1679 // empty. Otherwise Y is the set of declarations found in the
1680 // namespaces associated with the argument types as described
1681 // below. The set of declarations found by the lookup of the name
1682 // is the union of X and Y.
1683 //
1684 // Here, we compute Y and add its members to the overloaded
1685 // candidate set.
1686 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001687 NSEnd = AssociatedNamespaces.end();
1688 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001689 // When considering an associated namespace, the lookup is the
1690 // same as the lookup performed when the associated namespace is
1691 // used as a qualifier (3.4.3.2) except that:
1692 //
1693 // -- Any using-directives in the associated namespace are
1694 // ignored.
1695 //
John McCallc7e8e792009-08-07 22:18:02 +00001696 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001697 // associated classes are visible within their respective
1698 // namespaces even if they are not visible during an ordinary
1699 // lookup (11.4).
1700 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00001701 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCallc7e8e792009-08-07 22:18:02 +00001702 Decl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00001703 // If the only declaration here is an ordinary friend, consider
1704 // it only if it was declared in an associated classes.
1705 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00001706 DeclContext *LexDC = D->getLexicalDeclContext();
1707 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1708 continue;
1709 }
Mike Stump11289f42009-09-09 15:08:12 +00001710
Sebastian Redlc057f422009-10-23 19:23:15 +00001711 FunctionDecl *Fn;
1712 if (!Operator || !(Fn = dyn_cast<FunctionDecl>(D)) ||
1713 IsAcceptableNonMemberOperatorCandidate(Fn, T1, T2, Context))
1714 CollectFunctionDecl(Functions, D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00001715 }
1716 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001717}