blob: 1c7dce0def1535378369565b70cd48ce35e6b2d6 [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000020#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000021#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000023#include "clang/Parse/DeclSpec.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
26#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000027#include "llvm/ADT/SmallPtrSet.h"
John McCall6e247262009-10-10 05:48:19 +000028#include "llvm/Support/ErrorHandling.h"
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000029#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000030#include <vector>
31#include <iterator>
32#include <utility>
33#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000034
35using namespace clang;
36
John McCalld7be78a2009-11-10 07:01:13 +000037namespace {
38 class UnqualUsingEntry {
39 const DeclContext *Nominated;
40 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000041
John McCalld7be78a2009-11-10 07:01:13 +000042 public:
43 UnqualUsingEntry(const DeclContext *Nominated,
44 const DeclContext *CommonAncestor)
45 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
46 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000047
John McCalld7be78a2009-11-10 07:01:13 +000048 const DeclContext *getCommonAncestor() const {
49 return CommonAncestor;
50 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000051
John McCalld7be78a2009-11-10 07:01:13 +000052 const DeclContext *getNominatedNamespace() const {
53 return Nominated;
54 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000055
John McCalld7be78a2009-11-10 07:01:13 +000056 // Sort by the pointer value of the common ancestor.
57 struct Comparator {
58 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
59 return L.getCommonAncestor() < R.getCommonAncestor();
60 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000061
John McCalld7be78a2009-11-10 07:01:13 +000062 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
63 return E.getCommonAncestor() < DC;
64 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000065
John McCalld7be78a2009-11-10 07:01:13 +000066 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
67 return DC < E.getCommonAncestor();
68 }
69 };
70 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000071
John McCalld7be78a2009-11-10 07:01:13 +000072 /// A collection of using directives, as used by C++ unqualified
73 /// lookup.
74 class UnqualUsingDirectiveSet {
75 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000076
John McCalld7be78a2009-11-10 07:01:13 +000077 ListTy list;
78 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000079
John McCalld7be78a2009-11-10 07:01:13 +000080 public:
81 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000082
John McCalld7be78a2009-11-10 07:01:13 +000083 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
84 // C++ [namespace.udir]p1:
85 // During unqualified name lookup, the names appear as if they
86 // were declared in the nearest enclosing namespace which contains
87 // both the using-directive and the nominated namespace.
88 DeclContext *InnermostFileDC
89 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
90 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +000091
John McCalld7be78a2009-11-10 07:01:13 +000092 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +000093 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
94 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
95 visit(Ctx, EffectiveDC);
96 } else {
97 Scope::udir_iterator I = S->using_directives_begin(),
98 End = S->using_directives_end();
99
100 for (; I != End; ++I)
101 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
102 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000103 }
104 }
John McCalld7be78a2009-11-10 07:01:13 +0000105
106 // Visits a context and collect all of its using directives
107 // recursively. Treats all using directives as if they were
108 // declared in the context.
109 //
110 // A given context is only every visited once, so it is important
111 // that contexts be visited from the inside out in order to get
112 // the effective DCs right.
113 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
114 if (!visited.insert(DC))
115 return;
116
117 addUsingDirectives(DC, EffectiveDC);
118 }
119
120 // Visits a using directive and collects all of its using
121 // directives recursively. Treats all using directives as if they
122 // were declared in the effective DC.
123 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
124 DeclContext *NS = UD->getNominatedNamespace();
125 if (!visited.insert(NS))
126 return;
127
128 addUsingDirective(UD, EffectiveDC);
129 addUsingDirectives(NS, EffectiveDC);
130 }
131
132 // Adds all the using directives in a context (and those nominated
133 // by its using directives, transitively) as if they appeared in
134 // the given effective context.
135 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
136 llvm::SmallVector<DeclContext*,4> queue;
137 while (true) {
138 DeclContext::udir_iterator I, End;
139 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
140 UsingDirectiveDecl *UD = *I;
141 DeclContext *NS = UD->getNominatedNamespace();
142 if (visited.insert(NS)) {
143 addUsingDirective(UD, EffectiveDC);
144 queue.push_back(NS);
145 }
146 }
147
148 if (queue.empty())
149 return;
150
151 DC = queue.back();
152 queue.pop_back();
153 }
154 }
155
156 // Add a using directive as if it had been declared in the given
157 // context. This helps implement C++ [namespace.udir]p3:
158 // The using-directive is transitive: if a scope contains a
159 // using-directive that nominates a second namespace that itself
160 // contains using-directives, the effect is as if the
161 // using-directives from the second namespace also appeared in
162 // the first.
163 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
164 // Find the common ancestor between the effective context and
165 // the nominated namespace.
166 DeclContext *Common = UD->getNominatedNamespace();
167 while (!Common->Encloses(EffectiveDC))
168 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000169 Common = Common->getPrimaryContext();
John McCalld7be78a2009-11-10 07:01:13 +0000170
171 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
172 }
173
174 void done() {
175 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
176 }
177
178 typedef ListTy::iterator iterator;
179 typedef ListTy::const_iterator const_iterator;
180
181 iterator begin() { return list.begin(); }
182 iterator end() { return list.end(); }
183 const_iterator begin() const { return list.begin(); }
184 const_iterator end() const { return list.end(); }
185
186 std::pair<const_iterator,const_iterator>
187 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000188 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000189 UnqualUsingEntry::Comparator());
190 }
191 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000192}
193
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000194// Retrieve the set of identifier namespaces that correspond to a
195// specific kind of name lookup.
Mike Stump1eb44332009-09-09 15:08:12 +0000196inline unsigned
197getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000198 bool CPlusPlus) {
199 unsigned IDNS = 0;
200 switch (NameKind) {
201 case Sema::LookupOrdinaryName:
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000202 case Sema::LookupOperatorName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000203 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000204 IDNS = Decl::IDNS_Ordinary;
205 if (CPlusPlus)
206 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
207 break;
208
209 case Sema::LookupTagName:
210 IDNS = Decl::IDNS_Tag;
211 break;
212
213 case Sema::LookupMemberName:
214 IDNS = Decl::IDNS_Member;
215 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000216 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000217 break;
218
219 case Sema::LookupNestedNameSpecifierName:
220 case Sema::LookupNamespaceName:
221 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
222 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000223
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000224 case Sema::LookupObjCProtocolName:
225 IDNS = Decl::IDNS_ObjCProtocol;
226 break;
227
228 case Sema::LookupObjCImplementationName:
229 IDNS = Decl::IDNS_ObjCImplementation;
230 break;
231
232 case Sema::LookupObjCCategoryImplName:
233 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000234 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000235 }
236 return IDNS;
237}
238
John McCallf36e02d2009-10-09 21:13:30 +0000239// Necessary because CXXBasePaths is not complete in Sema.h
240void Sema::LookupResult::deletePaths(CXXBasePaths *Paths) {
241 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000242}
243
John McCallf36e02d2009-10-09 21:13:30 +0000244void Sema::LookupResult::resolveKind() {
245 unsigned N = Decls.size();
Douglas Gregor69d993a2009-01-17 01:13:24 +0000246
John McCallf36e02d2009-10-09 21:13:30 +0000247 // Fast case: no possible ambiguity.
248 if (N <= 1) return;
249
John McCall6e247262009-10-10 05:48:19 +0000250 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000251 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000252
John McCallf36e02d2009-10-09 21:13:30 +0000253 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
254
255 bool Ambiguous = false;
256 bool HasTag = false, HasFunction = false, HasNonFunction = false;
257
258 unsigned UniqueTagIndex = 0;
259
260 unsigned I = 0;
261 while (I < N) {
262 NamedDecl *D = Decls[I];
263 assert(D == D->getUnderlyingDecl());
264
265 NamedDecl *CanonD = cast<NamedDecl>(D->getCanonicalDecl());
266 if (!Unique.insert(CanonD)) {
267 // If it's not unique, pull something off the back (and
268 // continue at this index).
269 Decls[I] = Decls[--N];
270 } else if (isa<UnresolvedUsingDecl>(D)) {
271 // FIXME: proper support for UnresolvedUsingDecls.
272 Decls[I] = Decls[--N];
273 } else {
274 // Otherwise, do some decl type analysis and then continue.
275 if (isa<TagDecl>(D)) {
276 if (HasTag)
277 Ambiguous = true;
278 UniqueTagIndex = I;
279 HasTag = true;
280 } else if (D->isFunctionOrFunctionTemplate()) {
281 HasFunction = true;
282 } else {
283 if (HasNonFunction)
284 Ambiguous = true;
285 HasNonFunction = true;
286 }
287 I++;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000288 }
Mike Stump1eb44332009-09-09 15:08:12 +0000289 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000290
John McCallf36e02d2009-10-09 21:13:30 +0000291 // C++ [basic.scope.hiding]p2:
292 // A class name or enumeration name can be hidden by the name of
293 // an object, function, or enumerator declared in the same
294 // scope. If a class or enumeration name and an object, function,
295 // or enumerator are declared in the same scope (in any order)
296 // with the same name, the class or enumeration name is hidden
297 // wherever the object, function, or enumerator name is visible.
298 // But it's still an error if there are distinct tag types found,
299 // even if they're not visible. (ref?)
300 if (HasTag && !Ambiguous && (HasFunction || HasNonFunction))
301 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000302
John McCallf36e02d2009-10-09 21:13:30 +0000303 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000304
John McCallf36e02d2009-10-09 21:13:30 +0000305 if (HasFunction && HasNonFunction)
306 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000307
John McCallf36e02d2009-10-09 21:13:30 +0000308 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000309 setAmbiguous(LookupResult::AmbiguousReference);
John McCallf36e02d2009-10-09 21:13:30 +0000310 else if (N > 1)
John McCalla24dc2e2009-11-17 02:14:36 +0000311 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000312 else
John McCalla24dc2e2009-11-17 02:14:36 +0000313 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000314}
315
316/// @brief Converts the result of name lookup into a single (possible
317/// NULL) pointer to a declaration.
318///
319/// The resulting declaration will either be the declaration we found
320/// (if only a single declaration was found), an
321/// OverloadedFunctionDecl (if an overloaded function was found), or
322/// NULL (if no declaration was found). This conversion must not be
Mike Stump1eb44332009-09-09 15:08:12 +0000323/// used anywhere where name lookup could result in an ambiguity.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000324///
325/// The OverloadedFunctionDecl conversion is meant as a stop-gap
326/// solution, since it causes the OverloadedFunctionDecl to be
327/// leaked. FIXME: Eventually, there will be a better way to iterate
328/// over the set of overloaded functions returned by name lookup.
John McCallf36e02d2009-10-09 21:13:30 +0000329NamedDecl *Sema::LookupResult::getAsSingleDecl(ASTContext &C) const {
330 size_t size = Decls.size();
331 if (size == 0) return 0;
332 if (size == 1) return *begin();
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000333
John McCallf36e02d2009-10-09 21:13:30 +0000334 if (isAmbiguous()) return 0;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000335
John McCallf36e02d2009-10-09 21:13:30 +0000336 iterator I = begin(), E = end();
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000337
John McCallf36e02d2009-10-09 21:13:30 +0000338 OverloadedFunctionDecl *Ovl
339 = OverloadedFunctionDecl::Create(C, (*I)->getDeclContext(),
340 (*I)->getDeclName());
341 for (; I != E; ++I) {
342 NamedDecl *ND = *I;
343 assert(ND->getUnderlyingDecl() == ND
344 && "decls in lookup result should have redirections stripped");
345 assert(ND->isFunctionOrFunctionTemplate());
346 if (isa<FunctionDecl>(ND))
347 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregor31a19b62009-04-01 21:51:26 +0000348 else
John McCallf36e02d2009-10-09 21:13:30 +0000349 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
350 // FIXME: UnresolvedUsingDecls.
Douglas Gregor31a19b62009-04-01 21:51:26 +0000351 }
John McCallf36e02d2009-10-09 21:13:30 +0000352
353 return Ovl;
Douglas Gregord8635172009-02-02 21:35:47 +0000354}
355
John McCallf36e02d2009-10-09 21:13:30 +0000356void Sema::LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
357 CXXBasePaths::paths_iterator I, E;
358 DeclContext::lookup_iterator DI, DE;
359 for (I = P.begin(), E = P.end(); I != E; ++I)
360 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
361 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000362}
363
John McCallf36e02d2009-10-09 21:13:30 +0000364void Sema::LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
365 Paths = new CXXBasePaths;
366 Paths->swap(P);
367 addDeclsFromBasePaths(*Paths);
368 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000369 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000370}
371
John McCallf36e02d2009-10-09 21:13:30 +0000372void Sema::LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
373 Paths = new CXXBasePaths;
374 Paths->swap(P);
375 addDeclsFromBasePaths(*Paths);
376 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000377 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000378}
379
380void Sema::LookupResult::print(llvm::raw_ostream &Out) {
381 Out << Decls.size() << " result(s)";
382 if (isAmbiguous()) Out << ", ambiguous";
383 if (Paths) Out << ", base paths present";
384
385 for (iterator I = begin(), E = end(); I != E; ++I) {
386 Out << "\n";
387 (*I)->print(Out, 2);
388 }
389}
390
391// Adds all qualifying matches for a name within a decl context to the
392// given lookup result. Returns true if any matches were found.
John McCalld7be78a2009-11-10 07:01:13 +0000393static bool LookupDirect(Sema::LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +0000394 const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000395 bool Found = false;
396
John McCalld7be78a2009-11-10 07:01:13 +0000397 DeclContext::lookup_const_iterator I, E;
John McCalla24dc2e2009-11-17 02:14:36 +0000398 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I)
399 if (Sema::isAcceptableLookupResult(*I, R.getLookupKind(),
400 R.getIdentifierNamespace()))
John McCallf36e02d2009-10-09 21:13:30 +0000401 R.addDecl(*I), Found = true;
402
403 return Found;
404}
405
John McCalld7be78a2009-11-10 07:01:13 +0000406// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000407static bool
408CppNamespaceLookup(Sema::LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCalla24dc2e2009-11-17 02:14:36 +0000409 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000410
411 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
412
John McCalld7be78a2009-11-10 07:01:13 +0000413 // Perform direct name lookup into the LookupCtx.
John McCalla24dc2e2009-11-17 02:14:36 +0000414 bool Found = LookupDirect(R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000415
John McCalld7be78a2009-11-10 07:01:13 +0000416 // Perform direct name lookup into the namespaces nominated by the
417 // using directives whose common ancestor is this namespace.
418 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
419 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000420
John McCalld7be78a2009-11-10 07:01:13 +0000421 for (; UI != UEnd; ++UI)
John McCalla24dc2e2009-11-17 02:14:36 +0000422 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000423 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000424
425 R.resolveKind();
426
427 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000428}
429
430static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000431 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000432 return Ctx->isFileContext();
433 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000434}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000435
Douglas Gregore942bbe2009-09-10 16:57:35 +0000436// Find the next outer declaration context corresponding to this scope.
437static DeclContext *findOuterContext(Scope *S) {
438 for (S = S->getParent(); S; S = S->getParent())
439 if (S->getEntity())
440 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
441
442 return 0;
443}
444
John McCalla24dc2e2009-11-17 02:14:36 +0000445bool Sema::CppLookupName(LookupResult &R, Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000446 assert(getLangOptions().CPlusPlus &&
447 "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000448 LookupNameKind NameKind = R.getLookupKind();
Mike Stump1eb44332009-09-09 15:08:12 +0000449 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000450 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
John McCall02cace72009-08-28 07:59:38 +0000451
452 // If we're testing for redeclarations, also look in the friend namespaces.
John McCalla24dc2e2009-11-17 02:14:36 +0000453 if (R.isForRedeclaration()) {
John McCall02cace72009-08-28 07:59:38 +0000454 if (IDNS & Decl::IDNS_Tag) IDNS |= Decl::IDNS_TagFriend;
455 if (IDNS & Decl::IDNS_Ordinary) IDNS |= Decl::IDNS_OrdinaryFriend;
456 }
457
John McCalla24dc2e2009-11-17 02:14:36 +0000458 R.setIdentifierNamespace(IDNS);
459
460 DeclarationName Name = R.getLookupName();
461
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000462 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000463 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000464 I = IdResolver.begin(Name),
465 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000466
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000467 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000468 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000469 // ...During unqualified name lookup (3.4.1), the names appear as if
470 // they were declared in the nearest enclosing namespace which contains
471 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000472 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000473 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000474 //
475 // For example:
476 // namespace A { int i; }
477 // void foo() {
478 // int i;
479 // {
480 // using namespace A;
481 // ++i; // finds local 'i', A::i appears at global scope
482 // }
483 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000484 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000485 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000486 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000487 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000488 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000489 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
John McCallf36e02d2009-10-09 21:13:30 +0000490 Found = true;
491 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000492 }
493 }
John McCallf36e02d2009-10-09 21:13:30 +0000494 if (Found) {
495 R.resolveKind();
496 return true;
497 }
498
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000499 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregore942bbe2009-09-10 16:57:35 +0000500 DeclContext *OuterCtx = findOuterContext(S);
501 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
502 Ctx = Ctx->getLookupParent()) {
503 if (Ctx->isFunctionOrMethod())
504 continue;
505
506 // Perform qualified name lookup into this context.
507 // FIXME: In some cases, we know that every name that could be found by
508 // this qualified name lookup will also be on the identifier chain. For
509 // example, inside a class without any base classes, we never need to
510 // perform qualified lookup because all of the members are on top of the
511 // identifier chain.
John McCalla24dc2e2009-11-17 02:14:36 +0000512 if (LookupQualifiedName(R, Ctx))
John McCallf36e02d2009-10-09 21:13:30 +0000513 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000514 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000515 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000516 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000517
John McCalld7be78a2009-11-10 07:01:13 +0000518 // Stop if we ran out of scopes.
519 // FIXME: This really, really shouldn't be happening.
520 if (!S) return false;
521
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000522 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000523 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000524 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000525 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
526 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000527
John McCalld7be78a2009-11-10 07:01:13 +0000528 UnqualUsingDirectiveSet UDirs;
529 UDirs.visitScopeChain(Initial, S);
530 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000531
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000532 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000533 // Unqualified name lookup in C++ requires looking into scopes
534 // that aren't strictly lexical, and therefore we walk through the
535 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000536
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000537 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000538 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregora24eb4e2009-08-24 18:55:03 +0000539 if (Ctx->isTransparentContext())
540 continue;
541
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000542 assert(Ctx && Ctx->isFileContext() &&
543 "We should have been looking only at file context here already.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000544
545 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000546 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000547 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000548 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
549 // We found something. Look for anything else in our scope
550 // with this same name and in an acceptable identifier
551 // namespace, so that we can construct an overload set if we
552 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000553 Found = true;
554 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000555 }
556 }
557
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000558 // Look into context considering using-directives.
John McCalla24dc2e2009-11-17 02:14:36 +0000559 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
John McCallf36e02d2009-10-09 21:13:30 +0000560 Found = true;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000561
John McCallf36e02d2009-10-09 21:13:30 +0000562 if (Found) {
563 R.resolveKind();
564 return true;
565 }
566
John McCalla24dc2e2009-11-17 02:14:36 +0000567 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000568 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000569 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000570
John McCallf36e02d2009-10-09 21:13:30 +0000571 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000572}
573
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000574/// @brief Perform unqualified name lookup starting from a given
575/// scope.
576///
577/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
578/// used to find names within the current scope. For example, 'x' in
579/// @code
580/// int x;
581/// int f() {
582/// return x; // unqualified name look finds 'x' in the global scope
583/// }
584/// @endcode
585///
586/// Different lookup criteria can find different names. For example, a
587/// particular scope can have both a struct and a function of the same
588/// name, and each can be found by certain lookup criteria. For more
589/// information about lookup criteria, see the documentation for the
590/// class LookupCriteria.
591///
592/// @param S The scope from which unqualified name lookup will
593/// begin. If the lookup criteria permits, name lookup may also search
594/// in the parent scopes.
595///
596/// @param Name The name of the entity that we are searching for.
597///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000598/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +0000599/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +0000600/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000601///
602/// @returns The result of name lookup, which includes zero or more
603/// declarations and possibly additional information used to diagnose
604/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000605bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
606 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +0000607 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000608
John McCalla24dc2e2009-11-17 02:14:36 +0000609 LookupNameKind NameKind = R.getLookupKind();
610
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000611 if (!getLangOptions().CPlusPlus) {
612 // Unqualified name lookup in C/Objective-C is purely lexical, so
613 // search in the declarations attached to the name.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000614 unsigned IDNS = 0;
615 switch (NameKind) {
616 case Sema::LookupOrdinaryName:
617 IDNS = Decl::IDNS_Ordinary;
618 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000619
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000620 case Sema::LookupTagName:
621 IDNS = Decl::IDNS_Tag;
622 break;
623
624 case Sema::LookupMemberName:
625 IDNS = Decl::IDNS_Member;
626 break;
627
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000628 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000629 case Sema::LookupNestedNameSpecifierName:
630 case Sema::LookupNamespaceName:
631 assert(false && "C does not perform these kinds of name lookup");
632 break;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000633
634 case Sema::LookupRedeclarationWithLinkage:
635 // Find the nearest non-transparent declaration scope.
636 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000637 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000638 static_cast<DeclContext *>(S->getEntity())
639 ->isTransparentContext()))
640 S = S->getParent();
641 IDNS = Decl::IDNS_Ordinary;
642 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000643
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000644 case Sema::LookupObjCProtocolName:
645 IDNS = Decl::IDNS_ObjCProtocol;
646 break;
647
648 case Sema::LookupObjCImplementationName:
649 IDNS = Decl::IDNS_ObjCImplementation;
650 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000652 case Sema::LookupObjCCategoryImplName:
653 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000654 break;
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000655 }
656
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000657 // Scan up the scope chain looking for a decl that matches this
658 // identifier that is in the appropriate namespace. This search
659 // should not take long, as shadowing of names is uncommon, and
660 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000661 bool LeftStartingScope = false;
662
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000663 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +0000664 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000665 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000666 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000667 if (NameKind == LookupRedeclarationWithLinkage) {
668 // Determine whether this (or a previous) declaration is
669 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000670 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000671 LeftStartingScope = true;
672
673 // If we found something outside of our starting scope that
674 // does not have linkage, skip it.
675 if (LeftStartingScope && !((*I)->hasLinkage()))
676 continue;
677 }
678
John McCallf36e02d2009-10-09 21:13:30 +0000679 R.addDecl(*I);
680
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000681 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000682 // If this declaration has the "overloadable" attribute, we
683 // might have a set of overloaded functions.
684
685 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000686 while (!(S->getFlags() & Scope::DeclScope) ||
687 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000688 S = S->getParent();
689
690 // Find the last declaration in this scope (with the same
691 // name, naturally).
692 IdentifierResolver::iterator LastI = I;
693 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000694 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000695 break;
John McCallf36e02d2009-10-09 21:13:30 +0000696 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000697 }
Douglas Gregorf9201e02009-02-11 23:02:49 +0000698 }
699
John McCallf36e02d2009-10-09 21:13:30 +0000700 R.resolveKind();
701
702 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000703 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000704 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000705 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000706 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +0000707 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000708 }
709
710 // If we didn't find a use of this identifier, and if the identifier
711 // corresponds to a compiler builtin, create the decl object for the builtin
712 // now, injecting it into translation unit scope, and return it.
Mike Stump1eb44332009-09-09 15:08:12 +0000713 if (NameKind == LookupOrdinaryName ||
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000714 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000715 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000716 if (II && AllowBuiltinCreation) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000717 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor3e41d602009-02-13 23:20:09 +0000718 if (unsigned BuiltinID = II->getBuiltinID()) {
719 // In C++, we don't have any predefined library functions like
720 // 'malloc'. Instead, we'll just error.
Mike Stump1eb44332009-09-09 15:08:12 +0000721 if (getLangOptions().CPlusPlus &&
Douglas Gregor3e41d602009-02-13 23:20:09 +0000722 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCallf36e02d2009-10-09 21:13:30 +0000723 return false;
Douglas Gregor3e41d602009-02-13 23:20:09 +0000724
John McCallf36e02d2009-10-09 21:13:30 +0000725 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCalla24dc2e2009-11-17 02:14:36 +0000726 S, R.isForRedeclaration(),
727 R.getNameLoc());
John McCallf36e02d2009-10-09 21:13:30 +0000728 if (D) R.addDecl(D);
729 return (D != NULL);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000730 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000731 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000732 }
John McCallf36e02d2009-10-09 21:13:30 +0000733 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000734}
735
John McCall6e247262009-10-10 05:48:19 +0000736/// @brief Perform qualified name lookup in the namespaces nominated by
737/// using directives by the given context.
738///
739/// C++98 [namespace.qual]p2:
740/// Given X::m (where X is a user-declared namespace), or given ::m
741/// (where X is the global namespace), let S be the set of all
742/// declarations of m in X and in the transitive closure of all
743/// namespaces nominated by using-directives in X and its used
744/// namespaces, except that using-directives are ignored in any
745/// namespace, including X, directly containing one or more
746/// declarations of m. No namespace is searched more than once in
747/// the lookup of a name. If S is the empty set, the program is
748/// ill-formed. Otherwise, if S has exactly one member, or if the
749/// context of the reference is a using-declaration
750/// (namespace.udecl), S is the required set of declarations of
751/// m. Otherwise if the use of m is not one that allows a unique
752/// declaration to be chosen from S, the program is ill-formed.
753/// C++98 [namespace.qual]p5:
754/// During the lookup of a qualified namespace member name, if the
755/// lookup finds more than one declaration of the member, and if one
756/// declaration introduces a class name or enumeration name and the
757/// other declarations either introduce the same object, the same
758/// enumerator or a set of functions, the non-type name hides the
759/// class or enumeration name if and only if the declarations are
760/// from the same namespace; otherwise (the declarations are from
761/// different namespaces), the program is ill-formed.
762static bool LookupQualifiedNameInUsingDirectives(Sema::LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +0000763 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +0000764 assert(StartDC->isFileContext() && "start context is not a file context");
765
766 DeclContext::udir_iterator I = StartDC->using_directives_begin();
767 DeclContext::udir_iterator E = StartDC->using_directives_end();
768
769 if (I == E) return false;
770
771 // We have at least added all these contexts to the queue.
772 llvm::DenseSet<DeclContext*> Visited;
773 Visited.insert(StartDC);
774
775 // We have not yet looked into these namespaces, much less added
776 // their "using-children" to the queue.
777 llvm::SmallVector<NamespaceDecl*, 8> Queue;
778
779 // We have already looked into the initial namespace; seed the queue
780 // with its using-children.
781 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +0000782 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +0000783 if (Visited.insert(ND).second)
784 Queue.push_back(ND);
785 }
786
787 // The easiest way to implement the restriction in [namespace.qual]p5
788 // is to check whether any of the individual results found a tag
789 // and, if so, to declare an ambiguity if the final result is not
790 // a tag.
791 bool FoundTag = false;
792 bool FoundNonTag = false;
793
John McCalla24dc2e2009-11-17 02:14:36 +0000794 Sema::LookupResult LocalR(Sema::LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +0000795
796 bool Found = false;
797 while (!Queue.empty()) {
798 NamespaceDecl *ND = Queue.back();
799 Queue.pop_back();
800
801 // We go through some convolutions here to avoid copying results
802 // between LookupResults.
803 bool UseLocal = !R.empty();
804 Sema::LookupResult &DirectR = UseLocal ? LocalR : R;
John McCalla24dc2e2009-11-17 02:14:36 +0000805 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +0000806
807 if (FoundDirect) {
808 // First do any local hiding.
809 DirectR.resolveKind();
810
811 // If the local result is a tag, remember that.
812 if (DirectR.isSingleTagDecl())
813 FoundTag = true;
814 else
815 FoundNonTag = true;
816
817 // Append the local results to the total results if necessary.
818 if (UseLocal) {
819 R.addAllDecls(LocalR);
820 LocalR.clear();
821 }
822 }
823
824 // If we find names in this namespace, ignore its using directives.
825 if (FoundDirect) {
826 Found = true;
827 continue;
828 }
829
830 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
831 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
832 if (Visited.insert(Nom).second)
833 Queue.push_back(Nom);
834 }
835 }
836
837 if (Found) {
838 if (FoundTag && FoundNonTag)
839 R.setAmbiguousQualifiedTagHiding();
840 else
841 R.resolveKind();
842 }
843
844 return Found;
845}
846
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000847/// @brief Perform qualified name lookup into a given context.
848///
849/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
850/// names when the context of those names is explicit specified, e.g.,
851/// "std::vector" or "x->member".
852///
853/// Different lookup criteria can find different names. For example, a
854/// particular scope can have both a struct and a function of the same
855/// name, and each can be found by certain lookup criteria. For more
856/// information about lookup criteria, see the documentation for the
857/// class LookupCriteria.
858///
859/// @param LookupCtx The context in which qualified name lookup will
860/// search. If the lookup criteria permits, name lookup may also search
861/// in the parent contexts or (for C++ classes) base classes.
862///
863/// @param Name The name of the entity that we are searching for.
864///
865/// @param Criteria The criteria that this routine will use to
866/// determine which names are visible and which names will be
867/// found. Note that name lookup will find a name that is visible by
868/// the given criteria, but the entity itself may not be semantically
869/// correct or even the kind of entity expected based on the
870/// lookup. For example, searching for a nested-name-specifier name
871/// might result in an EnumDecl, which is visible but is not permitted
872/// as a nested-name-specifier in C++03.
873///
874/// @returns The result of name lookup, which includes zero or more
875/// declarations and possibly additional information used to diagnose
876/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000877bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000878 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +0000879
John McCalla24dc2e2009-11-17 02:14:36 +0000880 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +0000881 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000883 // If we're performing qualified name lookup (e.g., lookup into a
884 // struct), find fields as part of ordinary name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000885 LookupNameKind NameKind = R.getLookupKind();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000886 unsigned IDNS
Mike Stump1eb44332009-09-09 15:08:12 +0000887 = getIdentifierNamespacesFromLookupNameKind(NameKind,
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000888 getLangOptions().CPlusPlus);
889 if (NameKind == LookupOrdinaryName)
890 IDNS |= Decl::IDNS_Member;
Mike Stump1eb44332009-09-09 15:08:12 +0000891
John McCalla24dc2e2009-11-17 02:14:36 +0000892 R.setIdentifierNamespace(IDNS);
893
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000894 // Make sure that the declaration context is complete.
895 assert((!isa<TagDecl>(LookupCtx) ||
896 LookupCtx->isDependentContext() ||
897 cast<TagDecl>(LookupCtx)->isDefinition() ||
898 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
899 ->isBeingDefined()) &&
900 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000902 // Perform qualified name lookup into the LookupCtx.
John McCalla24dc2e2009-11-17 02:14:36 +0000903 if (LookupDirect(R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +0000904 R.resolveKind();
905 return true;
906 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000907
John McCall6e247262009-10-10 05:48:19 +0000908 // Don't descend into implied contexts for redeclarations.
909 // C++98 [namespace.qual]p6:
910 // In a declaration for a namespace member in which the
911 // declarator-id is a qualified-id, given that the qualified-id
912 // for the namespace member has the form
913 // nested-name-specifier unqualified-id
914 // the unqualified-id shall name a member of the namespace
915 // designated by the nested-name-specifier.
916 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +0000917 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +0000918 return false;
919
John McCalla24dc2e2009-11-17 02:14:36 +0000920 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +0000921 if (LookupCtx->isFileContext())
John McCalla24dc2e2009-11-17 02:14:36 +0000922 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +0000923
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000924 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +0000925 // classes, we're done.
John McCall6e247262009-10-10 05:48:19 +0000926 if (!isa<CXXRecordDecl>(LookupCtx))
John McCallf36e02d2009-10-09 21:13:30 +0000927 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000928
929 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +0000930 CXXRecordDecl *LookupRec = cast<CXXRecordDecl>(LookupCtx);
931 CXXBasePaths Paths;
932 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000933
934 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +0000935 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000936 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000937 case LookupOrdinaryName:
938 case LookupMemberName:
939 case LookupRedeclarationWithLinkage:
940 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
941 break;
942
943 case LookupTagName:
944 BaseCallback = &CXXRecordDecl::FindTagMember;
945 break;
946
947 case LookupOperatorName:
948 case LookupNamespaceName:
949 case LookupObjCProtocolName:
950 case LookupObjCImplementationName:
951 case LookupObjCCategoryImplName:
952 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +0000953 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000954
955 case LookupNestedNameSpecifierName:
956 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
957 break;
958 }
959
John McCalla24dc2e2009-11-17 02:14:36 +0000960 if (!LookupRec->lookupInBases(BaseCallback,
961 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +0000962 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000963
964 // C++ [class.member.lookup]p2:
965 // [...] If the resulting set of declarations are not all from
966 // sub-objects of the same type, or the set has a nonstatic member
967 // and includes members from distinct sub-objects, there is an
968 // ambiguity and the program is ill-formed. Otherwise that set is
969 // the result of the lookup.
970 // FIXME: support using declarations!
971 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +0000972 int SubobjectNumber = 0;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000973 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000974 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000975 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000976
977 // Determine whether we're looking at a distinct sub-object or not.
978 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +0000979 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000980 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
981 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +0000982 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +0000983 != Context.getCanonicalType(PathElement.Base->getType())) {
984 // We found members of the given name in two subobjects of
985 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +0000986 R.setAmbiguousBaseSubobjectTypes(Paths);
987 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000988 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
989 // We have a different subobject of the same type.
990
991 // C++ [class.member.lookup]p5:
992 // A static member, a nested type or an enumerator defined in
993 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +0000994 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000995 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000996 if (isa<VarDecl>(FirstDecl) ||
997 isa<TypeDecl>(FirstDecl) ||
998 isa<EnumConstantDecl>(FirstDecl))
999 continue;
1000
1001 if (isa<CXXMethodDecl>(FirstDecl)) {
1002 // Determine whether all of the methods are static.
1003 bool AllMethodsAreStatic = true;
1004 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1005 Func != Path->Decls.second; ++Func) {
1006 if (!isa<CXXMethodDecl>(*Func)) {
1007 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1008 break;
1009 }
1010
1011 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1012 AllMethodsAreStatic = false;
1013 break;
1014 }
1015 }
1016
1017 if (AllMethodsAreStatic)
1018 continue;
1019 }
1020
1021 // We have found a nonstatic member name in multiple, distinct
1022 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001023 R.setAmbiguousBaseSubobjects(Paths);
1024 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001025 }
1026 }
1027
1028 // Lookup in a base class succeeded; return these results.
1029
John McCallf36e02d2009-10-09 21:13:30 +00001030 DeclContext::lookup_iterator I, E;
1031 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I)
1032 R.addDecl(*I);
1033 R.resolveKind();
1034 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001035}
1036
1037/// @brief Performs name lookup for a name that was parsed in the
1038/// source code, and may contain a C++ scope specifier.
1039///
1040/// This routine is a convenience routine meant to be called from
1041/// contexts that receive a name and an optional C++ scope specifier
1042/// (e.g., "N::M::x"). It will then perform either qualified or
1043/// unqualified name lookup (with LookupQualifiedName or LookupName,
1044/// respectively) on the given name and return those results.
1045///
1046/// @param S The scope from which unqualified name lookup will
1047/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001048///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001049/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001050///
1051/// @param Name The name of the entity that name lookup will
1052/// search for.
1053///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001054/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001055/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001056/// C library functions (like "malloc") are implicitly declared.
1057///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001058/// @param EnteringContext Indicates whether we are going to enter the
1059/// context of the scope-specifier SS (if present).
1060///
John McCallf36e02d2009-10-09 21:13:30 +00001061/// @returns True if any decls were found (but possibly ambiguous)
1062bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001063 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001064 if (SS && SS->isInvalid()) {
1065 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001066 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001067 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001068 }
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Douglas Gregor495c35d2009-08-25 22:51:20 +00001070 if (SS && SS->isSet()) {
1071 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001072 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001073 // contex, and will perform name lookup in that context.
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001074 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCallf36e02d2009-10-09 21:13:30 +00001075 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001076
John McCalla24dc2e2009-11-17 02:14:36 +00001077 R.setContextRange(SS->getRange());
1078
1079 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001080 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001081
Douglas Gregor495c35d2009-08-25 22:51:20 +00001082 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001083 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001084 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001085 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001086 }
1087
Mike Stump1eb44332009-09-09 15:08:12 +00001088 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001089 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001090}
1091
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001092
Douglas Gregor7176fff2009-01-15 00:26:24 +00001093/// @brief Produce a diagnostic describing the ambiguity that resulted
1094/// from name lookup.
1095///
1096/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001097///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001098/// @param Name The name of the entity that name lookup was
1099/// searching for.
1100///
1101/// @param NameLoc The location of the name within the source code.
1102///
1103/// @param LookupRange A source range that provides more
1104/// source-location information concerning the lookup itself. For
1105/// example, this range might highlight a nested-name-specifier that
1106/// precedes the name.
1107///
1108/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001109bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001110 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1111
John McCalla24dc2e2009-11-17 02:14:36 +00001112 DeclarationName Name = Result.getLookupName();
1113 SourceLocation NameLoc = Result.getNameLoc();
1114 SourceRange LookupRange = Result.getContextRange();
1115
John McCall6e247262009-10-10 05:48:19 +00001116 switch (Result.getAmbiguityKind()) {
1117 case LookupResult::AmbiguousBaseSubobjects: {
1118 CXXBasePaths *Paths = Result.getBasePaths();
1119 QualType SubobjectType = Paths->front().back().Base->getType();
1120 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1121 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1122 << LookupRange;
1123
1124 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1125 while (isa<CXXMethodDecl>(*Found) &&
1126 cast<CXXMethodDecl>(*Found)->isStatic())
1127 ++Found;
1128
1129 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1130
1131 return true;
1132 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001133
John McCall6e247262009-10-10 05:48:19 +00001134 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001135 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1136 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001137
1138 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001139 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001140 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1141 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001142 Path != PathEnd; ++Path) {
1143 Decl *D = *Path->Decls.first;
1144 if (DeclsPrinted.insert(D).second)
1145 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1146 }
1147
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001148 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001149 }
1150
John McCall6e247262009-10-10 05:48:19 +00001151 case LookupResult::AmbiguousTagHiding: {
1152 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001153
John McCall6e247262009-10-10 05:48:19 +00001154 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1155
1156 LookupResult::iterator DI, DE = Result.end();
1157 for (DI = Result.begin(); DI != DE; ++DI)
1158 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1159 TagDecls.insert(TD);
1160 Diag(TD->getLocation(), diag::note_hidden_tag);
1161 }
1162
1163 for (DI = Result.begin(); DI != DE; ++DI)
1164 if (!isa<TagDecl>(*DI))
1165 Diag((*DI)->getLocation(), diag::note_hiding_object);
1166
1167 // For recovery purposes, go ahead and implement the hiding.
1168 Result.hideDecls(TagDecls);
1169
1170 return true;
1171 }
1172
1173 case LookupResult::AmbiguousReference: {
1174 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001175
John McCall6e247262009-10-10 05:48:19 +00001176 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1177 for (; DI != DE; ++DI)
1178 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001179
John McCall6e247262009-10-10 05:48:19 +00001180 return true;
1181 }
1182 }
1183
1184 llvm::llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001185 return true;
1186}
Douglas Gregorfa047642009-02-04 00:32:51 +00001187
Mike Stump1eb44332009-09-09 15:08:12 +00001188static void
1189addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001190 ASTContext &Context,
1191 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001192 Sema::AssociatedClassSet &AssociatedClasses);
1193
1194static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1195 DeclContext *Ctx) {
1196 if (Ctx->isFileContext())
1197 Namespaces.insert(Ctx);
1198}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001199
Mike Stump1eb44332009-09-09 15:08:12 +00001200// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001201// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001202static void
1203addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001204 ASTContext &Context,
1205 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001206 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001207 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001208 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001209 switch (Arg.getKind()) {
1210 case TemplateArgument::Null:
1211 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Douglas Gregor69be8d62009-07-08 07:51:57 +00001213 case TemplateArgument::Type:
1214 // [...] the namespaces and classes associated with the types of the
1215 // template arguments provided for template type parameters (excluding
1216 // template template parameters)
1217 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1218 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001219 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001220 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Douglas Gregor788cd062009-11-11 01:00:40 +00001222 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001223 // [...] the namespaces in which any template template arguments are
1224 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001225 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001226 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001227 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001228 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001229 DeclContext *Ctx = ClassTemplate->getDeclContext();
1230 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1231 AssociatedClasses.insert(EnclosingClass);
1232 // Add the associated namespace for this class.
1233 while (Ctx->isRecord())
1234 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001235 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001236 }
1237 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001238 }
1239
1240 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001241 case TemplateArgument::Integral:
1242 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001243 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001244 // associated namespaces. ]
1245 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Douglas Gregor69be8d62009-07-08 07:51:57 +00001247 case TemplateArgument::Pack:
1248 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1249 PEnd = Arg.pack_end();
1250 P != PEnd; ++P)
1251 addAssociatedClassesAndNamespaces(*P, Context,
1252 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001253 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001254 break;
1255 }
1256}
1257
Douglas Gregorfa047642009-02-04 00:32:51 +00001258// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001259// argument-dependent lookup with an argument of class type
1260// (C++ [basic.lookup.koenig]p2).
1261static void
1262addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregorfa047642009-02-04 00:32:51 +00001263 ASTContext &Context,
1264 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001265 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001266 // C++ [basic.lookup.koenig]p2:
1267 // [...]
1268 // -- If T is a class type (including unions), its associated
1269 // classes are: the class itself; the class of which it is a
1270 // member, if any; and its direct and indirect base
1271 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001272 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001273
1274 // Add the class of which it is a member, if any.
1275 DeclContext *Ctx = Class->getDeclContext();
1276 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1277 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001278 // Add the associated namespace for this class.
1279 while (Ctx->isRecord())
1280 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001281 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Douglas Gregorfa047642009-02-04 00:32:51 +00001283 // Add the class itself. If we've already seen this class, we don't
1284 // need to visit base classes.
1285 if (!AssociatedClasses.insert(Class))
1286 return;
1287
Mike Stump1eb44332009-09-09 15:08:12 +00001288 // -- If T is a template-id, its associated namespaces and classes are
1289 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001290 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001291 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001292 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001293 // namespaces in which any template template arguments are defined; and
1294 // the classes in which any member templates used as template template
1295 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001296 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001297 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001298 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1299 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1300 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1301 AssociatedClasses.insert(EnclosingClass);
1302 // Add the associated namespace for this class.
1303 while (Ctx->isRecord())
1304 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001305 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Douglas Gregor69be8d62009-07-08 07:51:57 +00001307 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1308 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1309 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1310 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001311 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001312 }
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Douglas Gregorfa047642009-02-04 00:32:51 +00001314 // Add direct and indirect base classes along with their associated
1315 // namespaces.
1316 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1317 Bases.push_back(Class);
1318 while (!Bases.empty()) {
1319 // Pop this class off the stack.
1320 Class = Bases.back();
1321 Bases.pop_back();
1322
1323 // Visit the base classes.
1324 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1325 BaseEnd = Class->bases_end();
1326 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001327 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001328 // In dependent contexts, we do ADL twice, and the first time around,
1329 // the base type might be a dependent TemplateSpecializationType, or a
1330 // TemplateTypeParmType. If that happens, simply ignore it.
1331 // FIXME: If we want to support export, we probably need to add the
1332 // namespace of the template in a TemplateSpecializationType, or even
1333 // the classes and namespaces of known non-dependent arguments.
1334 if (!BaseType)
1335 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001336 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1337 if (AssociatedClasses.insert(BaseDecl)) {
1338 // Find the associated namespace for this base class.
1339 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1340 while (BaseCtx->isRecord())
1341 BaseCtx = BaseCtx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001342 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001343
1344 // Make sure we visit the bases of this base class.
1345 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1346 Bases.push_back(BaseDecl);
1347 }
1348 }
1349 }
1350}
1351
1352// \brief Add the associated classes and namespaces for
1353// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001354// (C++ [basic.lookup.koenig]p2).
1355static void
1356addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregorfa047642009-02-04 00:32:51 +00001357 ASTContext &Context,
1358 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001359 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001360 // C++ [basic.lookup.koenig]p2:
1361 //
1362 // For each argument type T in the function call, there is a set
1363 // of zero or more associated namespaces and a set of zero or more
1364 // associated classes to be considered. The sets of namespaces and
1365 // classes is determined entirely by the types of the function
1366 // arguments (and the namespace of any template template
1367 // argument). Typedef names and using-declarations used to specify
1368 // the types do not contribute to this set. The sets of namespaces
1369 // and classes are determined in the following way:
1370 T = Context.getCanonicalType(T).getUnqualifiedType();
1371
1372 // -- If T is a pointer to U or an array of U, its associated
Mike Stump1eb44332009-09-09 15:08:12 +00001373 // namespaces and classes are those associated with U.
Douglas Gregorfa047642009-02-04 00:32:51 +00001374 //
1375 // We handle this by unwrapping pointer and array types immediately,
1376 // to avoid unnecessary recursion.
1377 while (true) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001378 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001379 T = Ptr->getPointeeType();
1380 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1381 T = Ptr->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001382 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001383 break;
1384 }
1385
1386 // -- If T is a fundamental type, its associated sets of
1387 // namespaces and classes are both empty.
John McCall183700f2009-09-21 23:43:11 +00001388 if (T->getAs<BuiltinType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001389 return;
1390
1391 // -- If T is a class type (including unions), its associated
1392 // classes are: the class itself; the class of which it is a
1393 // member, if any; and its direct and indirect base
1394 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001395 // which its associated classes are defined.
Ted Kremenek6217b802009-07-29 21:53:49 +00001396 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001397 if (CXXRecordDecl *ClassDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001398 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001399 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1400 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001401 AssociatedClasses);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001402 return;
1403 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001404
1405 // -- If T is an enumeration type, its associated namespace is
1406 // the namespace in which it is defined. If it is class
1407 // member, its associated class is the member’s class; else
Mike Stump1eb44332009-09-09 15:08:12 +00001408 // it has no associated class.
John McCall183700f2009-09-21 23:43:11 +00001409 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001410 EnumDecl *Enum = EnumT->getDecl();
1411
1412 DeclContext *Ctx = Enum->getDeclContext();
1413 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1414 AssociatedClasses.insert(EnclosingClass);
1415
1416 // Add the associated namespace for this class.
1417 while (Ctx->isRecord())
1418 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001419 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001420
1421 return;
1422 }
1423
1424 // -- If T is a function type, its associated namespaces and
1425 // classes are those associated with the function parameter
1426 // types and those associated with the return type.
John McCall183700f2009-09-21 23:43:11 +00001427 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001428 // Return type
John McCall183700f2009-09-21 23:43:11 +00001429 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001430 Context,
John McCall6ff07852009-08-07 22:18:02 +00001431 AssociatedNamespaces, AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001432
John McCall183700f2009-09-21 23:43:11 +00001433 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001434 if (!Proto)
1435 return;
1436
1437 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001438 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001439 ArgEnd = Proto->arg_type_end();
Douglas Gregorfa047642009-02-04 00:32:51 +00001440 Arg != ArgEnd; ++Arg)
1441 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCall6ff07852009-08-07 22:18:02 +00001442 AssociatedNamespaces, AssociatedClasses);
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Douglas Gregorfa047642009-02-04 00:32:51 +00001444 return;
1445 }
1446
1447 // -- If T is a pointer to a member function of a class X, its
1448 // associated namespaces and classes are those associated
1449 // with the function parameter types and return type,
Mike Stump1eb44332009-09-09 15:08:12 +00001450 // together with those associated with X.
Douglas Gregorfa047642009-02-04 00:32:51 +00001451 //
1452 // -- If T is a pointer to a data member of class X, its
1453 // associated namespaces and classes are those associated
1454 // with the member type together with those associated with
Mike Stump1eb44332009-09-09 15:08:12 +00001455 // X.
Ted Kremenek6217b802009-07-29 21:53:49 +00001456 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001457 // Handle the type that the pointer to member points to.
1458 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1459 Context,
John McCall6ff07852009-08-07 22:18:02 +00001460 AssociatedNamespaces,
1461 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001462
1463 // Handle the class type into which this points.
Ted Kremenek6217b802009-07-29 21:53:49 +00001464 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001465 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1466 Context,
John McCall6ff07852009-08-07 22:18:02 +00001467 AssociatedNamespaces,
1468 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001469
1470 return;
1471 }
1472
1473 // FIXME: What about block pointers?
1474 // FIXME: What about Objective-C message sends?
1475}
1476
1477/// \brief Find the associated classes and namespaces for
1478/// argument-dependent lookup for a call with the given set of
1479/// arguments.
1480///
1481/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001482/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001483/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001484void
Douglas Gregorfa047642009-02-04 00:32:51 +00001485Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1486 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001487 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001488 AssociatedNamespaces.clear();
1489 AssociatedClasses.clear();
1490
1491 // C++ [basic.lookup.koenig]p2:
1492 // For each argument type T in the function call, there is a set
1493 // of zero or more associated namespaces and a set of zero or more
1494 // associated classes to be considered. The sets of namespaces and
1495 // classes is determined entirely by the types of the function
1496 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001497 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001498 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1499 Expr *Arg = Args[ArgIdx];
1500
1501 if (Arg->getType() != Context.OverloadTy) {
1502 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001503 AssociatedNamespaces,
1504 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001505 continue;
1506 }
1507
1508 // [...] In addition, if the argument is the name or address of a
1509 // set of overloaded functions and/or function templates, its
1510 // associated classes and namespaces are the union of those
1511 // associated with each of the members of the set: the namespace
1512 // in which the function or function template is defined and the
1513 // classes and namespaces associated with its (non-dependent)
1514 // parameter types and return type.
1515 DeclRefExpr *DRE = 0;
Douglas Gregordaa439a2009-07-08 10:57:20 +00001516 TemplateIdRefExpr *TIRE = 0;
1517 Arg = Arg->IgnoreParens();
Douglas Gregorfa047642009-02-04 00:32:51 +00001518 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregordaa439a2009-07-08 10:57:20 +00001519 if (unaryOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001520 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
Douglas Gregordaa439a2009-07-08 10:57:20 +00001521 TIRE = dyn_cast<TemplateIdRefExpr>(unaryOp->getSubExpr());
1522 }
1523 } else {
Douglas Gregorfa047642009-02-04 00:32:51 +00001524 DRE = dyn_cast<DeclRefExpr>(Arg);
Douglas Gregordaa439a2009-07-08 10:57:20 +00001525 TIRE = dyn_cast<TemplateIdRefExpr>(Arg);
1526 }
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Douglas Gregordaa439a2009-07-08 10:57:20 +00001528 OverloadedFunctionDecl *Ovl = 0;
1529 if (DRE)
1530 Ovl = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1531 else if (TIRE)
Douglas Gregord99cbe62009-07-29 18:26:50 +00001532 Ovl = TIRE->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001533 if (!Ovl)
1534 continue;
1535
1536 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1537 FuncEnd = Ovl->function_end();
1538 Func != FuncEnd; ++Func) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001539 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func);
1540 if (!FDecl)
1541 FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001542
1543 // Add the namespace in which this function was defined. Note
1544 // that, if this is a member function, we do *not* consider the
1545 // enclosing namespace of its class.
1546 DeclContext *Ctx = FDecl->getDeclContext();
John McCall6ff07852009-08-07 22:18:02 +00001547 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001548
1549 // Add the classes and namespaces associated with the parameter
1550 // types and return type of this function.
1551 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001552 AssociatedNamespaces,
1553 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001554 }
1555 }
1556}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001557
1558/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1559/// an acceptable non-member overloaded operator for a call whose
1560/// arguments have types T1 (and, if non-empty, T2). This routine
1561/// implements the check in C++ [over.match.oper]p3b2 concerning
1562/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001563static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001564IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1565 QualType T1, QualType T2,
1566 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001567 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1568 return true;
1569
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001570 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1571 return true;
1572
John McCall183700f2009-09-21 23:43:11 +00001573 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001574 if (Proto->getNumArgs() < 1)
1575 return false;
1576
1577 if (T1->isEnumeralType()) {
1578 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001579 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001580 return true;
1581 }
1582
1583 if (Proto->getNumArgs() < 2)
1584 return false;
1585
1586 if (!T2.isNull() && T2->isEnumeralType()) {
1587 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001588 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001589 return true;
1590 }
1591
1592 return false;
1593}
1594
Douglas Gregor6e378de2009-04-23 23:18:26 +00001595/// \brief Find the protocol with the given name, if any.
1596ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCallf36e02d2009-10-09 21:13:30 +00001597 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001598 return cast_or_null<ObjCProtocolDecl>(D);
1599}
1600
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001601/// \brief Find the Objective-C category implementation with the given
1602/// name, if any.
1603ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
John McCallf36e02d2009-10-09 21:13:30 +00001604 Decl *D = LookupSingleName(TUScope, II, LookupObjCCategoryImplName);
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001605 return cast_or_null<ObjCCategoryImplDecl>(D);
1606}
1607
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001608void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001609 QualType T1, QualType T2,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001610 FunctionSet &Functions) {
1611 // C++ [over.match.oper]p3:
1612 // -- The set of non-member candidates is the result of the
1613 // unqualified lookup of operator@ in the context of the
1614 // expression according to the usual rules for name lookup in
1615 // unqualified function calls (3.4.2) except that all member
1616 // functions are ignored. However, if no operand has a class
1617 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00001618 // that have a first parameter of type T1 or "reference to
1619 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001620 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00001621 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001622 // when T2 is an enumeration type, are candidate functions.
1623 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00001624 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1625 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001627 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1628
John McCallf36e02d2009-10-09 21:13:30 +00001629 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001630 return;
1631
1632 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1633 Op != OpEnd; ++Op) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001634 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001635 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1636 Functions.insert(FD); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00001637 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor364e0212009-06-27 21:05:07 +00001638 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1639 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00001640 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00001641 // later?
1642 if (!FunTmpl->getDeclContext()->isRecord())
1643 Functions.insert(FunTmpl);
1644 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001645 }
1646}
1647
John McCall6ff07852009-08-07 22:18:02 +00001648static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1649 Decl *D) {
1650 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1651 Functions.insert(Func);
1652 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1653 Functions.insert(FunTmpl);
1654}
1655
Sebastian Redl644be852009-10-23 19:23:15 +00001656void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001657 Expr **Args, unsigned NumArgs,
1658 FunctionSet &Functions) {
1659 // Find all of the associated namespaces and classes based on the
1660 // arguments we have.
1661 AssociatedNamespaceSet AssociatedNamespaces;
1662 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00001663 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00001664 AssociatedNamespaces,
1665 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001666
Sebastian Redl644be852009-10-23 19:23:15 +00001667 QualType T1, T2;
1668 if (Operator) {
1669 T1 = Args[0]->getType();
1670 if (NumArgs >= 2)
1671 T2 = Args[1]->getType();
1672 }
1673
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001674 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001675 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1676 // and let Y be the lookup set produced by argument dependent
1677 // lookup (defined as follows). If X contains [...] then Y is
1678 // empty. Otherwise Y is the set of declarations found in the
1679 // namespaces associated with the argument types as described
1680 // below. The set of declarations found by the lookup of the name
1681 // is the union of X and Y.
1682 //
1683 // Here, we compute Y and add its members to the overloaded
1684 // candidate set.
1685 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001686 NSEnd = AssociatedNamespaces.end();
1687 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001688 // When considering an associated namespace, the lookup is the
1689 // same as the lookup performed when the associated namespace is
1690 // used as a qualifier (3.4.3.2) except that:
1691 //
1692 // -- Any using-directives in the associated namespace are
1693 // ignored.
1694 //
John McCall6ff07852009-08-07 22:18:02 +00001695 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001696 // associated classes are visible within their respective
1697 // namespaces even if they are not visible during an ordinary
1698 // lookup (11.4).
1699 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00001700 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6ff07852009-08-07 22:18:02 +00001701 Decl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00001702 // If the only declaration here is an ordinary friend, consider
1703 // it only if it was declared in an associated classes.
1704 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00001705 DeclContext *LexDC = D->getLexicalDeclContext();
1706 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1707 continue;
1708 }
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Sebastian Redl644be852009-10-23 19:23:15 +00001710 FunctionDecl *Fn;
1711 if (!Operator || !(Fn = dyn_cast<FunctionDecl>(D)) ||
1712 IsAcceptableNonMemberOperatorCandidate(Fn, T1, T2, Context))
1713 CollectFunctionDecl(Functions, D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001714 }
1715 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001716}