blob: 1ddfef839fd64d15d7e5bc97f4e495a3325350c9 [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
Douglas Gregor889ceb72009-02-03 19:21:40 +0000195// Retrieve the set of identifier namespaces that correspond to a
196// specific kind of name lookup.
Mike Stump11289f42009-09-09 15:08:12 +0000197inline unsigned
198getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
Douglas Gregor889ceb72009-02-03 19:21:40 +0000199 bool CPlusPlus) {
200 unsigned IDNS = 0;
201 switch (NameKind) {
202 case Sema::LookupOrdinaryName:
Douglas Gregor94eabf32009-02-04 16:44:47 +0000203 case Sema::LookupOperatorName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000204 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205 IDNS = Decl::IDNS_Ordinary;
206 if (CPlusPlus)
207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
208 break;
209
210 case Sema::LookupTagName:
211 IDNS = Decl::IDNS_Tag;
212 break;
213
214 case Sema::LookupMemberName:
215 IDNS = Decl::IDNS_Member;
216 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000217 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000218 break;
219
220 case Sema::LookupNestedNameSpecifierName:
221 case Sema::LookupNamespaceName:
222 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
223 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000224
Douglas Gregor79947a22009-04-24 00:11:27 +0000225 case Sema::LookupObjCProtocolName:
226 IDNS = Decl::IDNS_ObjCProtocol;
227 break;
228
229 case Sema::LookupObjCImplementationName:
230 IDNS = Decl::IDNS_ObjCImplementation;
231 break;
232
233 case Sema::LookupObjCCategoryImplName:
234 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000235 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000236 }
237 return IDNS;
238}
239
John McCall9f3059a2009-10-09 21:13:30 +0000240// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000241void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000242 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000243}
244
John McCall283b9012009-11-22 00:44:51 +0000245/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000246void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000247 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.
John McCall1f82f242009-11-18 22:49:29 +0000250 if (N == 0) {
251 assert(ResultKind == NotFound);
252 return;
253 }
254
John McCall283b9012009-11-22 00:44:51 +0000255 // If there's a single decl, we need to examine it to decide what
256 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000257 if (N == 1) {
John McCall283b9012009-11-22 00:44:51 +0000258 if (isa<FunctionTemplateDecl>(Decls[0]))
259 ResultKind = FoundOverloaded;
260 else if (isa<UnresolvedUsingValueDecl>(Decls[0]))
John McCalle61f2ba2009-11-18 02:36:19 +0000261 ResultKind = FoundUnresolvedValue;
262 return;
263 }
John McCall9f3059a2009-10-09 21:13:30 +0000264
John McCall6538c932009-10-10 05:48:19 +0000265 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000266 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000267
John McCall9f3059a2009-10-09 21:13:30 +0000268 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
269
270 bool Ambiguous = false;
271 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000272 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000273
274 unsigned UniqueTagIndex = 0;
275
276 unsigned I = 0;
277 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000278 NamedDecl *D = Decls[I]->getUnderlyingDecl();
279 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000280
John McCallf0f1cf02009-11-17 07:50:12 +0000281 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000282 // If it's not unique, pull something off the back (and
283 // continue at this index).
284 Decls[I] = Decls[--N];
John McCall9f3059a2009-10-09 21:13:30 +0000285 } else {
286 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000287
288 if (isa<UnresolvedUsingValueDecl>(D)) {
289 HasUnresolved = true;
290 } else if (isa<TagDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000291 if (HasTag)
292 Ambiguous = true;
293 UniqueTagIndex = I;
294 HasTag = true;
John McCall283b9012009-11-22 00:44:51 +0000295 } else if (isa<FunctionTemplateDecl>(D)) {
296 HasFunction = true;
297 HasFunctionTemplate = true;
298 } else if (isa<FunctionDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000299 HasFunction = true;
300 } else {
301 if (HasNonFunction)
302 Ambiguous = true;
303 HasNonFunction = true;
304 }
305 I++;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000306 }
Mike Stump11289f42009-09-09 15:08:12 +0000307 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000308
John McCall9f3059a2009-10-09 21:13:30 +0000309 // C++ [basic.scope.hiding]p2:
310 // A class name or enumeration name can be hidden by the name of
311 // an object, function, or enumerator declared in the same
312 // scope. If a class or enumeration name and an object, function,
313 // or enumerator are declared in the same scope (in any order)
314 // with the same name, the class or enumeration name is hidden
315 // wherever the object, function, or enumerator name is visible.
316 // But it's still an error if there are distinct tag types found,
317 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000318 if (HideTags && HasTag && !Ambiguous &&
319 (HasFunction || HasNonFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000320 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000321
John McCall9f3059a2009-10-09 21:13:30 +0000322 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000323
John McCall80053822009-12-03 00:58:24 +0000324 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000325 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000326
John McCall9f3059a2009-10-09 21:13:30 +0000327 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000328 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000329 else if (HasUnresolved)
330 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000331 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000332 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000333 else
John McCall27b18f82009-11-17 02:14:36 +0000334 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000335}
336
John McCall5cebab12009-11-18 07:57:50 +0000337void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000338 CXXBasePaths::paths_iterator I, E;
339 DeclContext::lookup_iterator DI, DE;
340 for (I = P.begin(), E = P.end(); I != E; ++I)
341 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
342 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000343}
344
John McCall5cebab12009-11-18 07:57:50 +0000345void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000346 Paths = new CXXBasePaths;
347 Paths->swap(P);
348 addDeclsFromBasePaths(*Paths);
349 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000350 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000351}
352
John McCall5cebab12009-11-18 07:57:50 +0000353void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000354 Paths = new CXXBasePaths;
355 Paths->swap(P);
356 addDeclsFromBasePaths(*Paths);
357 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000358 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000359}
360
John McCall5cebab12009-11-18 07:57:50 +0000361void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000362 Out << Decls.size() << " result(s)";
363 if (isAmbiguous()) Out << ", ambiguous";
364 if (Paths) Out << ", base paths present";
365
366 for (iterator I = begin(), E = end(); I != E; ++I) {
367 Out << "\n";
368 (*I)->print(Out, 2);
369 }
370}
371
372// Adds all qualifying matches for a name within a decl context to the
373// given lookup result. Returns true if any matches were found.
John McCall5cebab12009-11-18 07:57:50 +0000374static bool LookupDirect(LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000375 bool Found = false;
376
John McCallf6c8a4e2009-11-10 07:01:13 +0000377 DeclContext::lookup_const_iterator I, E;
John McCall27b18f82009-11-17 02:14:36 +0000378 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I)
379 if (Sema::isAcceptableLookupResult(*I, R.getLookupKind(),
380 R.getIdentifierNamespace()))
John McCall9f3059a2009-10-09 21:13:30 +0000381 R.addDecl(*I), Found = true;
382
383 return Found;
384}
385
John McCallf6c8a4e2009-11-10 07:01:13 +0000386// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000387static bool
John McCall5cebab12009-11-18 07:57:50 +0000388CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCall27b18f82009-11-17 02:14:36 +0000389 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000390
391 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
392
John McCallf6c8a4e2009-11-10 07:01:13 +0000393 // Perform direct name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000394 bool Found = LookupDirect(R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000395
John McCallf6c8a4e2009-11-10 07:01:13 +0000396 // Perform direct name lookup into the namespaces nominated by the
397 // using directives whose common ancestor is this namespace.
398 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
399 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000400
John McCallf6c8a4e2009-11-10 07:01:13 +0000401 for (; UI != UEnd; ++UI)
John McCall27b18f82009-11-17 02:14:36 +0000402 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000403 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000404
405 R.resolveKind();
406
407 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000408}
409
410static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000411 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000412 return Ctx->isFileContext();
413 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000414}
Douglas Gregored8f2882009-01-30 01:04:22 +0000415
Douglas Gregor7f737c02009-09-10 16:57:35 +0000416// Find the next outer declaration context corresponding to this scope.
417static DeclContext *findOuterContext(Scope *S) {
418 for (S = S->getParent(); S; S = S->getParent())
419 if (S->getEntity())
420 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
421
422 return 0;
423}
424
John McCall27b18f82009-11-17 02:14:36 +0000425bool Sema::CppLookupName(LookupResult &R, Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000426 assert(getLangOptions().CPlusPlus &&
427 "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000428 LookupNameKind NameKind = R.getLookupKind();
Mike Stump11289f42009-09-09 15:08:12 +0000429 unsigned IDNS
Douglas Gregor2ada0482009-02-04 17:27:36 +0000430 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
John McCallaa74a0c2009-08-28 07:59:38 +0000431
432 // If we're testing for redeclarations, also look in the friend namespaces.
John McCall27b18f82009-11-17 02:14:36 +0000433 if (R.isForRedeclaration()) {
John McCallaa74a0c2009-08-28 07:59:38 +0000434 if (IDNS & Decl::IDNS_Tag) IDNS |= Decl::IDNS_TagFriend;
435 if (IDNS & Decl::IDNS_Ordinary) IDNS |= Decl::IDNS_OrdinaryFriend;
436 }
437
John McCall27b18f82009-11-17 02:14:36 +0000438 R.setIdentifierNamespace(IDNS);
439
440 DeclarationName Name = R.getLookupName();
441
Douglas Gregor889ceb72009-02-03 19:21:40 +0000442 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000443 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000444 I = IdResolver.begin(Name),
445 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000446
Douglas Gregor889ceb72009-02-03 19:21:40 +0000447 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000448 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000449 // ...During unqualified name lookup (3.4.1), the names appear as if
450 // they were declared in the nearest enclosing namespace which contains
451 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000452 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000453 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000454 //
455 // For example:
456 // namespace A { int i; }
457 // void foo() {
458 // int i;
459 // {
460 // using namespace A;
461 // ++i; // finds local 'i', A::i appears at global scope
462 // }
463 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000464 //
Douglas Gregor700792c2009-02-05 19:25:20 +0000465 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000466 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000467 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000468 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000469 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
John McCall9f3059a2009-10-09 21:13:30 +0000470 Found = true;
471 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000472 }
473 }
John McCall9f3059a2009-10-09 21:13:30 +0000474 if (Found) {
475 R.resolveKind();
476 return true;
477 }
478
Douglas Gregor700792c2009-02-05 19:25:20 +0000479 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregor7f737c02009-09-10 16:57:35 +0000480 DeclContext *OuterCtx = findOuterContext(S);
481 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
482 Ctx = Ctx->getLookupParent()) {
483 if (Ctx->isFunctionOrMethod())
484 continue;
485
486 // Perform qualified name lookup into this context.
487 // FIXME: In some cases, we know that every name that could be found by
488 // this qualified name lookup will also be on the identifier chain. For
489 // example, inside a class without any base classes, we never need to
490 // perform qualified lookup because all of the members are on top of the
491 // identifier chain.
John McCall27b18f82009-11-17 02:14:36 +0000492 if (LookupQualifiedName(R, Ctx))
John McCall9f3059a2009-10-09 21:13:30 +0000493 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000494 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000495 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000496 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000497
John McCallf6c8a4e2009-11-10 07:01:13 +0000498 // Stop if we ran out of scopes.
499 // FIXME: This really, really shouldn't be happening.
500 if (!S) return false;
501
Douglas Gregor700792c2009-02-05 19:25:20 +0000502 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000503 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000504 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000505 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
506 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000507
John McCallf6c8a4e2009-11-10 07:01:13 +0000508 UnqualUsingDirectiveSet UDirs;
509 UDirs.visitScopeChain(Initial, S);
510 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000511
Douglas Gregor700792c2009-02-05 19:25:20 +0000512 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000513 // Unqualified name lookup in C++ requires looking into scopes
514 // that aren't strictly lexical, and therefore we walk through the
515 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000516
Douglas Gregor889ceb72009-02-03 19:21:40 +0000517 for (; S; S = S->getParent()) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000518 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregorf2270432009-08-24 18:55:03 +0000519 if (Ctx->isTransparentContext())
520 continue;
521
Douglas Gregor700792c2009-02-05 19:25:20 +0000522 assert(Ctx && Ctx->isFileContext() &&
523 "We should have been looking only at file context here already.");
Douglas Gregor889ceb72009-02-03 19:21:40 +0000524
525 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000526 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000527 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000528 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
529 // We found something. Look for anything else in our scope
530 // with this same name and in an acceptable identifier
531 // namespace, so that we can construct an overload set if we
532 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000533 Found = true;
534 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000535 }
536 }
537
Douglas Gregor700792c2009-02-05 19:25:20 +0000538 // Look into context considering using-directives.
John McCall27b18f82009-11-17 02:14:36 +0000539 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
John McCall9f3059a2009-10-09 21:13:30 +0000540 Found = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000541
John McCall9f3059a2009-10-09 21:13:30 +0000542 if (Found) {
543 R.resolveKind();
544 return true;
545 }
546
John McCall27b18f82009-11-17 02:14:36 +0000547 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000548 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000549 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000550
John McCall9f3059a2009-10-09 21:13:30 +0000551 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000552}
553
Douglas Gregor34074322009-01-14 22:20:51 +0000554/// @brief Perform unqualified name lookup starting from a given
555/// scope.
556///
557/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
558/// used to find names within the current scope. For example, 'x' in
559/// @code
560/// int x;
561/// int f() {
562/// return x; // unqualified name look finds 'x' in the global scope
563/// }
564/// @endcode
565///
566/// Different lookup criteria can find different names. For example, a
567/// particular scope can have both a struct and a function of the same
568/// name, and each can be found by certain lookup criteria. For more
569/// information about lookup criteria, see the documentation for the
570/// class LookupCriteria.
571///
572/// @param S The scope from which unqualified name lookup will
573/// begin. If the lookup criteria permits, name lookup may also search
574/// in the parent scopes.
575///
576/// @param Name The name of the entity that we are searching for.
577///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000578/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000579/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000580/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000581///
582/// @returns The result of name lookup, which includes zero or more
583/// declarations and possibly additional information used to diagnose
584/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000585bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
586 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +0000587 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000588
John McCall27b18f82009-11-17 02:14:36 +0000589 LookupNameKind NameKind = R.getLookupKind();
590
Douglas Gregor34074322009-01-14 22:20:51 +0000591 if (!getLangOptions().CPlusPlus) {
592 // Unqualified name lookup in C/Objective-C is purely lexical, so
593 // search in the declarations attached to the name.
Douglas Gregored8f2882009-01-30 01:04:22 +0000594 unsigned IDNS = 0;
595 switch (NameKind) {
596 case Sema::LookupOrdinaryName:
597 IDNS = Decl::IDNS_Ordinary;
598 break;
Douglas Gregor34074322009-01-14 22:20:51 +0000599
Douglas Gregored8f2882009-01-30 01:04:22 +0000600 case Sema::LookupTagName:
601 IDNS = Decl::IDNS_Tag;
602 break;
603
604 case Sema::LookupMemberName:
605 IDNS = Decl::IDNS_Member;
606 break;
607
Douglas Gregor94eabf32009-02-04 16:44:47 +0000608 case Sema::LookupOperatorName:
Douglas Gregored8f2882009-01-30 01:04:22 +0000609 case Sema::LookupNestedNameSpecifierName:
610 case Sema::LookupNamespaceName:
611 assert(false && "C does not perform these kinds of name lookup");
612 break;
Douglas Gregoreddf4332009-02-24 20:03:32 +0000613
614 case Sema::LookupRedeclarationWithLinkage:
615 // Find the nearest non-transparent declaration scope.
616 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000617 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000618 static_cast<DeclContext *>(S->getEntity())
619 ->isTransparentContext()))
620 S = S->getParent();
621 IDNS = Decl::IDNS_Ordinary;
622 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000623
Douglas Gregor79947a22009-04-24 00:11:27 +0000624 case Sema::LookupObjCProtocolName:
625 IDNS = Decl::IDNS_ObjCProtocol;
626 break;
627
628 case Sema::LookupObjCImplementationName:
629 IDNS = Decl::IDNS_ObjCImplementation;
630 break;
Mike Stump11289f42009-09-09 15:08:12 +0000631
Douglas Gregor79947a22009-04-24 00:11:27 +0000632 case Sema::LookupObjCCategoryImplName:
633 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000634 break;
Douglas Gregored8f2882009-01-30 01:04:22 +0000635 }
636
Douglas Gregor34074322009-01-14 22:20:51 +0000637 // Scan up the scope chain looking for a decl that matches this
638 // identifier that is in the appropriate namespace. This search
639 // should not take long, as shadowing of names is uncommon, and
640 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000641 bool LeftStartingScope = false;
642
Douglas Gregored8f2882009-01-30 01:04:22 +0000643 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000644 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000645 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000646 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000647 if (NameKind == LookupRedeclarationWithLinkage) {
648 // Determine whether this (or a previous) declaration is
649 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000650 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000651 LeftStartingScope = true;
652
653 // If we found something outside of our starting scope that
654 // does not have linkage, skip it.
655 if (LeftStartingScope && !((*I)->hasLinkage()))
656 continue;
657 }
658
John McCall9f3059a2009-10-09 21:13:30 +0000659 R.addDecl(*I);
660
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000661 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000662 // If this declaration has the "overloadable" attribute, we
663 // might have a set of overloaded functions.
664
665 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000666 while (!(S->getFlags() & Scope::DeclScope) ||
667 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000668 S = S->getParent();
669
670 // Find the last declaration in this scope (with the same
671 // name, naturally).
672 IdentifierResolver::iterator LastI = I;
673 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000674 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000675 break;
John McCall9f3059a2009-10-09 21:13:30 +0000676 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000677 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000678 }
679
John McCall9f3059a2009-10-09 21:13:30 +0000680 R.resolveKind();
681
682 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000683 }
Douglas Gregor34074322009-01-14 22:20:51 +0000684 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000685 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000686 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +0000687 return true;
Douglas Gregor34074322009-01-14 22:20:51 +0000688 }
689
690 // If we didn't find a use of this identifier, and if the identifier
691 // corresponds to a compiler builtin, create the decl object for the builtin
692 // now, injecting it into translation unit scope, and return it.
Mike Stump11289f42009-09-09 15:08:12 +0000693 if (NameKind == LookupOrdinaryName ||
Douglas Gregoreddf4332009-02-24 20:03:32 +0000694 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor34074322009-01-14 22:20:51 +0000695 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000696 if (II && AllowBuiltinCreation) {
Douglas Gregor34074322009-01-14 22:20:51 +0000697 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000698 if (unsigned BuiltinID = II->getBuiltinID()) {
699 // In C++, we don't have any predefined library functions like
700 // 'malloc'. Instead, we'll just error.
Mike Stump11289f42009-09-09 15:08:12 +0000701 if (getLangOptions().CPlusPlus &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000702 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCall9f3059a2009-10-09 21:13:30 +0000703 return false;
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000704
John McCall9f3059a2009-10-09 21:13:30 +0000705 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCall27b18f82009-11-17 02:14:36 +0000706 S, R.isForRedeclaration(),
707 R.getNameLoc());
John McCall9f3059a2009-10-09 21:13:30 +0000708 if (D) R.addDecl(D);
709 return (D != NULL);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000710 }
Douglas Gregor34074322009-01-14 22:20:51 +0000711 }
Douglas Gregor34074322009-01-14 22:20:51 +0000712 }
John McCall9f3059a2009-10-09 21:13:30 +0000713 return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000714}
715
John McCall6538c932009-10-10 05:48:19 +0000716/// @brief Perform qualified name lookup in the namespaces nominated by
717/// using directives by the given context.
718///
719/// C++98 [namespace.qual]p2:
720/// Given X::m (where X is a user-declared namespace), or given ::m
721/// (where X is the global namespace), let S be the set of all
722/// declarations of m in X and in the transitive closure of all
723/// namespaces nominated by using-directives in X and its used
724/// namespaces, except that using-directives are ignored in any
725/// namespace, including X, directly containing one or more
726/// declarations of m. No namespace is searched more than once in
727/// the lookup of a name. If S is the empty set, the program is
728/// ill-formed. Otherwise, if S has exactly one member, or if the
729/// context of the reference is a using-declaration
730/// (namespace.udecl), S is the required set of declarations of
731/// m. Otherwise if the use of m is not one that allows a unique
732/// declaration to be chosen from S, the program is ill-formed.
733/// C++98 [namespace.qual]p5:
734/// During the lookup of a qualified namespace member name, if the
735/// lookup finds more than one declaration of the member, and if one
736/// declaration introduces a class name or enumeration name and the
737/// other declarations either introduce the same object, the same
738/// enumerator or a set of functions, the non-type name hides the
739/// class or enumeration name if and only if the declarations are
740/// from the same namespace; otherwise (the declarations are from
741/// different namespaces), the program is ill-formed.
John McCall5cebab12009-11-18 07:57:50 +0000742static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +0000743 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +0000744 assert(StartDC->isFileContext() && "start context is not a file context");
745
746 DeclContext::udir_iterator I = StartDC->using_directives_begin();
747 DeclContext::udir_iterator E = StartDC->using_directives_end();
748
749 if (I == E) return false;
750
751 // We have at least added all these contexts to the queue.
752 llvm::DenseSet<DeclContext*> Visited;
753 Visited.insert(StartDC);
754
755 // We have not yet looked into these namespaces, much less added
756 // their "using-children" to the queue.
757 llvm::SmallVector<NamespaceDecl*, 8> Queue;
758
759 // We have already looked into the initial namespace; seed the queue
760 // with its using-children.
761 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +0000762 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +0000763 if (Visited.insert(ND).second)
764 Queue.push_back(ND);
765 }
766
767 // The easiest way to implement the restriction in [namespace.qual]p5
768 // is to check whether any of the individual results found a tag
769 // and, if so, to declare an ambiguity if the final result is not
770 // a tag.
771 bool FoundTag = false;
772 bool FoundNonTag = false;
773
John McCall5cebab12009-11-18 07:57:50 +0000774 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +0000775
776 bool Found = false;
777 while (!Queue.empty()) {
778 NamespaceDecl *ND = Queue.back();
779 Queue.pop_back();
780
781 // We go through some convolutions here to avoid copying results
782 // between LookupResults.
783 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +0000784 LookupResult &DirectR = UseLocal ? LocalR : R;
John McCall27b18f82009-11-17 02:14:36 +0000785 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +0000786
787 if (FoundDirect) {
788 // First do any local hiding.
789 DirectR.resolveKind();
790
791 // If the local result is a tag, remember that.
792 if (DirectR.isSingleTagDecl())
793 FoundTag = true;
794 else
795 FoundNonTag = true;
796
797 // Append the local results to the total results if necessary.
798 if (UseLocal) {
799 R.addAllDecls(LocalR);
800 LocalR.clear();
801 }
802 }
803
804 // If we find names in this namespace, ignore its using directives.
805 if (FoundDirect) {
806 Found = true;
807 continue;
808 }
809
810 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
811 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
812 if (Visited.insert(Nom).second)
813 Queue.push_back(Nom);
814 }
815 }
816
817 if (Found) {
818 if (FoundTag && FoundNonTag)
819 R.setAmbiguousQualifiedTagHiding();
820 else
821 R.resolveKind();
822 }
823
824 return Found;
825}
826
Douglas Gregor34074322009-01-14 22:20:51 +0000827/// @brief Perform qualified name lookup into a given context.
828///
829/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
830/// names when the context of those names is explicit specified, e.g.,
831/// "std::vector" or "x->member".
832///
833/// Different lookup criteria can find different names. For example, a
834/// particular scope can have both a struct and a function of the same
835/// name, and each can be found by certain lookup criteria. For more
836/// information about lookup criteria, see the documentation for the
837/// class LookupCriteria.
838///
839/// @param LookupCtx The context in which qualified name lookup will
840/// search. If the lookup criteria permits, name lookup may also search
841/// in the parent contexts or (for C++ classes) base classes.
842///
843/// @param Name The name of the entity that we are searching for.
844///
845/// @param Criteria The criteria that this routine will use to
846/// determine which names are visible and which names will be
847/// found. Note that name lookup will find a name that is visible by
848/// the given criteria, but the entity itself may not be semantically
849/// correct or even the kind of entity expected based on the
850/// lookup. For example, searching for a nested-name-specifier name
851/// might result in an EnumDecl, which is visible but is not permitted
852/// as a nested-name-specifier in C++03.
853///
854/// @returns The result of name lookup, which includes zero or more
855/// declarations and possibly additional information used to diagnose
856/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000857bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx) {
Douglas Gregor34074322009-01-14 22:20:51 +0000858 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +0000859
John McCall27b18f82009-11-17 02:14:36 +0000860 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +0000861 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000862
Douglas Gregor34074322009-01-14 22:20:51 +0000863 // If we're performing qualified name lookup (e.g., lookup into a
864 // struct), find fields as part of ordinary name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000865 LookupNameKind NameKind = R.getLookupKind();
Douglas Gregored8f2882009-01-30 01:04:22 +0000866 unsigned IDNS
Mike Stump11289f42009-09-09 15:08:12 +0000867 = getIdentifierNamespacesFromLookupNameKind(NameKind,
Douglas Gregored8f2882009-01-30 01:04:22 +0000868 getLangOptions().CPlusPlus);
869 if (NameKind == LookupOrdinaryName)
870 IDNS |= Decl::IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000871
John McCall27b18f82009-11-17 02:14:36 +0000872 R.setIdentifierNamespace(IDNS);
873
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000874 // Make sure that the declaration context is complete.
875 assert((!isa<TagDecl>(LookupCtx) ||
876 LookupCtx->isDependentContext() ||
877 cast<TagDecl>(LookupCtx)->isDefinition() ||
878 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
879 ->isBeingDefined()) &&
880 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +0000881
Douglas Gregor34074322009-01-14 22:20:51 +0000882 // Perform qualified name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000883 if (LookupDirect(R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +0000884 R.resolveKind();
885 return true;
886 }
Douglas Gregor34074322009-01-14 22:20:51 +0000887
John McCall6538c932009-10-10 05:48:19 +0000888 // Don't descend into implied contexts for redeclarations.
889 // C++98 [namespace.qual]p6:
890 // In a declaration for a namespace member in which the
891 // declarator-id is a qualified-id, given that the qualified-id
892 // for the namespace member has the form
893 // nested-name-specifier unqualified-id
894 // the unqualified-id shall name a member of the namespace
895 // designated by the nested-name-specifier.
896 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +0000897 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +0000898 return false;
899
John McCall27b18f82009-11-17 02:14:36 +0000900 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +0000901 if (LookupCtx->isFileContext())
John McCall27b18f82009-11-17 02:14:36 +0000902 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +0000903
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000904 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +0000905 // classes, we're done.
John McCall6538c932009-10-10 05:48:19 +0000906 if (!isa<CXXRecordDecl>(LookupCtx))
John McCall9f3059a2009-10-09 21:13:30 +0000907 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000908
909 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +0000910 CXXRecordDecl *LookupRec = cast<CXXRecordDecl>(LookupCtx);
911 CXXBasePaths Paths;
912 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000913
914 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +0000915 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +0000916 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000917 case LookupOrdinaryName:
918 case LookupMemberName:
919 case LookupRedeclarationWithLinkage:
920 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
921 break;
922
923 case LookupTagName:
924 BaseCallback = &CXXRecordDecl::FindTagMember;
925 break;
926
927 case LookupOperatorName:
928 case LookupNamespaceName:
929 case LookupObjCProtocolName:
930 case LookupObjCImplementationName:
931 case LookupObjCCategoryImplName:
932 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +0000933 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000934
935 case LookupNestedNameSpecifierName:
936 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
937 break;
938 }
939
John McCall27b18f82009-11-17 02:14:36 +0000940 if (!LookupRec->lookupInBases(BaseCallback,
941 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +0000942 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000943
944 // C++ [class.member.lookup]p2:
945 // [...] If the resulting set of declarations are not all from
946 // sub-objects of the same type, or the set has a nonstatic member
947 // and includes members from distinct sub-objects, there is an
948 // ambiguity and the program is ill-formed. Otherwise that set is
949 // the result of the lookup.
950 // FIXME: support using declarations!
951 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +0000952 int SubobjectNumber = 0;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000953 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000954 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000955 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000956
957 // Determine whether we're looking at a distinct sub-object or not.
958 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +0000959 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000960 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
961 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +0000962 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000963 != Context.getCanonicalType(PathElement.Base->getType())) {
964 // We found members of the given name in two subobjects of
965 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +0000966 R.setAmbiguousBaseSubobjectTypes(Paths);
967 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000968 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
969 // We have a different subobject of the same type.
970
971 // C++ [class.member.lookup]p5:
972 // A static member, a nested type or an enumerator defined in
973 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +0000974 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000975 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000976 if (isa<VarDecl>(FirstDecl) ||
977 isa<TypeDecl>(FirstDecl) ||
978 isa<EnumConstantDecl>(FirstDecl))
979 continue;
980
981 if (isa<CXXMethodDecl>(FirstDecl)) {
982 // Determine whether all of the methods are static.
983 bool AllMethodsAreStatic = true;
984 for (DeclContext::lookup_iterator Func = Path->Decls.first;
985 Func != Path->Decls.second; ++Func) {
986 if (!isa<CXXMethodDecl>(*Func)) {
987 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
988 break;
989 }
990
991 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
992 AllMethodsAreStatic = false;
993 break;
994 }
995 }
996
997 if (AllMethodsAreStatic)
998 continue;
999 }
1000
1001 // We have found a nonstatic member name in multiple, distinct
1002 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001003 R.setAmbiguousBaseSubobjects(Paths);
1004 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001005 }
1006 }
1007
1008 // Lookup in a base class succeeded; return these results.
1009
John McCall9f3059a2009-10-09 21:13:30 +00001010 DeclContext::lookup_iterator I, E;
1011 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I)
1012 R.addDecl(*I);
1013 R.resolveKind();
1014 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001015}
1016
1017/// @brief Performs name lookup for a name that was parsed in the
1018/// source code, and may contain a C++ scope specifier.
1019///
1020/// This routine is a convenience routine meant to be called from
1021/// contexts that receive a name and an optional C++ scope specifier
1022/// (e.g., "N::M::x"). It will then perform either qualified or
1023/// unqualified name lookup (with LookupQualifiedName or LookupName,
1024/// respectively) on the given name and return those results.
1025///
1026/// @param S The scope from which unqualified name lookup will
1027/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001028///
Douglas Gregore861bac2009-08-25 22:51:20 +00001029/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001030///
1031/// @param Name The name of the entity that name lookup will
1032/// search for.
1033///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001034/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001035/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001036/// C library functions (like "malloc") are implicitly declared.
1037///
Douglas Gregore861bac2009-08-25 22:51:20 +00001038/// @param EnteringContext Indicates whether we are going to enter the
1039/// context of the scope-specifier SS (if present).
1040///
John McCall9f3059a2009-10-09 21:13:30 +00001041/// @returns True if any decls were found (but possibly ambiguous)
1042bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001043 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001044 if (SS && SS->isInvalid()) {
1045 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001046 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001047 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001048 }
Mike Stump11289f42009-09-09 15:08:12 +00001049
Douglas Gregore861bac2009-08-25 22:51:20 +00001050 if (SS && SS->isSet()) {
1051 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001052 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001053 // contex, and will perform name lookup in that context.
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001054 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCall9f3059a2009-10-09 21:13:30 +00001055 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001056
John McCall27b18f82009-11-17 02:14:36 +00001057 R.setContextRange(SS->getRange());
1058
1059 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001060 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001061
Douglas Gregore861bac2009-08-25 22:51:20 +00001062 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001063 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001064 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001065 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001066 }
1067
Mike Stump11289f42009-09-09 15:08:12 +00001068 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001069 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001070}
1071
Douglas Gregor889ceb72009-02-03 19:21:40 +00001072
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001073/// @brief Produce a diagnostic describing the ambiguity that resulted
1074/// from name lookup.
1075///
1076/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001077///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001078/// @param Name The name of the entity that name lookup was
1079/// searching for.
1080///
1081/// @param NameLoc The location of the name within the source code.
1082///
1083/// @param LookupRange A source range that provides more
1084/// source-location information concerning the lookup itself. For
1085/// example, this range might highlight a nested-name-specifier that
1086/// precedes the name.
1087///
1088/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001089bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001090 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1091
John McCall27b18f82009-11-17 02:14:36 +00001092 DeclarationName Name = Result.getLookupName();
1093 SourceLocation NameLoc = Result.getNameLoc();
1094 SourceRange LookupRange = Result.getContextRange();
1095
John McCall6538c932009-10-10 05:48:19 +00001096 switch (Result.getAmbiguityKind()) {
1097 case LookupResult::AmbiguousBaseSubobjects: {
1098 CXXBasePaths *Paths = Result.getBasePaths();
1099 QualType SubobjectType = Paths->front().back().Base->getType();
1100 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1101 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1102 << LookupRange;
1103
1104 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1105 while (isa<CXXMethodDecl>(*Found) &&
1106 cast<CXXMethodDecl>(*Found)->isStatic())
1107 ++Found;
1108
1109 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1110
1111 return true;
1112 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001113
John McCall6538c932009-10-10 05:48:19 +00001114 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001115 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1116 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001117
1118 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001119 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001120 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1121 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001122 Path != PathEnd; ++Path) {
1123 Decl *D = *Path->Decls.first;
1124 if (DeclsPrinted.insert(D).second)
1125 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1126 }
1127
Douglas Gregor1c846b02009-01-16 00:38:09 +00001128 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001129 }
1130
John McCall6538c932009-10-10 05:48:19 +00001131 case LookupResult::AmbiguousTagHiding: {
1132 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001133
John McCall6538c932009-10-10 05:48:19 +00001134 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1135
1136 LookupResult::iterator DI, DE = Result.end();
1137 for (DI = Result.begin(); DI != DE; ++DI)
1138 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1139 TagDecls.insert(TD);
1140 Diag(TD->getLocation(), diag::note_hidden_tag);
1141 }
1142
1143 for (DI = Result.begin(); DI != DE; ++DI)
1144 if (!isa<TagDecl>(*DI))
1145 Diag((*DI)->getLocation(), diag::note_hiding_object);
1146
1147 // For recovery purposes, go ahead and implement the hiding.
1148 Result.hideDecls(TagDecls);
1149
1150 return true;
1151 }
1152
1153 case LookupResult::AmbiguousReference: {
1154 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001155
John McCall6538c932009-10-10 05:48:19 +00001156 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1157 for (; DI != DE; ++DI)
1158 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001159
John McCall6538c932009-10-10 05:48:19 +00001160 return true;
1161 }
1162 }
1163
1164 llvm::llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001165 return true;
1166}
Douglas Gregore254f902009-02-04 00:32:51 +00001167
Mike Stump11289f42009-09-09 15:08:12 +00001168static void
1169addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001170 ASTContext &Context,
1171 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001172 Sema::AssociatedClassSet &AssociatedClasses);
1173
1174static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1175 DeclContext *Ctx) {
1176 if (Ctx->isFileContext())
1177 Namespaces.insert(Ctx);
1178}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001179
Mike Stump11289f42009-09-09 15:08:12 +00001180// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001181// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001182static void
1183addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001184 ASTContext &Context,
1185 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001186 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001187 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001188 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001189 switch (Arg.getKind()) {
1190 case TemplateArgument::Null:
1191 break;
Mike Stump11289f42009-09-09 15:08:12 +00001192
Douglas Gregor197e5f72009-07-08 07:51:57 +00001193 case TemplateArgument::Type:
1194 // [...] the namespaces and classes associated with the types of the
1195 // template arguments provided for template type parameters (excluding
1196 // template template parameters)
1197 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1198 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001199 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001200 break;
Mike Stump11289f42009-09-09 15:08:12 +00001201
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001202 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001203 // [...] the namespaces in which any template template arguments are
1204 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001205 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001206 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001207 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001208 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001209 DeclContext *Ctx = ClassTemplate->getDeclContext();
1210 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1211 AssociatedClasses.insert(EnclosingClass);
1212 // Add the associated namespace for this class.
1213 while (Ctx->isRecord())
1214 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001215 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001216 }
1217 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001218 }
1219
1220 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001221 case TemplateArgument::Integral:
1222 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001223 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001224 // associated namespaces. ]
1225 break;
Mike Stump11289f42009-09-09 15:08:12 +00001226
Douglas Gregor197e5f72009-07-08 07:51:57 +00001227 case TemplateArgument::Pack:
1228 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1229 PEnd = Arg.pack_end();
1230 P != PEnd; ++P)
1231 addAssociatedClassesAndNamespaces(*P, Context,
1232 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001233 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001234 break;
1235 }
1236}
1237
Douglas Gregore254f902009-02-04 00:32:51 +00001238// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001239// argument-dependent lookup with an argument of class type
1240// (C++ [basic.lookup.koenig]p2).
1241static void
1242addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregore254f902009-02-04 00:32:51 +00001243 ASTContext &Context,
1244 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001245 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001246 // C++ [basic.lookup.koenig]p2:
1247 // [...]
1248 // -- If T is a class type (including unions), its associated
1249 // classes are: the class itself; the class of which it is a
1250 // member, if any; and its direct and indirect base
1251 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001252 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001253
1254 // Add the class of which it is a member, if any.
1255 DeclContext *Ctx = Class->getDeclContext();
1256 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1257 AssociatedClasses.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001258 // Add the associated namespace for this class.
1259 while (Ctx->isRecord())
1260 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001261 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001262
Douglas Gregore254f902009-02-04 00:32:51 +00001263 // Add the class itself. If we've already seen this class, we don't
1264 // need to visit base classes.
1265 if (!AssociatedClasses.insert(Class))
1266 return;
1267
Mike Stump11289f42009-09-09 15:08:12 +00001268 // -- If T is a template-id, its associated namespaces and classes are
1269 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001270 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001271 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001272 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001273 // namespaces in which any template template arguments are defined; and
1274 // the classes in which any member templates used as template template
1275 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001276 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001277 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001278 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1279 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1280 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1281 AssociatedClasses.insert(EnclosingClass);
1282 // Add the associated namespace for this class.
1283 while (Ctx->isRecord())
1284 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001285 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001286
Douglas Gregor197e5f72009-07-08 07:51:57 +00001287 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1288 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1289 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1290 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001291 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001292 }
Mike Stump11289f42009-09-09 15:08:12 +00001293
Douglas Gregore254f902009-02-04 00:32:51 +00001294 // Add direct and indirect base classes along with their associated
1295 // namespaces.
1296 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1297 Bases.push_back(Class);
1298 while (!Bases.empty()) {
1299 // Pop this class off the stack.
1300 Class = Bases.back();
1301 Bases.pop_back();
1302
1303 // Visit the base classes.
1304 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1305 BaseEnd = Class->bases_end();
1306 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001307 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001308 // In dependent contexts, we do ADL twice, and the first time around,
1309 // the base type might be a dependent TemplateSpecializationType, or a
1310 // TemplateTypeParmType. If that happens, simply ignore it.
1311 // FIXME: If we want to support export, we probably need to add the
1312 // namespace of the template in a TemplateSpecializationType, or even
1313 // the classes and namespaces of known non-dependent arguments.
1314 if (!BaseType)
1315 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001316 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1317 if (AssociatedClasses.insert(BaseDecl)) {
1318 // Find the associated namespace for this base class.
1319 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1320 while (BaseCtx->isRecord())
1321 BaseCtx = BaseCtx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001322 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001323
1324 // Make sure we visit the bases of this base class.
1325 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1326 Bases.push_back(BaseDecl);
1327 }
1328 }
1329 }
1330}
1331
1332// \brief Add the associated classes and namespaces for
1333// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001334// (C++ [basic.lookup.koenig]p2).
1335static void
1336addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregore254f902009-02-04 00:32:51 +00001337 ASTContext &Context,
1338 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001339 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001340 // C++ [basic.lookup.koenig]p2:
1341 //
1342 // For each argument type T in the function call, there is a set
1343 // of zero or more associated namespaces and a set of zero or more
1344 // associated classes to be considered. The sets of namespaces and
1345 // classes is determined entirely by the types of the function
1346 // arguments (and the namespace of any template template
1347 // argument). Typedef names and using-declarations used to specify
1348 // the types do not contribute to this set. The sets of namespaces
1349 // and classes are determined in the following way:
1350 T = Context.getCanonicalType(T).getUnqualifiedType();
1351
1352 // -- If T is a pointer to U or an array of U, its associated
Mike Stump11289f42009-09-09 15:08:12 +00001353 // namespaces and classes are those associated with U.
Douglas Gregore254f902009-02-04 00:32:51 +00001354 //
1355 // We handle this by unwrapping pointer and array types immediately,
1356 // to avoid unnecessary recursion.
1357 while (true) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001358 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001359 T = Ptr->getPointeeType();
1360 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1361 T = Ptr->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001362 else
Douglas Gregore254f902009-02-04 00:32:51 +00001363 break;
1364 }
1365
1366 // -- If T is a fundamental type, its associated sets of
1367 // namespaces and classes are both empty.
John McCall9dd450b2009-09-21 23:43:11 +00001368 if (T->getAs<BuiltinType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001369 return;
1370
1371 // -- If T is a class type (including unions), its associated
1372 // classes are: the class itself; the class of which it is a
1373 // member, if any; and its direct and indirect base
1374 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001375 // which its associated classes are defined.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001376 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump11289f42009-09-09 15:08:12 +00001377 if (CXXRecordDecl *ClassDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001378 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001379 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1380 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001381 AssociatedClasses);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001382 return;
1383 }
Douglas Gregore254f902009-02-04 00:32:51 +00001384
1385 // -- If T is an enumeration type, its associated namespace is
1386 // the namespace in which it is defined. If it is class
1387 // member, its associated class is the member’s class; else
Mike Stump11289f42009-09-09 15:08:12 +00001388 // it has no associated class.
John McCall9dd450b2009-09-21 23:43:11 +00001389 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001390 EnumDecl *Enum = EnumT->getDecl();
1391
1392 DeclContext *Ctx = Enum->getDeclContext();
1393 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1394 AssociatedClasses.insert(EnclosingClass);
1395
1396 // Add the associated namespace for this class.
1397 while (Ctx->isRecord())
1398 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001399 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001400
1401 return;
1402 }
1403
1404 // -- If T is a function type, its associated namespaces and
1405 // classes are those associated with the function parameter
1406 // types and those associated with the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001407 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001408 // Return type
John McCall9dd450b2009-09-21 23:43:11 +00001409 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregore254f902009-02-04 00:32:51 +00001410 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001411 AssociatedNamespaces, AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001412
John McCall9dd450b2009-09-21 23:43:11 +00001413 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregore254f902009-02-04 00:32:51 +00001414 if (!Proto)
1415 return;
1416
1417 // Argument types
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001418 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001419 ArgEnd = Proto->arg_type_end();
Douglas Gregore254f902009-02-04 00:32:51 +00001420 Arg != ArgEnd; ++Arg)
1421 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallc7e8e792009-08-07 22:18:02 +00001422 AssociatedNamespaces, AssociatedClasses);
Mike Stump11289f42009-09-09 15:08:12 +00001423
Douglas Gregore254f902009-02-04 00:32:51 +00001424 return;
1425 }
1426
1427 // -- If T is a pointer to a member function of a class X, its
1428 // associated namespaces and classes are those associated
1429 // with the function parameter types and return type,
Mike Stump11289f42009-09-09 15:08:12 +00001430 // together with those associated with X.
Douglas Gregore254f902009-02-04 00:32:51 +00001431 //
1432 // -- If T is a pointer to a data member of class X, its
1433 // associated namespaces and classes are those associated
1434 // with the member type together with those associated with
Mike Stump11289f42009-09-09 15:08:12 +00001435 // X.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001436 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001437 // Handle the type that the pointer to member points to.
1438 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1439 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001440 AssociatedNamespaces,
1441 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001442
1443 // Handle the class type into which this points.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001444 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001445 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1446 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001447 AssociatedNamespaces,
1448 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001449
1450 return;
1451 }
1452
1453 // FIXME: What about block pointers?
1454 // FIXME: What about Objective-C message sends?
1455}
1456
1457/// \brief Find the associated classes and namespaces for
1458/// argument-dependent lookup for a call with the given set of
1459/// arguments.
1460///
1461/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001462/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001463/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001464void
Douglas Gregore254f902009-02-04 00:32:51 +00001465Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1466 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001467 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001468 AssociatedNamespaces.clear();
1469 AssociatedClasses.clear();
1470
1471 // C++ [basic.lookup.koenig]p2:
1472 // For each argument type T in the function call, there is a set
1473 // of zero or more associated namespaces and a set of zero or more
1474 // associated classes to be considered. The sets of namespaces and
1475 // classes is determined entirely by the types of the function
1476 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001477 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001478 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1479 Expr *Arg = Args[ArgIdx];
1480
1481 if (Arg->getType() != Context.OverloadTy) {
1482 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001483 AssociatedNamespaces,
1484 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001485 continue;
1486 }
1487
1488 // [...] In addition, if the argument is the name or address of a
1489 // set of overloaded functions and/or function templates, its
1490 // associated classes and namespaces are the union of those
1491 // associated with each of the members of the set: the namespace
1492 // in which the function or function template is defined and the
1493 // classes and namespaces associated with its (non-dependent)
1494 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001495 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001496 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1497 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1498 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001499
John McCalld14a8642009-11-21 08:51:07 +00001500 // TODO: avoid the copies. This should be easy when the cases
1501 // share a storage implementation.
1502 llvm::SmallVector<NamedDecl*, 8> Functions;
1503
1504 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1505 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00001506 else
Douglas Gregore254f902009-02-04 00:32:51 +00001507 continue;
1508
John McCalld14a8642009-11-21 08:51:07 +00001509 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1510 E = Functions.end(); I != E; ++I) {
1511 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001512 if (!FDecl)
John McCalld14a8642009-11-21 08:51:07 +00001513 FDecl = cast<FunctionTemplateDecl>(*I)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001514
1515 // Add the namespace in which this function was defined. Note
1516 // that, if this is a member function, we do *not* consider the
1517 // enclosing namespace of its class.
1518 DeclContext *Ctx = FDecl->getDeclContext();
John McCallc7e8e792009-08-07 22:18:02 +00001519 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001520
1521 // Add the classes and namespaces associated with the parameter
1522 // types and return type of this function.
1523 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001524 AssociatedNamespaces,
1525 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001526 }
1527 }
1528}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001529
1530/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1531/// an acceptable non-member overloaded operator for a call whose
1532/// arguments have types T1 (and, if non-empty, T2). This routine
1533/// implements the check in C++ [over.match.oper]p3b2 concerning
1534/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001535static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001536IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1537 QualType T1, QualType T2,
1538 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001539 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1540 return true;
1541
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001542 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1543 return true;
1544
John McCall9dd450b2009-09-21 23:43:11 +00001545 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001546 if (Proto->getNumArgs() < 1)
1547 return false;
1548
1549 if (T1->isEnumeralType()) {
1550 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001551 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001552 return true;
1553 }
1554
1555 if (Proto->getNumArgs() < 2)
1556 return false;
1557
1558 if (!T2.isNull() && T2->isEnumeralType()) {
1559 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001560 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001561 return true;
1562 }
1563
1564 return false;
1565}
1566
John McCall5cebab12009-11-18 07:57:50 +00001567NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1568 LookupNameKind NameKind,
1569 RedeclarationKind Redecl) {
1570 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1571 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00001572 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00001573}
1574
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001575/// \brief Find the protocol with the given name, if any.
1576ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001577 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001578 return cast_or_null<ObjCProtocolDecl>(D);
1579}
1580
Douglas Gregor79947a22009-04-24 00:11:27 +00001581/// \brief Find the Objective-C category implementation with the given
1582/// name, if any.
1583ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001584 Decl *D = LookupSingleName(TUScope, II, LookupObjCCategoryImplName);
Douglas Gregor79947a22009-04-24 00:11:27 +00001585 return cast_or_null<ObjCCategoryImplDecl>(D);
1586}
1587
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001588void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001589 QualType T1, QualType T2,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001590 FunctionSet &Functions) {
1591 // C++ [over.match.oper]p3:
1592 // -- The set of non-member candidates is the result of the
1593 // unqualified lookup of operator@ in the context of the
1594 // expression according to the usual rules for name lookup in
1595 // unqualified function calls (3.4.2) except that all member
1596 // functions are ignored. However, if no operand has a class
1597 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001598 // that have a first parameter of type T1 or "reference to
1599 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001600 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001601 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001602 // when T2 is an enumeration type, are candidate functions.
1603 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00001604 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1605 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00001606
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001607 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1608
John McCall9f3059a2009-10-09 21:13:30 +00001609 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001610 return;
1611
1612 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1613 Op != OpEnd; ++Op) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001614 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001615 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1616 Functions.insert(FD); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001617 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor15448f82009-06-27 21:05:07 +00001618 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1619 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001620 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001621 // later?
1622 if (!FunTmpl->getDeclContext()->isRecord())
1623 Functions.insert(FunTmpl);
1624 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001625 }
1626}
1627
John McCallc7e8e792009-08-07 22:18:02 +00001628static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1629 Decl *D) {
1630 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1631 Functions.insert(Func);
1632 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1633 Functions.insert(FunTmpl);
1634}
1635
Sebastian Redlc057f422009-10-23 19:23:15 +00001636void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001637 Expr **Args, unsigned NumArgs,
1638 FunctionSet &Functions) {
1639 // Find all of the associated namespaces and classes based on the
1640 // arguments we have.
1641 AssociatedNamespaceSet AssociatedNamespaces;
1642 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00001643 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00001644 AssociatedNamespaces,
1645 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001646
Sebastian Redlc057f422009-10-23 19:23:15 +00001647 QualType T1, T2;
1648 if (Operator) {
1649 T1 = Args[0]->getType();
1650 if (NumArgs >= 2)
1651 T2 = Args[1]->getType();
1652 }
1653
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001654 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001655 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1656 // and let Y be the lookup set produced by argument dependent
1657 // lookup (defined as follows). If X contains [...] then Y is
1658 // empty. Otherwise Y is the set of declarations found in the
1659 // namespaces associated with the argument types as described
1660 // below. The set of declarations found by the lookup of the name
1661 // is the union of X and Y.
1662 //
1663 // Here, we compute Y and add its members to the overloaded
1664 // candidate set.
1665 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001666 NSEnd = AssociatedNamespaces.end();
1667 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001668 // When considering an associated namespace, the lookup is the
1669 // same as the lookup performed when the associated namespace is
1670 // used as a qualifier (3.4.3.2) except that:
1671 //
1672 // -- Any using-directives in the associated namespace are
1673 // ignored.
1674 //
John McCallc7e8e792009-08-07 22:18:02 +00001675 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001676 // associated classes are visible within their respective
1677 // namespaces even if they are not visible during an ordinary
1678 // lookup (11.4).
1679 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00001680 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCallc7e8e792009-08-07 22:18:02 +00001681 Decl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00001682 // If the only declaration here is an ordinary friend, consider
1683 // it only if it was declared in an associated classes.
1684 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00001685 DeclContext *LexDC = D->getLexicalDeclContext();
1686 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1687 continue;
1688 }
Mike Stump11289f42009-09-09 15:08:12 +00001689
Sebastian Redlc057f422009-10-23 19:23:15 +00001690 FunctionDecl *Fn;
1691 if (!Operator || !(Fn = dyn_cast<FunctionDecl>(D)) ||
1692 IsAcceptableNonMemberOperatorCandidate(Fn, T1, T2, Context))
1693 CollectFunctionDecl(Functions, D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00001694 }
1695 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001696}