blob: 724e2fc1e4f586c7c312783233181dbfe7770ed8 [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"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6e247262009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000030#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000031#include <vector>
32#include <iterator>
33#include <utility>
34#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000035
36using namespace clang;
37
John McCalld7be78a2009-11-10 07:01:13 +000038namespace {
39 class UnqualUsingEntry {
40 const DeclContext *Nominated;
41 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000042
John McCalld7be78a2009-11-10 07:01:13 +000043 public:
44 UnqualUsingEntry(const DeclContext *Nominated,
45 const DeclContext *CommonAncestor)
46 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
47 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000048
John McCalld7be78a2009-11-10 07:01:13 +000049 const DeclContext *getCommonAncestor() const {
50 return CommonAncestor;
51 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000052
John McCalld7be78a2009-11-10 07:01:13 +000053 const DeclContext *getNominatedNamespace() const {
54 return Nominated;
55 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000056
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +000062
John McCalld7be78a2009-11-10 07:01:13 +000063 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
64 return E.getCommonAncestor() < DC;
65 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000066
John McCalld7be78a2009-11-10 07:01:13 +000067 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
68 return DC < E.getCommonAncestor();
69 }
70 };
71 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000072
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +000077
John McCalld7be78a2009-11-10 07:01:13 +000078 ListTy list;
79 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000080
John McCalld7be78a2009-11-10 07:01:13 +000081 public:
82 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000083
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +000092
John McCalld7be78a2009-11-10 07:01:13 +000093 for (; S; S = S->getParent()) {
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000104 }
105 }
John McCalld7be78a2009-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 McCall12ea5782009-11-10 09:20:04 +0000170 Common = Common->getPrimaryContext();
John McCalld7be78a2009-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 McCall12ea5782009-11-10 09:20:04 +0000189 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000190 UnqualUsingEntry::Comparator());
191 }
192 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000193}
194
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000195// Retrieve the set of identifier namespaces that correspond to a
196// specific kind of name lookup.
Mike Stump1eb44332009-09-09 15:08:12 +0000197inline unsigned
198getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000199 bool CPlusPlus) {
200 unsigned IDNS = 0;
201 switch (NameKind) {
202 case Sema::LookupOrdinaryName:
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000203 case Sema::LookupOperatorName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000204 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-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 Stump1eb44332009-09-09 15:08:12 +0000217 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-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 Gregor6e378de2009-04-23 23:18:26 +0000224
John McCall9f54ad42009-12-10 09:41:52 +0000225 case Sema::LookupUsingDeclName:
226 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
227 | Decl::IDNS_Member | Decl::IDNS_Using;
228 break;
229
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000230 case Sema::LookupObjCProtocolName:
231 IDNS = Decl::IDNS_ObjCProtocol;
232 break;
233
234 case Sema::LookupObjCImplementationName:
235 IDNS = Decl::IDNS_ObjCImplementation;
236 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000237 }
238 return IDNS;
239}
240
John McCallf36e02d2009-10-09 21:13:30 +0000241// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000242void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000243 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000244}
245
John McCall7453ed42009-11-22 00:44:51 +0000246/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000247void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000248 unsigned N = Decls.size();
John McCall9f54ad42009-12-10 09:41:52 +0000249
John McCallf36e02d2009-10-09 21:13:30 +0000250 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000251 if (N == 0) {
252 assert(ResultKind == NotFound);
253 return;
254 }
255
John McCall7453ed42009-11-22 00:44:51 +0000256 // If there's a single decl, we need to examine it to decide what
257 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000258 if (N == 1) {
John McCall7453ed42009-11-22 00:44:51 +0000259 if (isa<FunctionTemplateDecl>(Decls[0]))
260 ResultKind = FoundOverloaded;
261 else if (isa<UnresolvedUsingValueDecl>(Decls[0]))
John McCall7ba107a2009-11-18 02:36:19 +0000262 ResultKind = FoundUnresolvedValue;
263 return;
264 }
John McCallf36e02d2009-10-09 21:13:30 +0000265
John McCall6e247262009-10-10 05:48:19 +0000266 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000267 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000268
John McCallf36e02d2009-10-09 21:13:30 +0000269 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
270
271 bool Ambiguous = false;
272 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000273 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000274
275 unsigned UniqueTagIndex = 0;
276
277 unsigned I = 0;
278 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000279 NamedDecl *D = Decls[I]->getUnderlyingDecl();
280 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000281
John McCall314be4e2009-11-17 07:50:12 +0000282 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000283 // If it's not unique, pull something off the back (and
284 // continue at this index).
285 Decls[I] = Decls[--N];
John McCallf36e02d2009-10-09 21:13:30 +0000286 } else {
287 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000288
289 if (isa<UnresolvedUsingValueDecl>(D)) {
290 HasUnresolved = true;
291 } else if (isa<TagDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000292 if (HasTag)
293 Ambiguous = true;
294 UniqueTagIndex = I;
295 HasTag = true;
John McCall7453ed42009-11-22 00:44:51 +0000296 } else if (isa<FunctionTemplateDecl>(D)) {
297 HasFunction = true;
298 HasFunctionTemplate = true;
299 } else if (isa<FunctionDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000300 HasFunction = true;
301 } else {
302 if (HasNonFunction)
303 Ambiguous = true;
304 HasNonFunction = true;
305 }
306 I++;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000309
John McCallf36e02d2009-10-09 21:13:30 +0000310 // C++ [basic.scope.hiding]p2:
311 // A class name or enumeration name can be hidden by the name of
312 // an object, function, or enumerator declared in the same
313 // scope. If a class or enumeration name and an object, function,
314 // or enumerator are declared in the same scope (in any order)
315 // with the same name, the class or enumeration name is hidden
316 // wherever the object, function, or enumerator name is visible.
317 // But it's still an error if there are distinct tag types found,
318 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000319 if (HideTags && HasTag && !Ambiguous &&
320 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000321 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000322
John McCallf36e02d2009-10-09 21:13:30 +0000323 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000324
John McCallfda8e122009-12-03 00:58:24 +0000325 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000326 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000327
John McCallf36e02d2009-10-09 21:13:30 +0000328 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000329 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000330 else if (HasUnresolved)
331 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000332 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000333 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000334 else
John McCalla24dc2e2009-11-17 02:14:36 +0000335 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000336}
337
John McCall7d384dd2009-11-18 07:57:50 +0000338void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000339 CXXBasePaths::paths_iterator I, E;
340 DeclContext::lookup_iterator DI, DE;
341 for (I = P.begin(), E = P.end(); I != E; ++I)
342 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
343 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000344}
345
John McCall7d384dd2009-11-18 07:57:50 +0000346void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000347 Paths = new CXXBasePaths;
348 Paths->swap(P);
349 addDeclsFromBasePaths(*Paths);
350 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000351 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000352}
353
John McCall7d384dd2009-11-18 07:57:50 +0000354void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000355 Paths = new CXXBasePaths;
356 Paths->swap(P);
357 addDeclsFromBasePaths(*Paths);
358 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000359 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000360}
361
John McCall7d384dd2009-11-18 07:57:50 +0000362void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000363 Out << Decls.size() << " result(s)";
364 if (isAmbiguous()) Out << ", ambiguous";
365 if (Paths) Out << ", base paths present";
366
367 for (iterator I = begin(), E = end(); I != E; ++I) {
368 Out << "\n";
369 (*I)->print(Out, 2);
370 }
371}
372
373// Adds all qualifying matches for a name within a decl context to the
374// given lookup result. Returns true if any matches were found.
John McCall7d384dd2009-11-18 07:57:50 +0000375static bool LookupDirect(LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000376 bool Found = false;
377
John McCalld7be78a2009-11-10 07:01:13 +0000378 DeclContext::lookup_const_iterator I, E;
John McCalla24dc2e2009-11-17 02:14:36 +0000379 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I)
380 if (Sema::isAcceptableLookupResult(*I, R.getLookupKind(),
381 R.getIdentifierNamespace()))
John McCallf36e02d2009-10-09 21:13:30 +0000382 R.addDecl(*I), Found = true;
383
384 return Found;
385}
386
John McCalld7be78a2009-11-10 07:01:13 +0000387// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000388static bool
John McCall7d384dd2009-11-18 07:57:50 +0000389CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCalla24dc2e2009-11-17 02:14:36 +0000390 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000391
392 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
393
John McCalld7be78a2009-11-10 07:01:13 +0000394 // Perform direct name lookup into the LookupCtx.
John McCalla24dc2e2009-11-17 02:14:36 +0000395 bool Found = LookupDirect(R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000396
John McCalld7be78a2009-11-10 07:01:13 +0000397 // Perform direct name lookup into the namespaces nominated by the
398 // using directives whose common ancestor is this namespace.
399 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
400 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000401
John McCalld7be78a2009-11-10 07:01:13 +0000402 for (; UI != UEnd; ++UI)
John McCalla24dc2e2009-11-17 02:14:36 +0000403 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000404 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000405
406 R.resolveKind();
407
408 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000409}
410
411static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000412 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000413 return Ctx->isFileContext();
414 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000415}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000416
Douglas Gregore942bbe2009-09-10 16:57:35 +0000417// Find the next outer declaration context corresponding to this scope.
418static DeclContext *findOuterContext(Scope *S) {
419 for (S = S->getParent(); S; S = S->getParent())
420 if (S->getEntity())
421 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
422
423 return 0;
424}
425
John McCalla24dc2e2009-11-17 02:14:36 +0000426bool Sema::CppLookupName(LookupResult &R, Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000427 assert(getLangOptions().CPlusPlus &&
428 "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000429 LookupNameKind NameKind = R.getLookupKind();
Mike Stump1eb44332009-09-09 15:08:12 +0000430 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000431 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
John McCall02cace72009-08-28 07:59:38 +0000432
433 // If we're testing for redeclarations, also look in the friend namespaces.
John McCalla24dc2e2009-11-17 02:14:36 +0000434 if (R.isForRedeclaration()) {
John McCall02cace72009-08-28 07:59:38 +0000435 if (IDNS & Decl::IDNS_Tag) IDNS |= Decl::IDNS_TagFriend;
436 if (IDNS & Decl::IDNS_Ordinary) IDNS |= Decl::IDNS_OrdinaryFriend;
437 }
438
John McCalla24dc2e2009-11-17 02:14:36 +0000439 R.setIdentifierNamespace(IDNS);
440
441 DeclarationName Name = R.getLookupName();
442
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000443 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000444 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000445 I = IdResolver.begin(Name),
446 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000447
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000448 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000449 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000450 // ...During unqualified name lookup (3.4.1), the names appear as if
451 // they were declared in the nearest enclosing namespace which contains
452 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000453 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000454 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000455 //
456 // For example:
457 // namespace A { int i; }
458 // void foo() {
459 // int i;
460 // {
461 // using namespace A;
462 // ++i; // finds local 'i', A::i appears at global scope
463 // }
464 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000465 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000466 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000467 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000468 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000469 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000470 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
John McCallf36e02d2009-10-09 21:13:30 +0000471 Found = true;
472 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000473 }
474 }
John McCallf36e02d2009-10-09 21:13:30 +0000475 if (Found) {
476 R.resolveKind();
477 return true;
478 }
479
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000480 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregore942bbe2009-09-10 16:57:35 +0000481 DeclContext *OuterCtx = findOuterContext(S);
482 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
483 Ctx = Ctx->getLookupParent()) {
Douglas Gregor12372592009-12-08 15:38:36 +0000484 // We do not directly look into function or method contexts
485 // (since all local variables are found via the identifier
486 // changes) or in transparent contexts (since those entities
487 // will be found in the nearest enclosing non-transparent
488 // context).
489 if (Ctx->isFunctionOrMethod() || Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000490 continue;
491
492 // Perform qualified name lookup into this context.
493 // FIXME: In some cases, we know that every name that could be found by
494 // this qualified name lookup will also be on the identifier chain. For
495 // example, inside a class without any base classes, we never need to
496 // perform qualified lookup because all of the members are on top of the
497 // identifier chain.
John McCalla24dc2e2009-11-17 02:14:36 +0000498 if (LookupQualifiedName(R, Ctx))
John McCallf36e02d2009-10-09 21:13:30 +0000499 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000500 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000501 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000502 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000503
John McCalld7be78a2009-11-10 07:01:13 +0000504 // Stop if we ran out of scopes.
505 // FIXME: This really, really shouldn't be happening.
506 if (!S) return false;
507
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000508 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000509 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000510 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000511 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
512 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000513
John McCalld7be78a2009-11-10 07:01:13 +0000514 UnqualUsingDirectiveSet UDirs;
515 UDirs.visitScopeChain(Initial, S);
516 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000517
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000518 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000519 // Unqualified name lookup in C++ requires looking into scopes
520 // that aren't strictly lexical, and therefore we walk through the
521 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000522
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000523 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000524 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregora24eb4e2009-08-24 18:55:03 +0000525 if (Ctx->isTransparentContext())
526 continue;
527
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000528 assert(Ctx && Ctx->isFileContext() &&
529 "We should have been looking only at file context here already.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000530
531 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000532 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000533 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000534 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
535 // We found something. Look for anything else in our scope
536 // with this same name and in an acceptable identifier
537 // namespace, so that we can construct an overload set if we
538 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000539 Found = true;
540 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000541 }
542 }
543
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000544 // Look into context considering using-directives.
John McCalla24dc2e2009-11-17 02:14:36 +0000545 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
John McCallf36e02d2009-10-09 21:13:30 +0000546 Found = true;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000547
John McCallf36e02d2009-10-09 21:13:30 +0000548 if (Found) {
549 R.resolveKind();
550 return true;
551 }
552
John McCalla24dc2e2009-11-17 02:14:36 +0000553 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000554 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000555 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000556
John McCallf36e02d2009-10-09 21:13:30 +0000557 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000558}
559
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000560/// @brief Perform unqualified name lookup starting from a given
561/// scope.
562///
563/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
564/// used to find names within the current scope. For example, 'x' in
565/// @code
566/// int x;
567/// int f() {
568/// return x; // unqualified name look finds 'x' in the global scope
569/// }
570/// @endcode
571///
572/// Different lookup criteria can find different names. For example, a
573/// particular scope can have both a struct and a function of the same
574/// name, and each can be found by certain lookup criteria. For more
575/// information about lookup criteria, see the documentation for the
576/// class LookupCriteria.
577///
578/// @param S The scope from which unqualified name lookup will
579/// begin. If the lookup criteria permits, name lookup may also search
580/// in the parent scopes.
581///
582/// @param Name The name of the entity that we are searching for.
583///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000584/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +0000585/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +0000586/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000587///
588/// @returns The result of name lookup, which includes zero or more
589/// declarations and possibly additional information used to diagnose
590/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000591bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
592 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +0000593 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000594
John McCalla24dc2e2009-11-17 02:14:36 +0000595 LookupNameKind NameKind = R.getLookupKind();
596
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000597 if (!getLangOptions().CPlusPlus) {
598 // Unqualified name lookup in C/Objective-C is purely lexical, so
599 // search in the declarations attached to the name.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000600 unsigned IDNS = 0;
601 switch (NameKind) {
602 case Sema::LookupOrdinaryName:
603 IDNS = Decl::IDNS_Ordinary;
604 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000605
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000606 case Sema::LookupTagName:
607 IDNS = Decl::IDNS_Tag;
608 break;
609
610 case Sema::LookupMemberName:
611 IDNS = Decl::IDNS_Member;
612 break;
613
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000614 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000615 case Sema::LookupNestedNameSpecifierName:
616 case Sema::LookupNamespaceName:
John McCall9f54ad42009-12-10 09:41:52 +0000617 case Sema::LookupUsingDeclName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000618 assert(false && "C does not perform these kinds of name lookup");
619 break;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000620
621 case Sema::LookupRedeclarationWithLinkage:
622 // Find the nearest non-transparent declaration scope.
623 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000624 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000625 static_cast<DeclContext *>(S->getEntity())
626 ->isTransparentContext()))
627 S = S->getParent();
628 IDNS = Decl::IDNS_Ordinary;
629 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000630
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000631 case Sema::LookupObjCProtocolName:
632 IDNS = Decl::IDNS_ObjCProtocol;
633 break;
634
635 case Sema::LookupObjCImplementationName:
636 IDNS = Decl::IDNS_ObjCImplementation;
637 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000639 }
640
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000641 // Scan up the scope chain looking for a decl that matches this
642 // identifier that is in the appropriate namespace. This search
643 // should not take long, as shadowing of names is uncommon, and
644 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000645 bool LeftStartingScope = false;
646
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000647 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +0000648 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000649 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000650 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000651 if (NameKind == LookupRedeclarationWithLinkage) {
652 // Determine whether this (or a previous) declaration is
653 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000654 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000655 LeftStartingScope = true;
656
657 // If we found something outside of our starting scope that
658 // does not have linkage, skip it.
659 if (LeftStartingScope && !((*I)->hasLinkage()))
660 continue;
661 }
662
John McCallf36e02d2009-10-09 21:13:30 +0000663 R.addDecl(*I);
664
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000665 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000666 // If this declaration has the "overloadable" attribute, we
667 // might have a set of overloaded functions.
668
669 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000670 while (!(S->getFlags() & Scope::DeclScope) ||
671 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000672 S = S->getParent();
673
674 // Find the last declaration in this scope (with the same
675 // name, naturally).
676 IdentifierResolver::iterator LastI = I;
677 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000678 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000679 break;
John McCallf36e02d2009-10-09 21:13:30 +0000680 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000681 }
Douglas Gregorf9201e02009-02-11 23:02:49 +0000682 }
683
John McCallf36e02d2009-10-09 21:13:30 +0000684 R.resolveKind();
685
686 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000687 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000688 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000689 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000690 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +0000691 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000692 }
693
694 // If we didn't find a use of this identifier, and if the identifier
695 // corresponds to a compiler builtin, create the decl object for the builtin
696 // now, injecting it into translation unit scope, and return it.
Mike Stump1eb44332009-09-09 15:08:12 +0000697 if (NameKind == LookupOrdinaryName ||
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000698 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000699 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000700 if (II && AllowBuiltinCreation) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000701 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor3e41d602009-02-13 23:20:09 +0000702 if (unsigned BuiltinID = II->getBuiltinID()) {
703 // In C++, we don't have any predefined library functions like
704 // 'malloc'. Instead, we'll just error.
Mike Stump1eb44332009-09-09 15:08:12 +0000705 if (getLangOptions().CPlusPlus &&
Douglas Gregor3e41d602009-02-13 23:20:09 +0000706 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCallf36e02d2009-10-09 21:13:30 +0000707 return false;
Douglas Gregor3e41d602009-02-13 23:20:09 +0000708
John McCallf36e02d2009-10-09 21:13:30 +0000709 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCalla24dc2e2009-11-17 02:14:36 +0000710 S, R.isForRedeclaration(),
711 R.getNameLoc());
John McCallf36e02d2009-10-09 21:13:30 +0000712 if (D) R.addDecl(D);
713 return (D != NULL);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000714 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000715 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000716 }
John McCallf36e02d2009-10-09 21:13:30 +0000717 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000718}
719
John McCall6e247262009-10-10 05:48:19 +0000720/// @brief Perform qualified name lookup in the namespaces nominated by
721/// using directives by the given context.
722///
723/// C++98 [namespace.qual]p2:
724/// Given X::m (where X is a user-declared namespace), or given ::m
725/// (where X is the global namespace), let S be the set of all
726/// declarations of m in X and in the transitive closure of all
727/// namespaces nominated by using-directives in X and its used
728/// namespaces, except that using-directives are ignored in any
729/// namespace, including X, directly containing one or more
730/// declarations of m. No namespace is searched more than once in
731/// the lookup of a name. If S is the empty set, the program is
732/// ill-formed. Otherwise, if S has exactly one member, or if the
733/// context of the reference is a using-declaration
734/// (namespace.udecl), S is the required set of declarations of
735/// m. Otherwise if the use of m is not one that allows a unique
736/// declaration to be chosen from S, the program is ill-formed.
737/// C++98 [namespace.qual]p5:
738/// During the lookup of a qualified namespace member name, if the
739/// lookup finds more than one declaration of the member, and if one
740/// declaration introduces a class name or enumeration name and the
741/// other declarations either introduce the same object, the same
742/// enumerator or a set of functions, the non-type name hides the
743/// class or enumeration name if and only if the declarations are
744/// from the same namespace; otherwise (the declarations are from
745/// different namespaces), the program is ill-formed.
John McCall7d384dd2009-11-18 07:57:50 +0000746static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +0000747 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +0000748 assert(StartDC->isFileContext() && "start context is not a file context");
749
750 DeclContext::udir_iterator I = StartDC->using_directives_begin();
751 DeclContext::udir_iterator E = StartDC->using_directives_end();
752
753 if (I == E) return false;
754
755 // We have at least added all these contexts to the queue.
756 llvm::DenseSet<DeclContext*> Visited;
757 Visited.insert(StartDC);
758
759 // We have not yet looked into these namespaces, much less added
760 // their "using-children" to the queue.
761 llvm::SmallVector<NamespaceDecl*, 8> Queue;
762
763 // We have already looked into the initial namespace; seed the queue
764 // with its using-children.
765 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +0000766 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +0000767 if (Visited.insert(ND).second)
768 Queue.push_back(ND);
769 }
770
771 // The easiest way to implement the restriction in [namespace.qual]p5
772 // is to check whether any of the individual results found a tag
773 // and, if so, to declare an ambiguity if the final result is not
774 // a tag.
775 bool FoundTag = false;
776 bool FoundNonTag = false;
777
John McCall7d384dd2009-11-18 07:57:50 +0000778 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +0000779
780 bool Found = false;
781 while (!Queue.empty()) {
782 NamespaceDecl *ND = Queue.back();
783 Queue.pop_back();
784
785 // We go through some convolutions here to avoid copying results
786 // between LookupResults.
787 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +0000788 LookupResult &DirectR = UseLocal ? LocalR : R;
John McCalla24dc2e2009-11-17 02:14:36 +0000789 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +0000790
791 if (FoundDirect) {
792 // First do any local hiding.
793 DirectR.resolveKind();
794
795 // If the local result is a tag, remember that.
796 if (DirectR.isSingleTagDecl())
797 FoundTag = true;
798 else
799 FoundNonTag = true;
800
801 // Append the local results to the total results if necessary.
802 if (UseLocal) {
803 R.addAllDecls(LocalR);
804 LocalR.clear();
805 }
806 }
807
808 // If we find names in this namespace, ignore its using directives.
809 if (FoundDirect) {
810 Found = true;
811 continue;
812 }
813
814 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
815 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
816 if (Visited.insert(Nom).second)
817 Queue.push_back(Nom);
818 }
819 }
820
821 if (Found) {
822 if (FoundTag && FoundNonTag)
823 R.setAmbiguousQualifiedTagHiding();
824 else
825 R.resolveKind();
826 }
827
828 return Found;
829}
830
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000831/// @brief Perform qualified name lookup into a given context.
832///
833/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
834/// names when the context of those names is explicit specified, e.g.,
835/// "std::vector" or "x->member".
836///
837/// Different lookup criteria can find different names. For example, a
838/// particular scope can have both a struct and a function of the same
839/// name, and each can be found by certain lookup criteria. For more
840/// information about lookup criteria, see the documentation for the
841/// class LookupCriteria.
842///
843/// @param LookupCtx The context in which qualified name lookup will
844/// search. If the lookup criteria permits, name lookup may also search
845/// in the parent contexts or (for C++ classes) base classes.
846///
847/// @param Name The name of the entity that we are searching for.
848///
849/// @param Criteria The criteria that this routine will use to
850/// determine which names are visible and which names will be
851/// found. Note that name lookup will find a name that is visible by
852/// the given criteria, but the entity itself may not be semantically
853/// correct or even the kind of entity expected based on the
854/// lookup. For example, searching for a nested-name-specifier name
855/// might result in an EnumDecl, which is visible but is not permitted
856/// as a nested-name-specifier in C++03.
857///
858/// @returns The result of name lookup, which includes zero or more
859/// declarations and possibly additional information used to diagnose
860/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000861bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000862 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +0000863
John McCalla24dc2e2009-11-17 02:14:36 +0000864 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +0000865 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000867 // If we're performing qualified name lookup (e.g., lookup into a
868 // struct), find fields as part of ordinary name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000869 LookupNameKind NameKind = R.getLookupKind();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000870 unsigned IDNS
Mike Stump1eb44332009-09-09 15:08:12 +0000871 = getIdentifierNamespacesFromLookupNameKind(NameKind,
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000872 getLangOptions().CPlusPlus);
873 if (NameKind == LookupOrdinaryName)
874 IDNS |= Decl::IDNS_Member;
Mike Stump1eb44332009-09-09 15:08:12 +0000875
John McCalla24dc2e2009-11-17 02:14:36 +0000876 R.setIdentifierNamespace(IDNS);
877
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000878 // Make sure that the declaration context is complete.
879 assert((!isa<TagDecl>(LookupCtx) ||
880 LookupCtx->isDependentContext() ||
881 cast<TagDecl>(LookupCtx)->isDefinition() ||
882 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
883 ->isBeingDefined()) &&
884 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000886 // Perform qualified name lookup into the LookupCtx.
John McCalla24dc2e2009-11-17 02:14:36 +0000887 if (LookupDirect(R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +0000888 R.resolveKind();
889 return true;
890 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000891
John McCall6e247262009-10-10 05:48:19 +0000892 // Don't descend into implied contexts for redeclarations.
893 // C++98 [namespace.qual]p6:
894 // In a declaration for a namespace member in which the
895 // declarator-id is a qualified-id, given that the qualified-id
896 // for the namespace member has the form
897 // nested-name-specifier unqualified-id
898 // the unqualified-id shall name a member of the namespace
899 // designated by the nested-name-specifier.
900 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +0000901 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +0000902 return false;
903
John McCalla24dc2e2009-11-17 02:14:36 +0000904 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +0000905 if (LookupCtx->isFileContext())
John McCalla24dc2e2009-11-17 02:14:36 +0000906 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +0000907
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000908 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +0000909 // classes, we're done.
John McCall6e247262009-10-10 05:48:19 +0000910 if (!isa<CXXRecordDecl>(LookupCtx))
John McCallf36e02d2009-10-09 21:13:30 +0000911 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000912
913 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +0000914 CXXRecordDecl *LookupRec = cast<CXXRecordDecl>(LookupCtx);
915 CXXBasePaths Paths;
916 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000917
918 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +0000919 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000920 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000921 case LookupOrdinaryName:
922 case LookupMemberName:
923 case LookupRedeclarationWithLinkage:
924 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
925 break;
926
927 case LookupTagName:
928 BaseCallback = &CXXRecordDecl::FindTagMember;
929 break;
John McCall9f54ad42009-12-10 09:41:52 +0000930
931 case LookupUsingDeclName:
932 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +0000933
934 case LookupOperatorName:
935 case LookupNamespaceName:
936 case LookupObjCProtocolName:
937 case LookupObjCImplementationName:
Douglas Gregora8f32e02009-10-06 17:59:45 +0000938 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +0000939 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000940
941 case LookupNestedNameSpecifierName:
942 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
943 break;
944 }
945
John McCalla24dc2e2009-11-17 02:14:36 +0000946 if (!LookupRec->lookupInBases(BaseCallback,
947 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +0000948 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000949
950 // C++ [class.member.lookup]p2:
951 // [...] If the resulting set of declarations are not all from
952 // sub-objects of the same type, or the set has a nonstatic member
953 // and includes members from distinct sub-objects, there is an
954 // ambiguity and the program is ill-formed. Otherwise that set is
955 // the result of the lookup.
956 // FIXME: support using declarations!
957 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +0000958 int SubobjectNumber = 0;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000959 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000960 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000961 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000962
963 // Determine whether we're looking at a distinct sub-object or not.
964 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +0000965 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000966 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
967 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +0000968 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +0000969 != Context.getCanonicalType(PathElement.Base->getType())) {
970 // We found members of the given name in two subobjects of
971 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +0000972 R.setAmbiguousBaseSubobjectTypes(Paths);
973 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000974 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
975 // We have a different subobject of the same type.
976
977 // C++ [class.member.lookup]p5:
978 // A static member, a nested type or an enumerator defined in
979 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +0000980 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000981 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000982 if (isa<VarDecl>(FirstDecl) ||
983 isa<TypeDecl>(FirstDecl) ||
984 isa<EnumConstantDecl>(FirstDecl))
985 continue;
986
987 if (isa<CXXMethodDecl>(FirstDecl)) {
988 // Determine whether all of the methods are static.
989 bool AllMethodsAreStatic = true;
990 for (DeclContext::lookup_iterator Func = Path->Decls.first;
991 Func != Path->Decls.second; ++Func) {
992 if (!isa<CXXMethodDecl>(*Func)) {
993 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
994 break;
995 }
996
997 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
998 AllMethodsAreStatic = false;
999 break;
1000 }
1001 }
1002
1003 if (AllMethodsAreStatic)
1004 continue;
1005 }
1006
1007 // We have found a nonstatic member name in multiple, distinct
1008 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001009 R.setAmbiguousBaseSubobjects(Paths);
1010 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001011 }
1012 }
1013
1014 // Lookup in a base class succeeded; return these results.
1015
John McCallf36e02d2009-10-09 21:13:30 +00001016 DeclContext::lookup_iterator I, E;
1017 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I)
1018 R.addDecl(*I);
1019 R.resolveKind();
1020 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001021}
1022
1023/// @brief Performs name lookup for a name that was parsed in the
1024/// source code, and may contain a C++ scope specifier.
1025///
1026/// This routine is a convenience routine meant to be called from
1027/// contexts that receive a name and an optional C++ scope specifier
1028/// (e.g., "N::M::x"). It will then perform either qualified or
1029/// unqualified name lookup (with LookupQualifiedName or LookupName,
1030/// respectively) on the given name and return those results.
1031///
1032/// @param S The scope from which unqualified name lookup will
1033/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001034///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001035/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001036///
1037/// @param Name The name of the entity that name lookup will
1038/// search for.
1039///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001040/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001041/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001042/// C library functions (like "malloc") are implicitly declared.
1043///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001044/// @param EnteringContext Indicates whether we are going to enter the
1045/// context of the scope-specifier SS (if present).
1046///
John McCallf36e02d2009-10-09 21:13:30 +00001047/// @returns True if any decls were found (but possibly ambiguous)
1048bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001049 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001050 if (SS && SS->isInvalid()) {
1051 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001052 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001053 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001054 }
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Douglas Gregor495c35d2009-08-25 22:51:20 +00001056 if (SS && SS->isSet()) {
1057 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001058 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001059 // contex, and will perform name lookup in that context.
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001060 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCallf36e02d2009-10-09 21:13:30 +00001061 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001062
John McCalla24dc2e2009-11-17 02:14:36 +00001063 R.setContextRange(SS->getRange());
1064
1065 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001066 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001067
Douglas Gregor495c35d2009-08-25 22:51:20 +00001068 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001069 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001070 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001071 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001072 }
1073
Mike Stump1eb44332009-09-09 15:08:12 +00001074 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001075 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001076}
1077
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001078
Douglas Gregor7176fff2009-01-15 00:26:24 +00001079/// @brief Produce a diagnostic describing the ambiguity that resulted
1080/// from name lookup.
1081///
1082/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001083///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001084/// @param Name The name of the entity that name lookup was
1085/// searching for.
1086///
1087/// @param NameLoc The location of the name within the source code.
1088///
1089/// @param LookupRange A source range that provides more
1090/// source-location information concerning the lookup itself. For
1091/// example, this range might highlight a nested-name-specifier that
1092/// precedes the name.
1093///
1094/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001095bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001096 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1097
John McCalla24dc2e2009-11-17 02:14:36 +00001098 DeclarationName Name = Result.getLookupName();
1099 SourceLocation NameLoc = Result.getNameLoc();
1100 SourceRange LookupRange = Result.getContextRange();
1101
John McCall6e247262009-10-10 05:48:19 +00001102 switch (Result.getAmbiguityKind()) {
1103 case LookupResult::AmbiguousBaseSubobjects: {
1104 CXXBasePaths *Paths = Result.getBasePaths();
1105 QualType SubobjectType = Paths->front().back().Base->getType();
1106 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1107 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1108 << LookupRange;
1109
1110 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1111 while (isa<CXXMethodDecl>(*Found) &&
1112 cast<CXXMethodDecl>(*Found)->isStatic())
1113 ++Found;
1114
1115 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1116
1117 return true;
1118 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001119
John McCall6e247262009-10-10 05:48:19 +00001120 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001121 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1122 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001123
1124 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001125 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001126 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1127 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001128 Path != PathEnd; ++Path) {
1129 Decl *D = *Path->Decls.first;
1130 if (DeclsPrinted.insert(D).second)
1131 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1132 }
1133
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001134 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001135 }
1136
John McCall6e247262009-10-10 05:48:19 +00001137 case LookupResult::AmbiguousTagHiding: {
1138 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001139
John McCall6e247262009-10-10 05:48:19 +00001140 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1141
1142 LookupResult::iterator DI, DE = Result.end();
1143 for (DI = Result.begin(); DI != DE; ++DI)
1144 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1145 TagDecls.insert(TD);
1146 Diag(TD->getLocation(), diag::note_hidden_tag);
1147 }
1148
1149 for (DI = Result.begin(); DI != DE; ++DI)
1150 if (!isa<TagDecl>(*DI))
1151 Diag((*DI)->getLocation(), diag::note_hiding_object);
1152
1153 // For recovery purposes, go ahead and implement the hiding.
1154 Result.hideDecls(TagDecls);
1155
1156 return true;
1157 }
1158
1159 case LookupResult::AmbiguousReference: {
1160 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001161
John McCall6e247262009-10-10 05:48:19 +00001162 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1163 for (; DI != DE; ++DI)
1164 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001165
John McCall6e247262009-10-10 05:48:19 +00001166 return true;
1167 }
1168 }
1169
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001170 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001171 return true;
1172}
Douglas Gregorfa047642009-02-04 00:32:51 +00001173
Mike Stump1eb44332009-09-09 15:08:12 +00001174static void
1175addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001176 ASTContext &Context,
1177 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001178 Sema::AssociatedClassSet &AssociatedClasses);
1179
1180static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1181 DeclContext *Ctx) {
1182 if (Ctx->isFileContext())
1183 Namespaces.insert(Ctx);
1184}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001185
Mike Stump1eb44332009-09-09 15:08:12 +00001186// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001187// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001188static void
1189addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
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) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001193 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001194 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001195 switch (Arg.getKind()) {
1196 case TemplateArgument::Null:
1197 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Douglas Gregor69be8d62009-07-08 07:51:57 +00001199 case TemplateArgument::Type:
1200 // [...] the namespaces and classes associated with the types of the
1201 // template arguments provided for template type parameters (excluding
1202 // template template parameters)
1203 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1204 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001205 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001206 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Douglas Gregor788cd062009-11-11 01:00:40 +00001208 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001209 // [...] the namespaces in which any template template arguments are
1210 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001211 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001212 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001213 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001214 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001215 DeclContext *Ctx = ClassTemplate->getDeclContext();
1216 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1217 AssociatedClasses.insert(EnclosingClass);
1218 // Add the associated namespace for this class.
1219 while (Ctx->isRecord())
1220 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001221 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001222 }
1223 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001224 }
1225
1226 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001227 case TemplateArgument::Integral:
1228 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001229 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001230 // associated namespaces. ]
1231 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Douglas Gregor69be8d62009-07-08 07:51:57 +00001233 case TemplateArgument::Pack:
1234 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1235 PEnd = Arg.pack_end();
1236 P != PEnd; ++P)
1237 addAssociatedClassesAndNamespaces(*P, Context,
1238 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001239 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001240 break;
1241 }
1242}
1243
Douglas Gregorfa047642009-02-04 00:32:51 +00001244// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001245// argument-dependent lookup with an argument of class type
1246// (C++ [basic.lookup.koenig]p2).
1247static void
1248addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregorfa047642009-02-04 00:32:51 +00001249 ASTContext &Context,
1250 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001251 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001252 // C++ [basic.lookup.koenig]p2:
1253 // [...]
1254 // -- If T is a class type (including unions), its associated
1255 // classes are: the class itself; the class of which it is a
1256 // member, if any; and its direct and indirect base
1257 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001258 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001259
1260 // Add the class of which it is a member, if any.
1261 DeclContext *Ctx = Class->getDeclContext();
1262 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1263 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001264 // Add the associated namespace for this class.
1265 while (Ctx->isRecord())
1266 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001267 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Douglas Gregorfa047642009-02-04 00:32:51 +00001269 // Add the class itself. If we've already seen this class, we don't
1270 // need to visit base classes.
1271 if (!AssociatedClasses.insert(Class))
1272 return;
1273
Mike Stump1eb44332009-09-09 15:08:12 +00001274 // -- If T is a template-id, its associated namespaces and classes are
1275 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001276 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001277 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001278 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001279 // namespaces in which any template template arguments are defined; and
1280 // the classes in which any member templates used as template template
1281 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001282 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001283 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001284 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1285 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1286 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1287 AssociatedClasses.insert(EnclosingClass);
1288 // Add the associated namespace for this class.
1289 while (Ctx->isRecord())
1290 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001291 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001292
Douglas Gregor69be8d62009-07-08 07:51:57 +00001293 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1294 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1295 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1296 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001297 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001298 }
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Douglas Gregorfa047642009-02-04 00:32:51 +00001300 // Add direct and indirect base classes along with their associated
1301 // namespaces.
1302 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1303 Bases.push_back(Class);
1304 while (!Bases.empty()) {
1305 // Pop this class off the stack.
1306 Class = Bases.back();
1307 Bases.pop_back();
1308
1309 // Visit the base classes.
1310 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1311 BaseEnd = Class->bases_end();
1312 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001313 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001314 // In dependent contexts, we do ADL twice, and the first time around,
1315 // the base type might be a dependent TemplateSpecializationType, or a
1316 // TemplateTypeParmType. If that happens, simply ignore it.
1317 // FIXME: If we want to support export, we probably need to add the
1318 // namespace of the template in a TemplateSpecializationType, or even
1319 // the classes and namespaces of known non-dependent arguments.
1320 if (!BaseType)
1321 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001322 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1323 if (AssociatedClasses.insert(BaseDecl)) {
1324 // Find the associated namespace for this base class.
1325 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1326 while (BaseCtx->isRecord())
1327 BaseCtx = BaseCtx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001328 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001329
1330 // Make sure we visit the bases of this base class.
1331 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1332 Bases.push_back(BaseDecl);
1333 }
1334 }
1335 }
1336}
1337
1338// \brief Add the associated classes and namespaces for
1339// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001340// (C++ [basic.lookup.koenig]p2).
1341static void
1342addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregorfa047642009-02-04 00:32:51 +00001343 ASTContext &Context,
1344 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001345 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001346 // C++ [basic.lookup.koenig]p2:
1347 //
1348 // For each argument type T in the function call, there is a set
1349 // of zero or more associated namespaces and a set of zero or more
1350 // associated classes to be considered. The sets of namespaces and
1351 // classes is determined entirely by the types of the function
1352 // arguments (and the namespace of any template template
1353 // argument). Typedef names and using-declarations used to specify
1354 // the types do not contribute to this set. The sets of namespaces
1355 // and classes are determined in the following way:
1356 T = Context.getCanonicalType(T).getUnqualifiedType();
1357
1358 // -- If T is a pointer to U or an array of U, its associated
Mike Stump1eb44332009-09-09 15:08:12 +00001359 // namespaces and classes are those associated with U.
Douglas Gregorfa047642009-02-04 00:32:51 +00001360 //
1361 // We handle this by unwrapping pointer and array types immediately,
1362 // to avoid unnecessary recursion.
1363 while (true) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001364 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001365 T = Ptr->getPointeeType();
1366 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1367 T = Ptr->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001368 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001369 break;
1370 }
1371
1372 // -- If T is a fundamental type, its associated sets of
1373 // namespaces and classes are both empty.
John McCall183700f2009-09-21 23:43:11 +00001374 if (T->getAs<BuiltinType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001375 return;
1376
1377 // -- If T is a class type (including unions), its associated
1378 // classes are: the class itself; the class of which it is a
1379 // member, if any; and its direct and indirect base
1380 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001381 // which its associated classes are defined.
Ted Kremenek6217b802009-07-29 21:53:49 +00001382 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001383 if (CXXRecordDecl *ClassDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001384 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001385 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1386 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001387 AssociatedClasses);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001388 return;
1389 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001390
1391 // -- If T is an enumeration type, its associated namespace is
1392 // the namespace in which it is defined. If it is class
1393 // member, its associated class is the member’s class; else
Mike Stump1eb44332009-09-09 15:08:12 +00001394 // it has no associated class.
John McCall183700f2009-09-21 23:43:11 +00001395 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001396 EnumDecl *Enum = EnumT->getDecl();
1397
1398 DeclContext *Ctx = Enum->getDeclContext();
1399 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1400 AssociatedClasses.insert(EnclosingClass);
1401
1402 // Add the associated namespace for this class.
1403 while (Ctx->isRecord())
1404 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001405 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001406
1407 return;
1408 }
1409
1410 // -- If T is a function type, its associated namespaces and
1411 // classes are those associated with the function parameter
1412 // types and those associated with the return type.
John McCall183700f2009-09-21 23:43:11 +00001413 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001414 // Return type
John McCall183700f2009-09-21 23:43:11 +00001415 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001416 Context,
John McCall6ff07852009-08-07 22:18:02 +00001417 AssociatedNamespaces, AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001418
John McCall183700f2009-09-21 23:43:11 +00001419 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001420 if (!Proto)
1421 return;
1422
1423 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001424 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001425 ArgEnd = Proto->arg_type_end();
Douglas Gregorfa047642009-02-04 00:32:51 +00001426 Arg != ArgEnd; ++Arg)
1427 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCall6ff07852009-08-07 22:18:02 +00001428 AssociatedNamespaces, AssociatedClasses);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Douglas Gregorfa047642009-02-04 00:32:51 +00001430 return;
1431 }
1432
1433 // -- If T is a pointer to a member function of a class X, its
1434 // associated namespaces and classes are those associated
1435 // with the function parameter types and return type,
Mike Stump1eb44332009-09-09 15:08:12 +00001436 // together with those associated with X.
Douglas Gregorfa047642009-02-04 00:32:51 +00001437 //
1438 // -- If T is a pointer to a data member of class X, its
1439 // associated namespaces and classes are those associated
1440 // with the member type together with those associated with
Mike Stump1eb44332009-09-09 15:08:12 +00001441 // X.
Ted Kremenek6217b802009-07-29 21:53:49 +00001442 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001443 // Handle the type that the pointer to member points to.
1444 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1445 Context,
John McCall6ff07852009-08-07 22:18:02 +00001446 AssociatedNamespaces,
1447 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001448
1449 // Handle the class type into which this points.
Ted Kremenek6217b802009-07-29 21:53:49 +00001450 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001451 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1452 Context,
John McCall6ff07852009-08-07 22:18:02 +00001453 AssociatedNamespaces,
1454 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001455
1456 return;
1457 }
1458
1459 // FIXME: What about block pointers?
1460 // FIXME: What about Objective-C message sends?
1461}
1462
1463/// \brief Find the associated classes and namespaces for
1464/// argument-dependent lookup for a call with the given set of
1465/// arguments.
1466///
1467/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001468/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001469/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001470void
Douglas Gregorfa047642009-02-04 00:32:51 +00001471Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1472 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001473 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001474 AssociatedNamespaces.clear();
1475 AssociatedClasses.clear();
1476
1477 // C++ [basic.lookup.koenig]p2:
1478 // For each argument type T in the function call, there is a set
1479 // of zero or more associated namespaces and a set of zero or more
1480 // associated classes to be considered. The sets of namespaces and
1481 // classes is determined entirely by the types of the function
1482 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001483 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001484 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1485 Expr *Arg = Args[ArgIdx];
1486
1487 if (Arg->getType() != Context.OverloadTy) {
1488 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001489 AssociatedNamespaces,
1490 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001491 continue;
1492 }
1493
1494 // [...] In addition, if the argument is the name or address of a
1495 // set of overloaded functions and/or function templates, its
1496 // associated classes and namespaces are the union of those
1497 // associated with each of the members of the set: the namespace
1498 // in which the function or function template is defined and the
1499 // classes and namespaces associated with its (non-dependent)
1500 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001501 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001502 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1503 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1504 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001505
John McCallba135432009-11-21 08:51:07 +00001506 // TODO: avoid the copies. This should be easy when the cases
1507 // share a storage implementation.
1508 llvm::SmallVector<NamedDecl*, 8> Functions;
1509
1510 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1511 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00001512 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001513 continue;
1514
John McCallba135432009-11-21 08:51:07 +00001515 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1516 E = Functions.end(); I != E; ++I) {
1517 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I);
Douglas Gregore53060f2009-06-25 22:08:12 +00001518 if (!FDecl)
John McCallba135432009-11-21 08:51:07 +00001519 FDecl = cast<FunctionTemplateDecl>(*I)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001520
1521 // Add the namespace in which this function was defined. Note
1522 // that, if this is a member function, we do *not* consider the
1523 // enclosing namespace of its class.
1524 DeclContext *Ctx = FDecl->getDeclContext();
John McCall6ff07852009-08-07 22:18:02 +00001525 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001526
1527 // Add the classes and namespaces associated with the parameter
1528 // types and return type of this function.
1529 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001530 AssociatedNamespaces,
1531 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001532 }
1533 }
1534}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001535
1536/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1537/// an acceptable non-member overloaded operator for a call whose
1538/// arguments have types T1 (and, if non-empty, T2). This routine
1539/// implements the check in C++ [over.match.oper]p3b2 concerning
1540/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001541static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001542IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1543 QualType T1, QualType T2,
1544 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001545 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1546 return true;
1547
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001548 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1549 return true;
1550
John McCall183700f2009-09-21 23:43:11 +00001551 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001552 if (Proto->getNumArgs() < 1)
1553 return false;
1554
1555 if (T1->isEnumeralType()) {
1556 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001557 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001558 return true;
1559 }
1560
1561 if (Proto->getNumArgs() < 2)
1562 return false;
1563
1564 if (!T2.isNull() && T2->isEnumeralType()) {
1565 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001566 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001567 return true;
1568 }
1569
1570 return false;
1571}
1572
John McCall7d384dd2009-11-18 07:57:50 +00001573NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1574 LookupNameKind NameKind,
1575 RedeclarationKind Redecl) {
1576 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1577 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00001578 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00001579}
1580
Douglas Gregor6e378de2009-04-23 23:18:26 +00001581/// \brief Find the protocol with the given name, if any.
1582ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCallf36e02d2009-10-09 21:13:30 +00001583 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001584 return cast_or_null<ObjCProtocolDecl>(D);
1585}
1586
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001587void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001588 QualType T1, QualType T2,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001589 FunctionSet &Functions) {
1590 // C++ [over.match.oper]p3:
1591 // -- The set of non-member candidates is the result of the
1592 // unqualified lookup of operator@ in the context of the
1593 // expression according to the usual rules for name lookup in
1594 // unqualified function calls (3.4.2) except that all member
1595 // functions are ignored. However, if no operand has a class
1596 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00001597 // that have a first parameter of type T1 or "reference to
1598 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001599 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00001600 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001601 // when T2 is an enumeration type, are candidate functions.
1602 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00001603 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1604 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001606 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1607
John McCallf36e02d2009-10-09 21:13:30 +00001608 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001609 return;
1610
1611 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1612 Op != OpEnd; ++Op) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001613 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001614 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1615 Functions.insert(FD); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00001616 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor364e0212009-06-27 21:05:07 +00001617 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1618 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00001619 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00001620 // later?
1621 if (!FunTmpl->getDeclContext()->isRecord())
1622 Functions.insert(FunTmpl);
1623 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001624 }
1625}
1626
John McCall6ff07852009-08-07 22:18:02 +00001627static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1628 Decl *D) {
1629 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1630 Functions.insert(Func);
1631 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1632 Functions.insert(FunTmpl);
1633}
1634
Sebastian Redl644be852009-10-23 19:23:15 +00001635void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001636 Expr **Args, unsigned NumArgs,
1637 FunctionSet &Functions) {
1638 // Find all of the associated namespaces and classes based on the
1639 // arguments we have.
1640 AssociatedNamespaceSet AssociatedNamespaces;
1641 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00001642 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00001643 AssociatedNamespaces,
1644 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001645
Sebastian Redl644be852009-10-23 19:23:15 +00001646 QualType T1, T2;
1647 if (Operator) {
1648 T1 = Args[0]->getType();
1649 if (NumArgs >= 2)
1650 T2 = Args[1]->getType();
1651 }
1652
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001653 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001654 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1655 // and let Y be the lookup set produced by argument dependent
1656 // lookup (defined as follows). If X contains [...] then Y is
1657 // empty. Otherwise Y is the set of declarations found in the
1658 // namespaces associated with the argument types as described
1659 // below. The set of declarations found by the lookup of the name
1660 // is the union of X and Y.
1661 //
1662 // Here, we compute Y and add its members to the overloaded
1663 // candidate set.
1664 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001665 NSEnd = AssociatedNamespaces.end();
1666 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001667 // When considering an associated namespace, the lookup is the
1668 // same as the lookup performed when the associated namespace is
1669 // used as a qualifier (3.4.3.2) except that:
1670 //
1671 // -- Any using-directives in the associated namespace are
1672 // ignored.
1673 //
John McCall6ff07852009-08-07 22:18:02 +00001674 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001675 // associated classes are visible within their respective
1676 // namespaces even if they are not visible during an ordinary
1677 // lookup (11.4).
1678 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00001679 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6ff07852009-08-07 22:18:02 +00001680 Decl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00001681 // If the only declaration here is an ordinary friend, consider
1682 // it only if it was declared in an associated classes.
1683 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00001684 DeclContext *LexDC = D->getLexicalDeclContext();
1685 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1686 continue;
1687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Sebastian Redl644be852009-10-23 19:23:15 +00001689 FunctionDecl *Fn;
1690 if (!Operator || !(Fn = dyn_cast<FunctionDecl>(D)) ||
1691 IsAcceptableNonMemberOperatorCandidate(Fn, T1, T2, Context))
1692 CollectFunctionDecl(Functions, D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001693 }
1694 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001695}