blob: 5e60cc8727aa8bfed53a9c49d497724110b9d588 [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 Gregor1c846b02009-01-16 00:38:09 +000030#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000031#include <vector>
32#include <iterator>
33#include <utility>
34#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000035
36using namespace clang;
37
John McCallf6c8a4e2009-11-10 07:01:13 +000038namespace {
39 class UnqualUsingEntry {
40 const DeclContext *Nominated;
41 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000042
John McCallf6c8a4e2009-11-10 07:01:13 +000043 public:
44 UnqualUsingEntry(const DeclContext *Nominated,
45 const DeclContext *CommonAncestor)
46 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
47 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000048
John McCallf6c8a4e2009-11-10 07:01:13 +000049 const DeclContext *getCommonAncestor() const {
50 return CommonAncestor;
51 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000052
John McCallf6c8a4e2009-11-10 07:01:13 +000053 const DeclContext *getNominatedNamespace() const {
54 return Nominated;
55 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000056
John McCallf6c8a4e2009-11-10 07:01:13 +000057 // Sort by the pointer value of the common ancestor.
58 struct Comparator {
59 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
60 return L.getCommonAncestor() < R.getCommonAncestor();
61 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000062
John McCallf6c8a4e2009-11-10 07:01:13 +000063 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
64 return E.getCommonAncestor() < DC;
65 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000066
John McCallf6c8a4e2009-11-10 07:01:13 +000067 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
68 return DC < E.getCommonAncestor();
69 }
70 };
71 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000072
John McCallf6c8a4e2009-11-10 07:01:13 +000073 /// A collection of using directives, as used by C++ unqualified
74 /// lookup.
75 class UnqualUsingDirectiveSet {
76 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000077
John McCallf6c8a4e2009-11-10 07:01:13 +000078 ListTy list;
79 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000080
John McCallf6c8a4e2009-11-10 07:01:13 +000081 public:
82 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000083
John McCallf6c8a4e2009-11-10 07:01:13 +000084 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
85 // C++ [namespace.udir]p1:
86 // During unqualified name lookup, the names appear as if they
87 // were declared in the nearest enclosing namespace which contains
88 // both the using-directive and the nominated namespace.
89 DeclContext *InnermostFileDC
90 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
91 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000092
John McCallf6c8a4e2009-11-10 07:01:13 +000093 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +000094 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
95 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
96 visit(Ctx, EffectiveDC);
97 } else {
98 Scope::udir_iterator I = S->using_directives_begin(),
99 End = S->using_directives_end();
100
101 for (; I != End; ++I)
102 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
103 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000104 }
105 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000106
107 // Visits a context and collect all of its using directives
108 // recursively. Treats all using directives as if they were
109 // declared in the context.
110 //
111 // A given context is only every visited once, so it is important
112 // that contexts be visited from the inside out in order to get
113 // the effective DCs right.
114 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
115 if (!visited.insert(DC))
116 return;
117
118 addUsingDirectives(DC, EffectiveDC);
119 }
120
121 // Visits a using directive and collects all of its using
122 // directives recursively. Treats all using directives as if they
123 // were declared in the effective DC.
124 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
125 DeclContext *NS = UD->getNominatedNamespace();
126 if (!visited.insert(NS))
127 return;
128
129 addUsingDirective(UD, EffectiveDC);
130 addUsingDirectives(NS, EffectiveDC);
131 }
132
133 // Adds all the using directives in a context (and those nominated
134 // by its using directives, transitively) as if they appeared in
135 // the given effective context.
136 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
137 llvm::SmallVector<DeclContext*,4> queue;
138 while (true) {
139 DeclContext::udir_iterator I, End;
140 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
141 UsingDirectiveDecl *UD = *I;
142 DeclContext *NS = UD->getNominatedNamespace();
143 if (visited.insert(NS)) {
144 addUsingDirective(UD, EffectiveDC);
145 queue.push_back(NS);
146 }
147 }
148
149 if (queue.empty())
150 return;
151
152 DC = queue.back();
153 queue.pop_back();
154 }
155 }
156
157 // Add a using directive as if it had been declared in the given
158 // context. This helps implement C++ [namespace.udir]p3:
159 // The using-directive is transitive: if a scope contains a
160 // using-directive that nominates a second namespace that itself
161 // contains using-directives, the effect is as if the
162 // using-directives from the second namespace also appeared in
163 // the first.
164 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
165 // Find the common ancestor between the effective context and
166 // the nominated namespace.
167 DeclContext *Common = UD->getNominatedNamespace();
168 while (!Common->Encloses(EffectiveDC))
169 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000170 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000171
172 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
173 }
174
175 void done() {
176 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
177 }
178
179 typedef ListTy::iterator iterator;
180 typedef ListTy::const_iterator const_iterator;
181
182 iterator begin() { return list.begin(); }
183 iterator end() { return list.end(); }
184 const_iterator begin() const { return list.begin(); }
185 const_iterator end() const { return list.end(); }
186
187 std::pair<const_iterator,const_iterator>
188 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000189 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000190 UnqualUsingEntry::Comparator());
191 }
192 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000193}
194
John McCallea305ed2009-12-18 10:40:03 +0000195static bool IsAcceptableIDNS(NamedDecl *D, unsigned IDNS) {
196 return D->isInIdentifierNamespace(IDNS);
197}
198
199static bool IsAcceptableOperatorName(NamedDecl *D, unsigned IDNS) {
200 return D->isInIdentifierNamespace(IDNS) &&
201 !D->getDeclContext()->isRecord();
202}
203
204static bool IsAcceptableNestedNameSpecifierName(NamedDecl *D, unsigned IDNS) {
205 return isa<TypedefDecl>(D) || D->isInIdentifierNamespace(Decl::IDNS_Tag);
206}
207
208static bool IsAcceptableNamespaceName(NamedDecl *D, unsigned IDNS) {
209 return isa<NamespaceDecl>(D) || isa<NamespaceAliasDecl>(D);
210}
211
212/// Gets the default result filter for the given lookup.
213static inline
214LookupResult::ResultFilter getResultFilter(Sema::LookupNameKind NameKind) {
215 switch (NameKind) {
216 case Sema::LookupOrdinaryName:
217 case Sema::LookupTagName:
218 case Sema::LookupMemberName:
219 case Sema::LookupRedeclarationWithLinkage: // FIXME: check linkage, scoping
220 case Sema::LookupUsingDeclName:
221 case Sema::LookupObjCProtocolName:
222 case Sema::LookupObjCImplementationName:
223 return &IsAcceptableIDNS;
224
225 case Sema::LookupOperatorName:
226 return &IsAcceptableOperatorName;
227
228 case Sema::LookupNestedNameSpecifierName:
229 return &IsAcceptableNestedNameSpecifierName;
230
231 case Sema::LookupNamespaceName:
232 return &IsAcceptableNamespaceName;
233 }
234
235 llvm_unreachable("unkknown lookup kind");
236 return 0;
237}
238
Douglas Gregor889ceb72009-02-03 19:21:40 +0000239// Retrieve the set of identifier namespaces that correspond to a
240// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000241static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
242 bool CPlusPlus,
243 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000244 unsigned IDNS = 0;
245 switch (NameKind) {
246 case Sema::LookupOrdinaryName:
Douglas Gregor94eabf32009-02-04 16:44:47 +0000247 case Sema::LookupOperatorName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000248 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000249 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000250 if (CPlusPlus) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000251 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
John McCallea305ed2009-12-18 10:40:03 +0000252 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
253 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000254 break;
255
256 case Sema::LookupTagName:
257 IDNS = Decl::IDNS_Tag;
John McCallea305ed2009-12-18 10:40:03 +0000258 if (CPlusPlus && Redeclaration)
259 IDNS |= Decl::IDNS_TagFriend;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000260 break;
261
262 case Sema::LookupMemberName:
263 IDNS = Decl::IDNS_Member;
264 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000265 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000266 break;
267
268 case Sema::LookupNestedNameSpecifierName:
269 case Sema::LookupNamespaceName:
270 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
271 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000272
John McCall84d87672009-12-10 09:41:52 +0000273 case Sema::LookupUsingDeclName:
274 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
275 | Decl::IDNS_Member | Decl::IDNS_Using;
276 break;
277
Douglas Gregor79947a22009-04-24 00:11:27 +0000278 case Sema::LookupObjCProtocolName:
279 IDNS = Decl::IDNS_ObjCProtocol;
280 break;
281
282 case Sema::LookupObjCImplementationName:
283 IDNS = Decl::IDNS_ObjCImplementation;
284 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000285 }
286 return IDNS;
287}
288
John McCallea305ed2009-12-18 10:40:03 +0000289void LookupResult::configure() {
290 IDNS = getIDNS(LookupKind,
291 SemaRef.getLangOptions().CPlusPlus,
292 isForRedeclaration());
293 IsAcceptableFn = getResultFilter(LookupKind);
294}
295
John McCall9f3059a2009-10-09 21:13:30 +0000296// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000297void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000298 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000299}
300
John McCall283b9012009-11-22 00:44:51 +0000301/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000302void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000303 unsigned N = Decls.size();
John McCall84d87672009-12-10 09:41:52 +0000304
John McCall9f3059a2009-10-09 21:13:30 +0000305 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000306 if (N == 0) {
307 assert(ResultKind == NotFound);
308 return;
309 }
310
John McCall283b9012009-11-22 00:44:51 +0000311 // If there's a single decl, we need to examine it to decide what
312 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000313 if (N == 1) {
John McCall283b9012009-11-22 00:44:51 +0000314 if (isa<FunctionTemplateDecl>(Decls[0]))
315 ResultKind = FoundOverloaded;
316 else if (isa<UnresolvedUsingValueDecl>(Decls[0]))
John McCalle61f2ba2009-11-18 02:36:19 +0000317 ResultKind = FoundUnresolvedValue;
318 return;
319 }
John McCall9f3059a2009-10-09 21:13:30 +0000320
John McCall6538c932009-10-10 05:48:19 +0000321 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000322 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000323
John McCall9f3059a2009-10-09 21:13:30 +0000324 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
325
326 bool Ambiguous = false;
327 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000328 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000329
330 unsigned UniqueTagIndex = 0;
331
332 unsigned I = 0;
333 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000334 NamedDecl *D = Decls[I]->getUnderlyingDecl();
335 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000336
John McCallf0f1cf02009-11-17 07:50:12 +0000337 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000338 // If it's not unique, pull something off the back (and
339 // continue at this index).
340 Decls[I] = Decls[--N];
John McCall9f3059a2009-10-09 21:13:30 +0000341 } else {
342 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000343
344 if (isa<UnresolvedUsingValueDecl>(D)) {
345 HasUnresolved = true;
346 } else if (isa<TagDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000347 if (HasTag)
348 Ambiguous = true;
349 UniqueTagIndex = I;
350 HasTag = true;
John McCall283b9012009-11-22 00:44:51 +0000351 } else if (isa<FunctionTemplateDecl>(D)) {
352 HasFunction = true;
353 HasFunctionTemplate = true;
354 } else if (isa<FunctionDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000355 HasFunction = true;
356 } else {
357 if (HasNonFunction)
358 Ambiguous = true;
359 HasNonFunction = true;
360 }
361 I++;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000362 }
Mike Stump11289f42009-09-09 15:08:12 +0000363 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000364
John McCall9f3059a2009-10-09 21:13:30 +0000365 // C++ [basic.scope.hiding]p2:
366 // A class name or enumeration name can be hidden by the name of
367 // an object, function, or enumerator declared in the same
368 // scope. If a class or enumeration name and an object, function,
369 // or enumerator are declared in the same scope (in any order)
370 // with the same name, the class or enumeration name is hidden
371 // wherever the object, function, or enumerator name is visible.
372 // But it's still an error if there are distinct tag types found,
373 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000374 if (HideTags && HasTag && !Ambiguous &&
375 (HasFunction || HasNonFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000376 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000377
John McCall9f3059a2009-10-09 21:13:30 +0000378 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000379
John McCall80053822009-12-03 00:58:24 +0000380 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000381 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000382
John McCall9f3059a2009-10-09 21:13:30 +0000383 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000384 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000385 else if (HasUnresolved)
386 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000387 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000388 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000389 else
John McCall27b18f82009-11-17 02:14:36 +0000390 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000391}
392
John McCall5cebab12009-11-18 07:57:50 +0000393void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000394 CXXBasePaths::paths_iterator I, E;
395 DeclContext::lookup_iterator DI, DE;
396 for (I = P.begin(), E = P.end(); I != E; ++I)
397 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
398 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000399}
400
John McCall5cebab12009-11-18 07:57:50 +0000401void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000402 Paths = new CXXBasePaths;
403 Paths->swap(P);
404 addDeclsFromBasePaths(*Paths);
405 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000406 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000407}
408
John McCall5cebab12009-11-18 07:57:50 +0000409void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000410 Paths = new CXXBasePaths;
411 Paths->swap(P);
412 addDeclsFromBasePaths(*Paths);
413 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000414 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000415}
416
John McCall5cebab12009-11-18 07:57:50 +0000417void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000418 Out << Decls.size() << " result(s)";
419 if (isAmbiguous()) Out << ", ambiguous";
420 if (Paths) Out << ", base paths present";
421
422 for (iterator I = begin(), E = end(); I != E; ++I) {
423 Out << "\n";
424 (*I)->print(Out, 2);
425 }
426}
427
428// Adds all qualifying matches for a name within a decl context to the
429// given lookup result. Returns true if any matches were found.
John McCall5cebab12009-11-18 07:57:50 +0000430static bool LookupDirect(LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000431 bool Found = false;
432
John McCallf6c8a4e2009-11-10 07:01:13 +0000433 DeclContext::lookup_const_iterator I, E;
John McCall27b18f82009-11-17 02:14:36 +0000434 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I)
John McCallea305ed2009-12-18 10:40:03 +0000435 if (R.isAcceptableDecl(*I))
John McCall9f3059a2009-10-09 21:13:30 +0000436 R.addDecl(*I), Found = true;
437
438 return Found;
439}
440
John McCallf6c8a4e2009-11-10 07:01:13 +0000441// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000442static bool
John McCall5cebab12009-11-18 07:57:50 +0000443CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCall27b18f82009-11-17 02:14:36 +0000444 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000445
446 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
447
John McCallf6c8a4e2009-11-10 07:01:13 +0000448 // Perform direct name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000449 bool Found = LookupDirect(R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000450
John McCallf6c8a4e2009-11-10 07:01:13 +0000451 // Perform direct name lookup into the namespaces nominated by the
452 // using directives whose common ancestor is this namespace.
453 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
454 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000455
John McCallf6c8a4e2009-11-10 07:01:13 +0000456 for (; UI != UEnd; ++UI)
John McCall27b18f82009-11-17 02:14:36 +0000457 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000458 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000459
460 R.resolveKind();
461
462 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000463}
464
465static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000466 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000467 return Ctx->isFileContext();
468 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000469}
Douglas Gregored8f2882009-01-30 01:04:22 +0000470
Douglas Gregor7f737c02009-09-10 16:57:35 +0000471// Find the next outer declaration context corresponding to this scope.
472static DeclContext *findOuterContext(Scope *S) {
473 for (S = S->getParent(); S; S = S->getParent())
474 if (S->getEntity())
475 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
476
477 return 0;
478}
479
John McCall27b18f82009-11-17 02:14:36 +0000480bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000481 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000482
483 DeclarationName Name = R.getLookupName();
484
Douglas Gregor889ceb72009-02-03 19:21:40 +0000485 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000486 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000487 I = IdResolver.begin(Name),
488 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000489
Douglas Gregor889ceb72009-02-03 19:21:40 +0000490 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000491 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000492 // ...During unqualified name lookup (3.4.1), the names appear as if
493 // they were declared in the nearest enclosing namespace which contains
494 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000495 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000496 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000497 //
498 // For example:
499 // namespace A { int i; }
500 // void foo() {
501 // int i;
502 // {
503 // using namespace A;
504 // ++i; // finds local 'i', A::i appears at global scope
505 // }
506 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000507 //
Douglas Gregor700792c2009-02-05 19:25:20 +0000508 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000509 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000510 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000511 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000512 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000513 Found = true;
514 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000515 }
516 }
John McCall9f3059a2009-10-09 21:13:30 +0000517 if (Found) {
518 R.resolveKind();
519 return true;
520 }
521
Douglas Gregor700792c2009-02-05 19:25:20 +0000522 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregor7f737c02009-09-10 16:57:35 +0000523 DeclContext *OuterCtx = findOuterContext(S);
524 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
525 Ctx = Ctx->getLookupParent()) {
Douglas Gregora64c1e52009-12-08 15:38:36 +0000526 // We do not directly look into function or method contexts
527 // (since all local variables are found via the identifier
528 // changes) or in transparent contexts (since those entities
529 // will be found in the nearest enclosing non-transparent
530 // context).
531 if (Ctx->isFunctionOrMethod() || Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000532 continue;
533
534 // Perform qualified name lookup into this context.
535 // FIXME: In some cases, we know that every name that could be found by
536 // this qualified name lookup will also be on the identifier chain. For
537 // example, inside a class without any base classes, we never need to
538 // perform qualified lookup because all of the members are on top of the
539 // identifier chain.
John McCall27b18f82009-11-17 02:14:36 +0000540 if (LookupQualifiedName(R, Ctx))
John McCall9f3059a2009-10-09 21:13:30 +0000541 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000542 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000543 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000544 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000545
John McCallf6c8a4e2009-11-10 07:01:13 +0000546 // Stop if we ran out of scopes.
547 // FIXME: This really, really shouldn't be happening.
548 if (!S) return false;
549
Douglas Gregor700792c2009-02-05 19:25:20 +0000550 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000551 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000552 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000553 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
554 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000555
John McCallf6c8a4e2009-11-10 07:01:13 +0000556 UnqualUsingDirectiveSet UDirs;
557 UDirs.visitScopeChain(Initial, S);
558 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000559
Douglas Gregor700792c2009-02-05 19:25:20 +0000560 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000561 // Unqualified name lookup in C++ requires looking into scopes
562 // that aren't strictly lexical, and therefore we walk through the
563 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000564
Douglas Gregor889ceb72009-02-03 19:21:40 +0000565 for (; S; S = S->getParent()) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000566 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregorf2270432009-08-24 18:55:03 +0000567 if (Ctx->isTransparentContext())
568 continue;
569
Douglas Gregor700792c2009-02-05 19:25:20 +0000570 assert(Ctx && Ctx->isFileContext() &&
571 "We should have been looking only at file context here already.");
Douglas Gregor889ceb72009-02-03 19:21:40 +0000572
573 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000574 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000575 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000576 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000577 // We found something. Look for anything else in our scope
578 // with this same name and in an acceptable identifier
579 // namespace, so that we can construct an overload set if we
580 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000581 Found = true;
582 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000583 }
584 }
585
Douglas Gregor700792c2009-02-05 19:25:20 +0000586 // Look into context considering using-directives.
John McCall27b18f82009-11-17 02:14:36 +0000587 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
John McCall9f3059a2009-10-09 21:13:30 +0000588 Found = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000589
John McCall9f3059a2009-10-09 21:13:30 +0000590 if (Found) {
591 R.resolveKind();
592 return true;
593 }
594
John McCall27b18f82009-11-17 02:14:36 +0000595 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000596 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000597 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000598
John McCall9f3059a2009-10-09 21:13:30 +0000599 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000600}
601
Douglas Gregor34074322009-01-14 22:20:51 +0000602/// @brief Perform unqualified name lookup starting from a given
603/// scope.
604///
605/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
606/// used to find names within the current scope. For example, 'x' in
607/// @code
608/// int x;
609/// int f() {
610/// return x; // unqualified name look finds 'x' in the global scope
611/// }
612/// @endcode
613///
614/// Different lookup criteria can find different names. For example, a
615/// particular scope can have both a struct and a function of the same
616/// name, and each can be found by certain lookup criteria. For more
617/// information about lookup criteria, see the documentation for the
618/// class LookupCriteria.
619///
620/// @param S The scope from which unqualified name lookup will
621/// begin. If the lookup criteria permits, name lookup may also search
622/// in the parent scopes.
623///
624/// @param Name The name of the entity that we are searching for.
625///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000626/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000627/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000628/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000629///
630/// @returns The result of name lookup, which includes zero or more
631/// declarations and possibly additional information used to diagnose
632/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000633bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
634 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +0000635 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000636
John McCall27b18f82009-11-17 02:14:36 +0000637 LookupNameKind NameKind = R.getLookupKind();
638
Douglas Gregor34074322009-01-14 22:20:51 +0000639 if (!getLangOptions().CPlusPlus) {
640 // Unqualified name lookup in C/Objective-C is purely lexical, so
641 // search in the declarations attached to the name.
642
John McCallea305ed2009-12-18 10:40:03 +0000643 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000644 // Find the nearest non-transparent declaration scope.
645 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000646 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000647 static_cast<DeclContext *>(S->getEntity())
648 ->isTransparentContext()))
649 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +0000650 }
651
John McCallea305ed2009-12-18 10:40:03 +0000652 unsigned IDNS = R.getIdentifierNamespace();
653
Douglas Gregor34074322009-01-14 22:20:51 +0000654 // Scan up the scope chain looking for a decl that matches this
655 // identifier that is in the appropriate namespace. This search
656 // should not take long, as shadowing of names is uncommon, and
657 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000658 bool LeftStartingScope = false;
659
Douglas Gregored8f2882009-01-30 01:04:22 +0000660 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000661 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000662 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000663 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000664 if (NameKind == LookupRedeclarationWithLinkage) {
665 // Determine whether this (or a previous) declaration is
666 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000667 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000668 LeftStartingScope = true;
669
670 // If we found something outside of our starting scope that
671 // does not have linkage, skip it.
672 if (LeftStartingScope && !((*I)->hasLinkage()))
673 continue;
674 }
675
John McCall9f3059a2009-10-09 21:13:30 +0000676 R.addDecl(*I);
677
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000678 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000679 // If this declaration has the "overloadable" attribute, we
680 // might have a set of overloaded functions.
681
682 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000683 while (!(S->getFlags() & Scope::DeclScope) ||
684 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000685 S = S->getParent();
686
687 // Find the last declaration in this scope (with the same
688 // name, naturally).
689 IdentifierResolver::iterator LastI = I;
690 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000691 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000692 break;
John McCall9f3059a2009-10-09 21:13:30 +0000693 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000694 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000695 }
696
John McCall9f3059a2009-10-09 21:13:30 +0000697 R.resolveKind();
698
699 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000700 }
Douglas Gregor34074322009-01-14 22:20:51 +0000701 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000702 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000703 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +0000704 return true;
Douglas Gregor34074322009-01-14 22:20:51 +0000705 }
706
707 // If we didn't find a use of this identifier, and if the identifier
708 // corresponds to a compiler builtin, create the decl object for the builtin
709 // now, injecting it into translation unit scope, and return it.
Mike Stump11289f42009-09-09 15:08:12 +0000710 if (NameKind == LookupOrdinaryName ||
Douglas Gregoreddf4332009-02-24 20:03:32 +0000711 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor34074322009-01-14 22:20:51 +0000712 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000713 if (II && AllowBuiltinCreation) {
Douglas Gregor34074322009-01-14 22:20:51 +0000714 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000715 if (unsigned BuiltinID = II->getBuiltinID()) {
716 // In C++, we don't have any predefined library functions like
717 // 'malloc'. Instead, we'll just error.
Mike Stump11289f42009-09-09 15:08:12 +0000718 if (getLangOptions().CPlusPlus &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000719 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCall9f3059a2009-10-09 21:13:30 +0000720 return false;
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000721
John McCall9f3059a2009-10-09 21:13:30 +0000722 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCall27b18f82009-11-17 02:14:36 +0000723 S, R.isForRedeclaration(),
724 R.getNameLoc());
John McCall9f3059a2009-10-09 21:13:30 +0000725 if (D) R.addDecl(D);
726 return (D != NULL);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000727 }
Douglas Gregor34074322009-01-14 22:20:51 +0000728 }
Douglas Gregor34074322009-01-14 22:20:51 +0000729 }
John McCall9f3059a2009-10-09 21:13:30 +0000730 return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000731}
732
John McCall6538c932009-10-10 05:48:19 +0000733/// @brief Perform qualified name lookup in the namespaces nominated by
734/// using directives by the given context.
735///
736/// C++98 [namespace.qual]p2:
737/// Given X::m (where X is a user-declared namespace), or given ::m
738/// (where X is the global namespace), let S be the set of all
739/// declarations of m in X and in the transitive closure of all
740/// namespaces nominated by using-directives in X and its used
741/// namespaces, except that using-directives are ignored in any
742/// namespace, including X, directly containing one or more
743/// declarations of m. No namespace is searched more than once in
744/// the lookup of a name. If S is the empty set, the program is
745/// ill-formed. Otherwise, if S has exactly one member, or if the
746/// context of the reference is a using-declaration
747/// (namespace.udecl), S is the required set of declarations of
748/// m. Otherwise if the use of m is not one that allows a unique
749/// declaration to be chosen from S, the program is ill-formed.
750/// C++98 [namespace.qual]p5:
751/// During the lookup of a qualified namespace member name, if the
752/// lookup finds more than one declaration of the member, and if one
753/// declaration introduces a class name or enumeration name and the
754/// other declarations either introduce the same object, the same
755/// enumerator or a set of functions, the non-type name hides the
756/// class or enumeration name if and only if the declarations are
757/// from the same namespace; otherwise (the declarations are from
758/// different namespaces), the program is ill-formed.
John McCall5cebab12009-11-18 07:57:50 +0000759static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +0000760 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +0000761 assert(StartDC->isFileContext() && "start context is not a file context");
762
763 DeclContext::udir_iterator I = StartDC->using_directives_begin();
764 DeclContext::udir_iterator E = StartDC->using_directives_end();
765
766 if (I == E) return false;
767
768 // We have at least added all these contexts to the queue.
769 llvm::DenseSet<DeclContext*> Visited;
770 Visited.insert(StartDC);
771
772 // We have not yet looked into these namespaces, much less added
773 // their "using-children" to the queue.
774 llvm::SmallVector<NamespaceDecl*, 8> Queue;
775
776 // We have already looked into the initial namespace; seed the queue
777 // with its using-children.
778 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +0000779 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +0000780 if (Visited.insert(ND).second)
781 Queue.push_back(ND);
782 }
783
784 // The easiest way to implement the restriction in [namespace.qual]p5
785 // is to check whether any of the individual results found a tag
786 // and, if so, to declare an ambiguity if the final result is not
787 // a tag.
788 bool FoundTag = false;
789 bool FoundNonTag = false;
790
John McCall5cebab12009-11-18 07:57:50 +0000791 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +0000792
793 bool Found = false;
794 while (!Queue.empty()) {
795 NamespaceDecl *ND = Queue.back();
796 Queue.pop_back();
797
798 // We go through some convolutions here to avoid copying results
799 // between LookupResults.
800 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +0000801 LookupResult &DirectR = UseLocal ? LocalR : R;
John McCall27b18f82009-11-17 02:14:36 +0000802 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +0000803
804 if (FoundDirect) {
805 // First do any local hiding.
806 DirectR.resolveKind();
807
808 // If the local result is a tag, remember that.
809 if (DirectR.isSingleTagDecl())
810 FoundTag = true;
811 else
812 FoundNonTag = true;
813
814 // Append the local results to the total results if necessary.
815 if (UseLocal) {
816 R.addAllDecls(LocalR);
817 LocalR.clear();
818 }
819 }
820
821 // If we find names in this namespace, ignore its using directives.
822 if (FoundDirect) {
823 Found = true;
824 continue;
825 }
826
827 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
828 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
829 if (Visited.insert(Nom).second)
830 Queue.push_back(Nom);
831 }
832 }
833
834 if (Found) {
835 if (FoundTag && FoundNonTag)
836 R.setAmbiguousQualifiedTagHiding();
837 else
838 R.resolveKind();
839 }
840
841 return Found;
842}
843
Douglas Gregor34074322009-01-14 22:20:51 +0000844/// @brief Perform qualified name lookup into a given context.
845///
846/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
847/// names when the context of those names is explicit specified, e.g.,
848/// "std::vector" or "x->member".
849///
850/// Different lookup criteria can find different names. For example, a
851/// particular scope can have both a struct and a function of the same
852/// name, and each can be found by certain lookup criteria. For more
853/// information about lookup criteria, see the documentation for the
854/// class LookupCriteria.
855///
856/// @param LookupCtx The context in which qualified name lookup will
857/// search. If the lookup criteria permits, name lookup may also search
858/// in the parent contexts or (for C++ classes) base classes.
859///
860/// @param Name The name of the entity that we are searching for.
861///
862/// @param Criteria The criteria that this routine will use to
863/// determine which names are visible and which names will be
864/// found. Note that name lookup will find a name that is visible by
865/// the given criteria, but the entity itself may not be semantically
866/// correct or even the kind of entity expected based on the
867/// lookup. For example, searching for a nested-name-specifier name
868/// might result in an EnumDecl, which is visible but is not permitted
869/// as a nested-name-specifier in C++03.
870///
871/// @returns The result of name lookup, which includes zero or more
872/// declarations and possibly additional information used to diagnose
873/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000874bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx) {
Douglas Gregor34074322009-01-14 22:20:51 +0000875 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +0000876
John McCall27b18f82009-11-17 02:14:36 +0000877 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +0000878 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000879
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000880 // Make sure that the declaration context is complete.
881 assert((!isa<TagDecl>(LookupCtx) ||
882 LookupCtx->isDependentContext() ||
883 cast<TagDecl>(LookupCtx)->isDefinition() ||
884 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
885 ->isBeingDefined()) &&
886 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +0000887
Douglas Gregor34074322009-01-14 22:20:51 +0000888 // Perform qualified name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000889 if (LookupDirect(R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +0000890 R.resolveKind();
891 return true;
892 }
Douglas Gregor34074322009-01-14 22:20:51 +0000893
John McCall6538c932009-10-10 05:48:19 +0000894 // Don't descend into implied contexts for redeclarations.
895 // C++98 [namespace.qual]p6:
896 // In a declaration for a namespace member in which the
897 // declarator-id is a qualified-id, given that the qualified-id
898 // for the namespace member has the form
899 // nested-name-specifier unqualified-id
900 // the unqualified-id shall name a member of the namespace
901 // designated by the nested-name-specifier.
902 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +0000903 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +0000904 return false;
905
John McCall27b18f82009-11-17 02:14:36 +0000906 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +0000907 if (LookupCtx->isFileContext())
John McCall27b18f82009-11-17 02:14:36 +0000908 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +0000909
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000910 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +0000911 // classes, we're done.
John McCall6538c932009-10-10 05:48:19 +0000912 if (!isa<CXXRecordDecl>(LookupCtx))
John McCall9f3059a2009-10-09 21:13:30 +0000913 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000914
915 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +0000916 CXXRecordDecl *LookupRec = cast<CXXRecordDecl>(LookupCtx);
917 CXXBasePaths Paths;
918 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000919
920 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +0000921 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +0000922 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000923 case LookupOrdinaryName:
924 case LookupMemberName:
925 case LookupRedeclarationWithLinkage:
926 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
927 break;
928
929 case LookupTagName:
930 BaseCallback = &CXXRecordDecl::FindTagMember;
931 break;
John McCall84d87672009-12-10 09:41:52 +0000932
933 case LookupUsingDeclName:
934 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +0000935
936 case LookupOperatorName:
937 case LookupNamespaceName:
938 case LookupObjCProtocolName:
939 case LookupObjCImplementationName:
Douglas Gregor36d1b142009-10-06 17:59:45 +0000940 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +0000941 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000942
943 case LookupNestedNameSpecifierName:
944 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
945 break;
946 }
947
John McCall27b18f82009-11-17 02:14:36 +0000948 if (!LookupRec->lookupInBases(BaseCallback,
949 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +0000950 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000951
952 // C++ [class.member.lookup]p2:
953 // [...] If the resulting set of declarations are not all from
954 // sub-objects of the same type, or the set has a nonstatic member
955 // and includes members from distinct sub-objects, there is an
956 // ambiguity and the program is ill-formed. Otherwise that set is
957 // the result of the lookup.
958 // FIXME: support using declarations!
959 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +0000960 int SubobjectNumber = 0;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000961 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000962 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000963 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000964
965 // Determine whether we're looking at a distinct sub-object or not.
966 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +0000967 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000968 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
969 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +0000970 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000971 != Context.getCanonicalType(PathElement.Base->getType())) {
972 // We found members of the given name in two subobjects of
973 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +0000974 R.setAmbiguousBaseSubobjectTypes(Paths);
975 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000976 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
977 // We have a different subobject of the same type.
978
979 // C++ [class.member.lookup]p5:
980 // A static member, a nested type or an enumerator defined in
981 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +0000982 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000983 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000984 if (isa<VarDecl>(FirstDecl) ||
985 isa<TypeDecl>(FirstDecl) ||
986 isa<EnumConstantDecl>(FirstDecl))
987 continue;
988
989 if (isa<CXXMethodDecl>(FirstDecl)) {
990 // Determine whether all of the methods are static.
991 bool AllMethodsAreStatic = true;
992 for (DeclContext::lookup_iterator Func = Path->Decls.first;
993 Func != Path->Decls.second; ++Func) {
994 if (!isa<CXXMethodDecl>(*Func)) {
995 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
996 break;
997 }
998
999 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1000 AllMethodsAreStatic = false;
1001 break;
1002 }
1003 }
1004
1005 if (AllMethodsAreStatic)
1006 continue;
1007 }
1008
1009 // We have found a nonstatic member name in multiple, distinct
1010 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001011 R.setAmbiguousBaseSubobjects(Paths);
1012 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001013 }
1014 }
1015
1016 // Lookup in a base class succeeded; return these results.
1017
John McCall9f3059a2009-10-09 21:13:30 +00001018 DeclContext::lookup_iterator I, E;
1019 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I)
1020 R.addDecl(*I);
1021 R.resolveKind();
1022 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001023}
1024
1025/// @brief Performs name lookup for a name that was parsed in the
1026/// source code, and may contain a C++ scope specifier.
1027///
1028/// This routine is a convenience routine meant to be called from
1029/// contexts that receive a name and an optional C++ scope specifier
1030/// (e.g., "N::M::x"). It will then perform either qualified or
1031/// unqualified name lookup (with LookupQualifiedName or LookupName,
1032/// respectively) on the given name and return those results.
1033///
1034/// @param S The scope from which unqualified name lookup will
1035/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001036///
Douglas Gregore861bac2009-08-25 22:51:20 +00001037/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001038///
1039/// @param Name The name of the entity that name lookup will
1040/// search for.
1041///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001042/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001043/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001044/// C library functions (like "malloc") are implicitly declared.
1045///
Douglas Gregore861bac2009-08-25 22:51:20 +00001046/// @param EnteringContext Indicates whether we are going to enter the
1047/// context of the scope-specifier SS (if present).
1048///
John McCall9f3059a2009-10-09 21:13:30 +00001049/// @returns True if any decls were found (but possibly ambiguous)
1050bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001051 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001052 if (SS && SS->isInvalid()) {
1053 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001054 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001055 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001056 }
Mike Stump11289f42009-09-09 15:08:12 +00001057
Douglas Gregore861bac2009-08-25 22:51:20 +00001058 if (SS && SS->isSet()) {
1059 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001060 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001061 // contex, and will perform name lookup in that context.
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001062 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCall9f3059a2009-10-09 21:13:30 +00001063 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001064
John McCall27b18f82009-11-17 02:14:36 +00001065 R.setContextRange(SS->getRange());
1066
1067 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001068 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001069
Douglas Gregore861bac2009-08-25 22:51:20 +00001070 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001071 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001072 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001073 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001074 }
1075
Mike Stump11289f42009-09-09 15:08:12 +00001076 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001077 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001078}
1079
Douglas Gregor889ceb72009-02-03 19:21:40 +00001080
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001081/// @brief Produce a diagnostic describing the ambiguity that resulted
1082/// from name lookup.
1083///
1084/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001085///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001086/// @param Name The name of the entity that name lookup was
1087/// searching for.
1088///
1089/// @param NameLoc The location of the name within the source code.
1090///
1091/// @param LookupRange A source range that provides more
1092/// source-location information concerning the lookup itself. For
1093/// example, this range might highlight a nested-name-specifier that
1094/// precedes the name.
1095///
1096/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001097bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001098 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1099
John McCall27b18f82009-11-17 02:14:36 +00001100 DeclarationName Name = Result.getLookupName();
1101 SourceLocation NameLoc = Result.getNameLoc();
1102 SourceRange LookupRange = Result.getContextRange();
1103
John McCall6538c932009-10-10 05:48:19 +00001104 switch (Result.getAmbiguityKind()) {
1105 case LookupResult::AmbiguousBaseSubobjects: {
1106 CXXBasePaths *Paths = Result.getBasePaths();
1107 QualType SubobjectType = Paths->front().back().Base->getType();
1108 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1109 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1110 << LookupRange;
1111
1112 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1113 while (isa<CXXMethodDecl>(*Found) &&
1114 cast<CXXMethodDecl>(*Found)->isStatic())
1115 ++Found;
1116
1117 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1118
1119 return true;
1120 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001121
John McCall6538c932009-10-10 05:48:19 +00001122 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001123 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1124 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001125
1126 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001127 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001128 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1129 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001130 Path != PathEnd; ++Path) {
1131 Decl *D = *Path->Decls.first;
1132 if (DeclsPrinted.insert(D).second)
1133 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1134 }
1135
Douglas Gregor1c846b02009-01-16 00:38:09 +00001136 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001137 }
1138
John McCall6538c932009-10-10 05:48:19 +00001139 case LookupResult::AmbiguousTagHiding: {
1140 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001141
John McCall6538c932009-10-10 05:48:19 +00001142 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1143
1144 LookupResult::iterator DI, DE = Result.end();
1145 for (DI = Result.begin(); DI != DE; ++DI)
1146 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1147 TagDecls.insert(TD);
1148 Diag(TD->getLocation(), diag::note_hidden_tag);
1149 }
1150
1151 for (DI = Result.begin(); DI != DE; ++DI)
1152 if (!isa<TagDecl>(*DI))
1153 Diag((*DI)->getLocation(), diag::note_hiding_object);
1154
1155 // For recovery purposes, go ahead and implement the hiding.
1156 Result.hideDecls(TagDecls);
1157
1158 return true;
1159 }
1160
1161 case LookupResult::AmbiguousReference: {
1162 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001163
John McCall6538c932009-10-10 05:48:19 +00001164 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1165 for (; DI != DE; ++DI)
1166 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001167
John McCall6538c932009-10-10 05:48:19 +00001168 return true;
1169 }
1170 }
1171
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001172 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001173 return true;
1174}
Douglas Gregore254f902009-02-04 00:32:51 +00001175
Mike Stump11289f42009-09-09 15:08:12 +00001176static void
1177addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001178 ASTContext &Context,
1179 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001180 Sema::AssociatedClassSet &AssociatedClasses);
1181
1182static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1183 DeclContext *Ctx) {
1184 if (Ctx->isFileContext())
1185 Namespaces.insert(Ctx);
1186}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001187
Mike Stump11289f42009-09-09 15:08:12 +00001188// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001189// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001190static void
1191addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
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) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001195 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001196 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001197 switch (Arg.getKind()) {
1198 case TemplateArgument::Null:
1199 break;
Mike Stump11289f42009-09-09 15:08:12 +00001200
Douglas Gregor197e5f72009-07-08 07:51:57 +00001201 case TemplateArgument::Type:
1202 // [...] the namespaces and classes associated with the types of the
1203 // template arguments provided for template type parameters (excluding
1204 // template template parameters)
1205 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1206 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001207 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001208 break;
Mike Stump11289f42009-09-09 15:08:12 +00001209
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001210 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001211 // [...] the namespaces in which any template template arguments are
1212 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001213 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001214 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001215 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001216 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001217 DeclContext *Ctx = ClassTemplate->getDeclContext();
1218 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1219 AssociatedClasses.insert(EnclosingClass);
1220 // Add the associated namespace for this class.
1221 while (Ctx->isRecord())
1222 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001223 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001224 }
1225 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001226 }
1227
1228 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001229 case TemplateArgument::Integral:
1230 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001231 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001232 // associated namespaces. ]
1233 break;
Mike Stump11289f42009-09-09 15:08:12 +00001234
Douglas Gregor197e5f72009-07-08 07:51:57 +00001235 case TemplateArgument::Pack:
1236 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1237 PEnd = Arg.pack_end();
1238 P != PEnd; ++P)
1239 addAssociatedClassesAndNamespaces(*P, Context,
1240 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001241 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001242 break;
1243 }
1244}
1245
Douglas Gregore254f902009-02-04 00:32:51 +00001246// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001247// argument-dependent lookup with an argument of class type
1248// (C++ [basic.lookup.koenig]p2).
1249static void
1250addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregore254f902009-02-04 00:32:51 +00001251 ASTContext &Context,
1252 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001253 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001254 // C++ [basic.lookup.koenig]p2:
1255 // [...]
1256 // -- If T is a class type (including unions), its associated
1257 // classes are: the class itself; the class of which it is a
1258 // member, if any; and its direct and indirect base
1259 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001260 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001261
1262 // Add the class of which it is a member, if any.
1263 DeclContext *Ctx = Class->getDeclContext();
1264 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1265 AssociatedClasses.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001266 // Add the associated namespace for this class.
1267 while (Ctx->isRecord())
1268 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001269 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001270
Douglas Gregore254f902009-02-04 00:32:51 +00001271 // Add the class itself. If we've already seen this class, we don't
1272 // need to visit base classes.
1273 if (!AssociatedClasses.insert(Class))
1274 return;
1275
Mike Stump11289f42009-09-09 15:08:12 +00001276 // -- If T is a template-id, its associated namespaces and classes are
1277 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001278 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001279 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001280 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001281 // namespaces in which any template template arguments are defined; and
1282 // the classes in which any member templates used as template template
1283 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001284 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001285 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001286 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1287 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1288 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1289 AssociatedClasses.insert(EnclosingClass);
1290 // Add the associated namespace for this class.
1291 while (Ctx->isRecord())
1292 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001293 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001294
Douglas Gregor197e5f72009-07-08 07:51:57 +00001295 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1296 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1297 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1298 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001299 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001300 }
Mike Stump11289f42009-09-09 15:08:12 +00001301
Douglas Gregore254f902009-02-04 00:32:51 +00001302 // Add direct and indirect base classes along with their associated
1303 // namespaces.
1304 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1305 Bases.push_back(Class);
1306 while (!Bases.empty()) {
1307 // Pop this class off the stack.
1308 Class = Bases.back();
1309 Bases.pop_back();
1310
1311 // Visit the base classes.
1312 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1313 BaseEnd = Class->bases_end();
1314 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001315 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001316 // In dependent contexts, we do ADL twice, and the first time around,
1317 // the base type might be a dependent TemplateSpecializationType, or a
1318 // TemplateTypeParmType. If that happens, simply ignore it.
1319 // FIXME: If we want to support export, we probably need to add the
1320 // namespace of the template in a TemplateSpecializationType, or even
1321 // the classes and namespaces of known non-dependent arguments.
1322 if (!BaseType)
1323 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001324 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1325 if (AssociatedClasses.insert(BaseDecl)) {
1326 // Find the associated namespace for this base class.
1327 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1328 while (BaseCtx->isRecord())
1329 BaseCtx = BaseCtx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001330 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001331
1332 // Make sure we visit the bases of this base class.
1333 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1334 Bases.push_back(BaseDecl);
1335 }
1336 }
1337 }
1338}
1339
1340// \brief Add the associated classes and namespaces for
1341// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001342// (C++ [basic.lookup.koenig]p2).
1343static void
1344addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregore254f902009-02-04 00:32:51 +00001345 ASTContext &Context,
1346 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001347 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001348 // C++ [basic.lookup.koenig]p2:
1349 //
1350 // For each argument type T in the function call, there is a set
1351 // of zero or more associated namespaces and a set of zero or more
1352 // associated classes to be considered. The sets of namespaces and
1353 // classes is determined entirely by the types of the function
1354 // arguments (and the namespace of any template template
1355 // argument). Typedef names and using-declarations used to specify
1356 // the types do not contribute to this set. The sets of namespaces
1357 // and classes are determined in the following way:
1358 T = Context.getCanonicalType(T).getUnqualifiedType();
1359
1360 // -- If T is a pointer to U or an array of U, its associated
Mike Stump11289f42009-09-09 15:08:12 +00001361 // namespaces and classes are those associated with U.
Douglas Gregore254f902009-02-04 00:32:51 +00001362 //
1363 // We handle this by unwrapping pointer and array types immediately,
1364 // to avoid unnecessary recursion.
1365 while (true) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001366 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001367 T = Ptr->getPointeeType();
1368 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1369 T = Ptr->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001370 else
Douglas Gregore254f902009-02-04 00:32:51 +00001371 break;
1372 }
1373
1374 // -- If T is a fundamental type, its associated sets of
1375 // namespaces and classes are both empty.
John McCall9dd450b2009-09-21 23:43:11 +00001376 if (T->getAs<BuiltinType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001377 return;
1378
1379 // -- If T is a class type (including unions), its associated
1380 // classes are: the class itself; the class of which it is a
1381 // member, if any; and its direct and indirect base
1382 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001383 // which its associated classes are defined.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001384 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump11289f42009-09-09 15:08:12 +00001385 if (CXXRecordDecl *ClassDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001386 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001387 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1388 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001389 AssociatedClasses);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001390 return;
1391 }
Douglas Gregore254f902009-02-04 00:32:51 +00001392
1393 // -- If T is an enumeration type, its associated namespace is
1394 // the namespace in which it is defined. If it is class
1395 // member, its associated class is the member’s class; else
Mike Stump11289f42009-09-09 15:08:12 +00001396 // it has no associated class.
John McCall9dd450b2009-09-21 23:43:11 +00001397 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001398 EnumDecl *Enum = EnumT->getDecl();
1399
1400 DeclContext *Ctx = Enum->getDeclContext();
1401 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1402 AssociatedClasses.insert(EnclosingClass);
1403
1404 // Add the associated namespace for this class.
1405 while (Ctx->isRecord())
1406 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001407 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001408
1409 return;
1410 }
1411
1412 // -- If T is a function type, its associated namespaces and
1413 // classes are those associated with the function parameter
1414 // types and those associated with the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001415 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001416 // Return type
John McCall9dd450b2009-09-21 23:43:11 +00001417 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregore254f902009-02-04 00:32:51 +00001418 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001419 AssociatedNamespaces, AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001420
John McCall9dd450b2009-09-21 23:43:11 +00001421 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregore254f902009-02-04 00:32:51 +00001422 if (!Proto)
1423 return;
1424
1425 // Argument types
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001426 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001427 ArgEnd = Proto->arg_type_end();
Douglas Gregore254f902009-02-04 00:32:51 +00001428 Arg != ArgEnd; ++Arg)
1429 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallc7e8e792009-08-07 22:18:02 +00001430 AssociatedNamespaces, AssociatedClasses);
Mike Stump11289f42009-09-09 15:08:12 +00001431
Douglas Gregore254f902009-02-04 00:32:51 +00001432 return;
1433 }
1434
1435 // -- If T is a pointer to a member function of a class X, its
1436 // associated namespaces and classes are those associated
1437 // with the function parameter types and return type,
Mike Stump11289f42009-09-09 15:08:12 +00001438 // together with those associated with X.
Douglas Gregore254f902009-02-04 00:32:51 +00001439 //
1440 // -- If T is a pointer to a data member of class X, its
1441 // associated namespaces and classes are those associated
1442 // with the member type together with those associated with
Mike Stump11289f42009-09-09 15:08:12 +00001443 // X.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001444 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001445 // Handle the type that the pointer to member points to.
1446 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1447 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001448 AssociatedNamespaces,
1449 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001450
1451 // Handle the class type into which this points.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001452 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001453 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1454 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001455 AssociatedNamespaces,
1456 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001457
1458 return;
1459 }
1460
1461 // FIXME: What about block pointers?
1462 // FIXME: What about Objective-C message sends?
1463}
1464
1465/// \brief Find the associated classes and namespaces for
1466/// argument-dependent lookup for a call with the given set of
1467/// arguments.
1468///
1469/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001470/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001471/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001472void
Douglas Gregore254f902009-02-04 00:32:51 +00001473Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1474 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001475 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001476 AssociatedNamespaces.clear();
1477 AssociatedClasses.clear();
1478
1479 // C++ [basic.lookup.koenig]p2:
1480 // For each argument type T in the function call, there is a set
1481 // of zero or more associated namespaces and a set of zero or more
1482 // associated classes to be considered. The sets of namespaces and
1483 // classes is determined entirely by the types of the function
1484 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001485 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001486 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1487 Expr *Arg = Args[ArgIdx];
1488
1489 if (Arg->getType() != Context.OverloadTy) {
1490 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001491 AssociatedNamespaces,
1492 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001493 continue;
1494 }
1495
1496 // [...] In addition, if the argument is the name or address of a
1497 // set of overloaded functions and/or function templates, its
1498 // associated classes and namespaces are the union of those
1499 // associated with each of the members of the set: the namespace
1500 // in which the function or function template is defined and the
1501 // classes and namespaces associated with its (non-dependent)
1502 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001503 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001504 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1505 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1506 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001507
John McCalld14a8642009-11-21 08:51:07 +00001508 // TODO: avoid the copies. This should be easy when the cases
1509 // share a storage implementation.
1510 llvm::SmallVector<NamedDecl*, 8> Functions;
1511
1512 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1513 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00001514 else
Douglas Gregore254f902009-02-04 00:32:51 +00001515 continue;
1516
John McCalld14a8642009-11-21 08:51:07 +00001517 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1518 E = Functions.end(); I != E; ++I) {
1519 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001520 if (!FDecl)
John McCalld14a8642009-11-21 08:51:07 +00001521 FDecl = cast<FunctionTemplateDecl>(*I)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001522
1523 // Add the namespace in which this function was defined. Note
1524 // that, if this is a member function, we do *not* consider the
1525 // enclosing namespace of its class.
1526 DeclContext *Ctx = FDecl->getDeclContext();
John McCallc7e8e792009-08-07 22:18:02 +00001527 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001528
1529 // Add the classes and namespaces associated with the parameter
1530 // types and return type of this function.
1531 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001532 AssociatedNamespaces,
1533 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001534 }
1535 }
1536}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001537
1538/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1539/// an acceptable non-member overloaded operator for a call whose
1540/// arguments have types T1 (and, if non-empty, T2). This routine
1541/// implements the check in C++ [over.match.oper]p3b2 concerning
1542/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001543static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001544IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1545 QualType T1, QualType T2,
1546 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001547 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1548 return true;
1549
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001550 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1551 return true;
1552
John McCall9dd450b2009-09-21 23:43:11 +00001553 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001554 if (Proto->getNumArgs() < 1)
1555 return false;
1556
1557 if (T1->isEnumeralType()) {
1558 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001559 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001560 return true;
1561 }
1562
1563 if (Proto->getNumArgs() < 2)
1564 return false;
1565
1566 if (!T2.isNull() && T2->isEnumeralType()) {
1567 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001568 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001569 return true;
1570 }
1571
1572 return false;
1573}
1574
John McCall5cebab12009-11-18 07:57:50 +00001575NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1576 LookupNameKind NameKind,
1577 RedeclarationKind Redecl) {
1578 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1579 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00001580 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00001581}
1582
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001583/// \brief Find the protocol with the given name, if any.
1584ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001585 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001586 return cast_or_null<ObjCProtocolDecl>(D);
1587}
1588
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001589void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001590 QualType T1, QualType T2,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001591 FunctionSet &Functions) {
1592 // C++ [over.match.oper]p3:
1593 // -- The set of non-member candidates is the result of the
1594 // unqualified lookup of operator@ in the context of the
1595 // expression according to the usual rules for name lookup in
1596 // unqualified function calls (3.4.2) except that all member
1597 // functions are ignored. However, if no operand has a class
1598 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001599 // that have a first parameter of type T1 or "reference to
1600 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001601 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001602 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001603 // when T2 is an enumeration type, are candidate functions.
1604 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00001605 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1606 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00001607
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001608 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1609
John McCall9f3059a2009-10-09 21:13:30 +00001610 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001611 return;
1612
1613 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1614 Op != OpEnd; ++Op) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001615 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001616 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1617 Functions.insert(FD); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001618 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor15448f82009-06-27 21:05:07 +00001619 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1620 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001621 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001622 // later?
1623 if (!FunTmpl->getDeclContext()->isRecord())
1624 Functions.insert(FunTmpl);
1625 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001626 }
1627}
1628
John McCallc7e8e792009-08-07 22:18:02 +00001629static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1630 Decl *D) {
1631 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1632 Functions.insert(Func);
1633 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1634 Functions.insert(FunTmpl);
1635}
1636
Sebastian Redlc057f422009-10-23 19:23:15 +00001637void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001638 Expr **Args, unsigned NumArgs,
1639 FunctionSet &Functions) {
1640 // Find all of the associated namespaces and classes based on the
1641 // arguments we have.
1642 AssociatedNamespaceSet AssociatedNamespaces;
1643 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00001644 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00001645 AssociatedNamespaces,
1646 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001647
Sebastian Redlc057f422009-10-23 19:23:15 +00001648 QualType T1, T2;
1649 if (Operator) {
1650 T1 = Args[0]->getType();
1651 if (NumArgs >= 2)
1652 T2 = Args[1]->getType();
1653 }
1654
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001655 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001656 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1657 // and let Y be the lookup set produced by argument dependent
1658 // lookup (defined as follows). If X contains [...] then Y is
1659 // empty. Otherwise Y is the set of declarations found in the
1660 // namespaces associated with the argument types as described
1661 // below. The set of declarations found by the lookup of the name
1662 // is the union of X and Y.
1663 //
1664 // Here, we compute Y and add its members to the overloaded
1665 // candidate set.
1666 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001667 NSEnd = AssociatedNamespaces.end();
1668 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001669 // When considering an associated namespace, the lookup is the
1670 // same as the lookup performed when the associated namespace is
1671 // used as a qualifier (3.4.3.2) except that:
1672 //
1673 // -- Any using-directives in the associated namespace are
1674 // ignored.
1675 //
John McCallc7e8e792009-08-07 22:18:02 +00001676 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001677 // associated classes are visible within their respective
1678 // namespaces even if they are not visible during an ordinary
1679 // lookup (11.4).
1680 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00001681 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCallc7e8e792009-08-07 22:18:02 +00001682 Decl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00001683 // If the only declaration here is an ordinary friend, consider
1684 // it only if it was declared in an associated classes.
1685 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00001686 DeclContext *LexDC = D->getLexicalDeclContext();
1687 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1688 continue;
1689 }
Mike Stump11289f42009-09-09 15:08:12 +00001690
Sebastian Redlc057f422009-10-23 19:23:15 +00001691 FunctionDecl *Fn;
1692 if (!Operator || !(Fn = dyn_cast<FunctionDecl>(D)) ||
1693 IsAcceptableNonMemberOperatorCandidate(Fn, T1, T2, Context))
1694 CollectFunctionDecl(Functions, D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00001695 }
1696 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001697}