blob: 48d7320d2e96fdd0dd800c32d203d466caae5d76 [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
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000225 case Sema::LookupObjCProtocolName:
226 IDNS = Decl::IDNS_ObjCProtocol;
227 break;
228
229 case Sema::LookupObjCImplementationName:
230 IDNS = Decl::IDNS_ObjCImplementation;
231 break;
232
233 case Sema::LookupObjCCategoryImplName:
234 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000235 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000236 }
237 return IDNS;
238}
239
John McCallf36e02d2009-10-09 21:13:30 +0000240// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000241void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000242 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000243}
244
John McCall7453ed42009-11-22 00:44:51 +0000245/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000246void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000247 unsigned N = Decls.size();
Douglas Gregor69d993a2009-01-17 01:13:24 +0000248
John McCallf36e02d2009-10-09 21:13:30 +0000249 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000250 if (N == 0) {
251 assert(ResultKind == NotFound);
252 return;
253 }
254
John McCall7453ed42009-11-22 00:44:51 +0000255 // If there's a single decl, we need to examine it to decide what
256 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000257 if (N == 1) {
John McCall7453ed42009-11-22 00:44:51 +0000258 if (isa<FunctionTemplateDecl>(Decls[0]))
259 ResultKind = FoundOverloaded;
260 else if (isa<UnresolvedUsingValueDecl>(Decls[0]))
John McCall7ba107a2009-11-18 02:36:19 +0000261 ResultKind = FoundUnresolvedValue;
262 return;
263 }
John McCallf36e02d2009-10-09 21:13:30 +0000264
John McCall6e247262009-10-10 05:48:19 +0000265 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000266 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000267
John McCallf36e02d2009-10-09 21:13:30 +0000268 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
269
270 bool Ambiguous = false;
271 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000272 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000273
274 unsigned UniqueTagIndex = 0;
275
276 unsigned I = 0;
277 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000278 NamedDecl *D = Decls[I]->getUnderlyingDecl();
279 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000280
John McCall314be4e2009-11-17 07:50:12 +0000281 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000282 // If it's not unique, pull something off the back (and
283 // continue at this index).
284 Decls[I] = Decls[--N];
John McCallf36e02d2009-10-09 21:13:30 +0000285 } else {
286 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000287
288 if (isa<UnresolvedUsingValueDecl>(D)) {
289 HasUnresolved = true;
290 } else if (isa<TagDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000291 if (HasTag)
292 Ambiguous = true;
293 UniqueTagIndex = I;
294 HasTag = true;
John McCall7453ed42009-11-22 00:44:51 +0000295 } else if (isa<FunctionTemplateDecl>(D)) {
296 HasFunction = true;
297 HasFunctionTemplate = true;
298 } else if (isa<FunctionDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000299 HasFunction = true;
300 } else {
301 if (HasNonFunction)
302 Ambiguous = true;
303 HasNonFunction = true;
304 }
305 I++;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000306 }
Mike Stump1eb44332009-09-09 15:08:12 +0000307 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000308
John McCallf36e02d2009-10-09 21:13:30 +0000309 // C++ [basic.scope.hiding]p2:
310 // A class name or enumeration name can be hidden by the name of
311 // an object, function, or enumerator declared in the same
312 // scope. If a class or enumeration name and an object, function,
313 // or enumerator are declared in the same scope (in any order)
314 // with the same name, the class or enumeration name is hidden
315 // wherever the object, function, or enumerator name is visible.
316 // But it's still an error if there are distinct tag types found,
317 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000318 if (HideTags && HasTag && !Ambiguous &&
319 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000320 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000321
John McCallf36e02d2009-10-09 21:13:30 +0000322 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000323
John McCallfda8e122009-12-03 00:58:24 +0000324 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000325 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000326
John McCallf36e02d2009-10-09 21:13:30 +0000327 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000328 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000329 else if (HasUnresolved)
330 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000331 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000332 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000333 else
John McCalla24dc2e2009-11-17 02:14:36 +0000334 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000335}
336
John McCall7d384dd2009-11-18 07:57:50 +0000337void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000338 CXXBasePaths::paths_iterator I, E;
339 DeclContext::lookup_iterator DI, DE;
340 for (I = P.begin(), E = P.end(); I != E; ++I)
341 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
342 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000343}
344
John McCall7d384dd2009-11-18 07:57:50 +0000345void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000346 Paths = new CXXBasePaths;
347 Paths->swap(P);
348 addDeclsFromBasePaths(*Paths);
349 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000350 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000351}
352
John McCall7d384dd2009-11-18 07:57:50 +0000353void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000354 Paths = new CXXBasePaths;
355 Paths->swap(P);
356 addDeclsFromBasePaths(*Paths);
357 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000358 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000359}
360
John McCall7d384dd2009-11-18 07:57:50 +0000361void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000362 Out << Decls.size() << " result(s)";
363 if (isAmbiguous()) Out << ", ambiguous";
364 if (Paths) Out << ", base paths present";
365
366 for (iterator I = begin(), E = end(); I != E; ++I) {
367 Out << "\n";
368 (*I)->print(Out, 2);
369 }
370}
371
372// Adds all qualifying matches for a name within a decl context to the
373// given lookup result. Returns true if any matches were found.
John McCall7d384dd2009-11-18 07:57:50 +0000374static bool LookupDirect(LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000375 bool Found = false;
376
John McCalld7be78a2009-11-10 07:01:13 +0000377 DeclContext::lookup_const_iterator I, E;
John McCalla24dc2e2009-11-17 02:14:36 +0000378 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I)
379 if (Sema::isAcceptableLookupResult(*I, R.getLookupKind(),
380 R.getIdentifierNamespace()))
John McCallf36e02d2009-10-09 21:13:30 +0000381 R.addDecl(*I), Found = true;
382
383 return Found;
384}
385
John McCalld7be78a2009-11-10 07:01:13 +0000386// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000387static bool
John McCall7d384dd2009-11-18 07:57:50 +0000388CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCalla24dc2e2009-11-17 02:14:36 +0000389 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000390
391 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
392
John McCalld7be78a2009-11-10 07:01:13 +0000393 // Perform direct name lookup into the LookupCtx.
John McCalla24dc2e2009-11-17 02:14:36 +0000394 bool Found = LookupDirect(R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000395
John McCalld7be78a2009-11-10 07:01:13 +0000396 // Perform direct name lookup into the namespaces nominated by the
397 // using directives whose common ancestor is this namespace.
398 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
399 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
John McCalld7be78a2009-11-10 07:01:13 +0000401 for (; UI != UEnd; ++UI)
John McCalla24dc2e2009-11-17 02:14:36 +0000402 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000403 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000404
405 R.resolveKind();
406
407 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000408}
409
410static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000411 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000412 return Ctx->isFileContext();
413 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000414}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000415
Douglas Gregore942bbe2009-09-10 16:57:35 +0000416// Find the next outer declaration context corresponding to this scope.
417static DeclContext *findOuterContext(Scope *S) {
418 for (S = S->getParent(); S; S = S->getParent())
419 if (S->getEntity())
420 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
421
422 return 0;
423}
424
John McCalla24dc2e2009-11-17 02:14:36 +0000425bool Sema::CppLookupName(LookupResult &R, Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000426 assert(getLangOptions().CPlusPlus &&
427 "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000428 LookupNameKind NameKind = R.getLookupKind();
Mike Stump1eb44332009-09-09 15:08:12 +0000429 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000430 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
John McCall02cace72009-08-28 07:59:38 +0000431
432 // If we're testing for redeclarations, also look in the friend namespaces.
John McCalla24dc2e2009-11-17 02:14:36 +0000433 if (R.isForRedeclaration()) {
John McCall02cace72009-08-28 07:59:38 +0000434 if (IDNS & Decl::IDNS_Tag) IDNS |= Decl::IDNS_TagFriend;
435 if (IDNS & Decl::IDNS_Ordinary) IDNS |= Decl::IDNS_OrdinaryFriend;
436 }
437
John McCalla24dc2e2009-11-17 02:14:36 +0000438 R.setIdentifierNamespace(IDNS);
439
440 DeclarationName Name = R.getLookupName();
441
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000442 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000443 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000444 I = IdResolver.begin(Name),
445 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000446
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000447 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000448 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000449 // ...During unqualified name lookup (3.4.1), the names appear as if
450 // they were declared in the nearest enclosing namespace which contains
451 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000452 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000453 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000454 //
455 // For example:
456 // namespace A { int i; }
457 // void foo() {
458 // int i;
459 // {
460 // using namespace A;
461 // ++i; // finds local 'i', A::i appears at global scope
462 // }
463 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000464 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000465 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000466 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000467 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000468 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000469 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
John McCallf36e02d2009-10-09 21:13:30 +0000470 Found = true;
471 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000472 }
473 }
John McCallf36e02d2009-10-09 21:13:30 +0000474 if (Found) {
475 R.resolveKind();
476 return true;
477 }
478
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000479 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregore942bbe2009-09-10 16:57:35 +0000480 DeclContext *OuterCtx = findOuterContext(S);
481 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
482 Ctx = Ctx->getLookupParent()) {
Douglas Gregor12372592009-12-08 15:38:36 +0000483 // We do not directly look into function or method contexts
484 // (since all local variables are found via the identifier
485 // changes) or in transparent contexts (since those entities
486 // will be found in the nearest enclosing non-transparent
487 // context).
488 if (Ctx->isFunctionOrMethod() || Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000489 continue;
490
491 // Perform qualified name lookup into this context.
492 // FIXME: In some cases, we know that every name that could be found by
493 // this qualified name lookup will also be on the identifier chain. For
494 // example, inside a class without any base classes, we never need to
495 // perform qualified lookup because all of the members are on top of the
496 // identifier chain.
John McCalla24dc2e2009-11-17 02:14:36 +0000497 if (LookupQualifiedName(R, Ctx))
John McCallf36e02d2009-10-09 21:13:30 +0000498 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000499 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000500 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000501 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000502
John McCalld7be78a2009-11-10 07:01:13 +0000503 // Stop if we ran out of scopes.
504 // FIXME: This really, really shouldn't be happening.
505 if (!S) return false;
506
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000507 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000508 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000509 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000510 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
511 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000512
John McCalld7be78a2009-11-10 07:01:13 +0000513 UnqualUsingDirectiveSet UDirs;
514 UDirs.visitScopeChain(Initial, S);
515 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000516
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000517 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000518 // Unqualified name lookup in C++ requires looking into scopes
519 // that aren't strictly lexical, and therefore we walk through the
520 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000521
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000522 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000523 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregora24eb4e2009-08-24 18:55:03 +0000524 if (Ctx->isTransparentContext())
525 continue;
526
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000527 assert(Ctx && Ctx->isFileContext() &&
528 "We should have been looking only at file context here already.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000529
530 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000531 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000532 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000533 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
534 // We found something. Look for anything else in our scope
535 // with this same name and in an acceptable identifier
536 // namespace, so that we can construct an overload set if we
537 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000538 Found = true;
539 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000540 }
541 }
542
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000543 // Look into context considering using-directives.
John McCalla24dc2e2009-11-17 02:14:36 +0000544 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
John McCallf36e02d2009-10-09 21:13:30 +0000545 Found = true;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000546
John McCallf36e02d2009-10-09 21:13:30 +0000547 if (Found) {
548 R.resolveKind();
549 return true;
550 }
551
John McCalla24dc2e2009-11-17 02:14:36 +0000552 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000553 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000554 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000555
John McCallf36e02d2009-10-09 21:13:30 +0000556 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000557}
558
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000559/// @brief Perform unqualified name lookup starting from a given
560/// scope.
561///
562/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
563/// used to find names within the current scope. For example, 'x' in
564/// @code
565/// int x;
566/// int f() {
567/// return x; // unqualified name look finds 'x' in the global scope
568/// }
569/// @endcode
570///
571/// Different lookup criteria can find different names. For example, a
572/// particular scope can have both a struct and a function of the same
573/// name, and each can be found by certain lookup criteria. For more
574/// information about lookup criteria, see the documentation for the
575/// class LookupCriteria.
576///
577/// @param S The scope from which unqualified name lookup will
578/// begin. If the lookup criteria permits, name lookup may also search
579/// in the parent scopes.
580///
581/// @param Name The name of the entity that we are searching for.
582///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000583/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +0000584/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +0000585/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000586///
587/// @returns The result of name lookup, which includes zero or more
588/// declarations and possibly additional information used to diagnose
589/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000590bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
591 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +0000592 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000593
John McCalla24dc2e2009-11-17 02:14:36 +0000594 LookupNameKind NameKind = R.getLookupKind();
595
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000596 if (!getLangOptions().CPlusPlus) {
597 // Unqualified name lookup in C/Objective-C is purely lexical, so
598 // search in the declarations attached to the name.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000599 unsigned IDNS = 0;
600 switch (NameKind) {
601 case Sema::LookupOrdinaryName:
602 IDNS = Decl::IDNS_Ordinary;
603 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000604
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000605 case Sema::LookupTagName:
606 IDNS = Decl::IDNS_Tag;
607 break;
608
609 case Sema::LookupMemberName:
610 IDNS = Decl::IDNS_Member;
611 break;
612
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000613 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000614 case Sema::LookupNestedNameSpecifierName:
615 case Sema::LookupNamespaceName:
616 assert(false && "C does not perform these kinds of name lookup");
617 break;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000618
619 case Sema::LookupRedeclarationWithLinkage:
620 // Find the nearest non-transparent declaration scope.
621 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000622 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000623 static_cast<DeclContext *>(S->getEntity())
624 ->isTransparentContext()))
625 S = S->getParent();
626 IDNS = Decl::IDNS_Ordinary;
627 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000628
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000629 case Sema::LookupObjCProtocolName:
630 IDNS = Decl::IDNS_ObjCProtocol;
631 break;
632
633 case Sema::LookupObjCImplementationName:
634 IDNS = Decl::IDNS_ObjCImplementation;
635 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000637 case Sema::LookupObjCCategoryImplName:
638 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000639 break;
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000640 }
641
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000642 // Scan up the scope chain looking for a decl that matches this
643 // identifier that is in the appropriate namespace. This search
644 // should not take long, as shadowing of names is uncommon, and
645 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000646 bool LeftStartingScope = false;
647
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000648 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +0000649 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000650 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000651 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000652 if (NameKind == LookupRedeclarationWithLinkage) {
653 // Determine whether this (or a previous) declaration is
654 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000655 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000656 LeftStartingScope = true;
657
658 // If we found something outside of our starting scope that
659 // does not have linkage, skip it.
660 if (LeftStartingScope && !((*I)->hasLinkage()))
661 continue;
662 }
663
John McCallf36e02d2009-10-09 21:13:30 +0000664 R.addDecl(*I);
665
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000666 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000667 // If this declaration has the "overloadable" attribute, we
668 // might have a set of overloaded functions.
669
670 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000671 while (!(S->getFlags() & Scope::DeclScope) ||
672 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000673 S = S->getParent();
674
675 // Find the last declaration in this scope (with the same
676 // name, naturally).
677 IdentifierResolver::iterator LastI = I;
678 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000679 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000680 break;
John McCallf36e02d2009-10-09 21:13:30 +0000681 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000682 }
Douglas Gregorf9201e02009-02-11 23:02:49 +0000683 }
684
John McCallf36e02d2009-10-09 21:13:30 +0000685 R.resolveKind();
686
687 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000688 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000689 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000690 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000691 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +0000692 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000693 }
694
695 // If we didn't find a use of this identifier, and if the identifier
696 // corresponds to a compiler builtin, create the decl object for the builtin
697 // now, injecting it into translation unit scope, and return it.
Mike Stump1eb44332009-09-09 15:08:12 +0000698 if (NameKind == LookupOrdinaryName ||
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000699 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000700 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000701 if (II && AllowBuiltinCreation) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000702 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor3e41d602009-02-13 23:20:09 +0000703 if (unsigned BuiltinID = II->getBuiltinID()) {
704 // In C++, we don't have any predefined library functions like
705 // 'malloc'. Instead, we'll just error.
Mike Stump1eb44332009-09-09 15:08:12 +0000706 if (getLangOptions().CPlusPlus &&
Douglas Gregor3e41d602009-02-13 23:20:09 +0000707 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCallf36e02d2009-10-09 21:13:30 +0000708 return false;
Douglas Gregor3e41d602009-02-13 23:20:09 +0000709
John McCallf36e02d2009-10-09 21:13:30 +0000710 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCalla24dc2e2009-11-17 02:14:36 +0000711 S, R.isForRedeclaration(),
712 R.getNameLoc());
John McCallf36e02d2009-10-09 21:13:30 +0000713 if (D) R.addDecl(D);
714 return (D != NULL);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000715 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000716 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000717 }
John McCallf36e02d2009-10-09 21:13:30 +0000718 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000719}
720
John McCall6e247262009-10-10 05:48:19 +0000721/// @brief Perform qualified name lookup in the namespaces nominated by
722/// using directives by the given context.
723///
724/// C++98 [namespace.qual]p2:
725/// Given X::m (where X is a user-declared namespace), or given ::m
726/// (where X is the global namespace), let S be the set of all
727/// declarations of m in X and in the transitive closure of all
728/// namespaces nominated by using-directives in X and its used
729/// namespaces, except that using-directives are ignored in any
730/// namespace, including X, directly containing one or more
731/// declarations of m. No namespace is searched more than once in
732/// the lookup of a name. If S is the empty set, the program is
733/// ill-formed. Otherwise, if S has exactly one member, or if the
734/// context of the reference is a using-declaration
735/// (namespace.udecl), S is the required set of declarations of
736/// m. Otherwise if the use of m is not one that allows a unique
737/// declaration to be chosen from S, the program is ill-formed.
738/// C++98 [namespace.qual]p5:
739/// During the lookup of a qualified namespace member name, if the
740/// lookup finds more than one declaration of the member, and if one
741/// declaration introduces a class name or enumeration name and the
742/// other declarations either introduce the same object, the same
743/// enumerator or a set of functions, the non-type name hides the
744/// class or enumeration name if and only if the declarations are
745/// from the same namespace; otherwise (the declarations are from
746/// different namespaces), the program is ill-formed.
John McCall7d384dd2009-11-18 07:57:50 +0000747static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +0000748 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +0000749 assert(StartDC->isFileContext() && "start context is not a file context");
750
751 DeclContext::udir_iterator I = StartDC->using_directives_begin();
752 DeclContext::udir_iterator E = StartDC->using_directives_end();
753
754 if (I == E) return false;
755
756 // We have at least added all these contexts to the queue.
757 llvm::DenseSet<DeclContext*> Visited;
758 Visited.insert(StartDC);
759
760 // We have not yet looked into these namespaces, much less added
761 // their "using-children" to the queue.
762 llvm::SmallVector<NamespaceDecl*, 8> Queue;
763
764 // We have already looked into the initial namespace; seed the queue
765 // with its using-children.
766 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +0000767 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +0000768 if (Visited.insert(ND).second)
769 Queue.push_back(ND);
770 }
771
772 // The easiest way to implement the restriction in [namespace.qual]p5
773 // is to check whether any of the individual results found a tag
774 // and, if so, to declare an ambiguity if the final result is not
775 // a tag.
776 bool FoundTag = false;
777 bool FoundNonTag = false;
778
John McCall7d384dd2009-11-18 07:57:50 +0000779 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +0000780
781 bool Found = false;
782 while (!Queue.empty()) {
783 NamespaceDecl *ND = Queue.back();
784 Queue.pop_back();
785
786 // We go through some convolutions here to avoid copying results
787 // between LookupResults.
788 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +0000789 LookupResult &DirectR = UseLocal ? LocalR : R;
John McCalla24dc2e2009-11-17 02:14:36 +0000790 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +0000791
792 if (FoundDirect) {
793 // First do any local hiding.
794 DirectR.resolveKind();
795
796 // If the local result is a tag, remember that.
797 if (DirectR.isSingleTagDecl())
798 FoundTag = true;
799 else
800 FoundNonTag = true;
801
802 // Append the local results to the total results if necessary.
803 if (UseLocal) {
804 R.addAllDecls(LocalR);
805 LocalR.clear();
806 }
807 }
808
809 // If we find names in this namespace, ignore its using directives.
810 if (FoundDirect) {
811 Found = true;
812 continue;
813 }
814
815 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
816 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
817 if (Visited.insert(Nom).second)
818 Queue.push_back(Nom);
819 }
820 }
821
822 if (Found) {
823 if (FoundTag && FoundNonTag)
824 R.setAmbiguousQualifiedTagHiding();
825 else
826 R.resolveKind();
827 }
828
829 return Found;
830}
831
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000832/// @brief Perform qualified name lookup into a given context.
833///
834/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
835/// names when the context of those names is explicit specified, e.g.,
836/// "std::vector" or "x->member".
837///
838/// Different lookup criteria can find different names. For example, a
839/// particular scope can have both a struct and a function of the same
840/// name, and each can be found by certain lookup criteria. For more
841/// information about lookup criteria, see the documentation for the
842/// class LookupCriteria.
843///
844/// @param LookupCtx The context in which qualified name lookup will
845/// search. If the lookup criteria permits, name lookup may also search
846/// in the parent contexts or (for C++ classes) base classes.
847///
848/// @param Name The name of the entity that we are searching for.
849///
850/// @param Criteria The criteria that this routine will use to
851/// determine which names are visible and which names will be
852/// found. Note that name lookup will find a name that is visible by
853/// the given criteria, but the entity itself may not be semantically
854/// correct or even the kind of entity expected based on the
855/// lookup. For example, searching for a nested-name-specifier name
856/// might result in an EnumDecl, which is visible but is not permitted
857/// as a nested-name-specifier in C++03.
858///
859/// @returns The result of name lookup, which includes zero or more
860/// declarations and possibly additional information used to diagnose
861/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000862bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000863 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +0000864
John McCalla24dc2e2009-11-17 02:14:36 +0000865 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +0000866 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000868 // If we're performing qualified name lookup (e.g., lookup into a
869 // struct), find fields as part of ordinary name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000870 LookupNameKind NameKind = R.getLookupKind();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000871 unsigned IDNS
Mike Stump1eb44332009-09-09 15:08:12 +0000872 = getIdentifierNamespacesFromLookupNameKind(NameKind,
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000873 getLangOptions().CPlusPlus);
874 if (NameKind == LookupOrdinaryName)
875 IDNS |= Decl::IDNS_Member;
Mike Stump1eb44332009-09-09 15:08:12 +0000876
John McCalla24dc2e2009-11-17 02:14:36 +0000877 R.setIdentifierNamespace(IDNS);
878
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000879 // Make sure that the declaration context is complete.
880 assert((!isa<TagDecl>(LookupCtx) ||
881 LookupCtx->isDependentContext() ||
882 cast<TagDecl>(LookupCtx)->isDefinition() ||
883 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
884 ->isBeingDefined()) &&
885 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000887 // Perform qualified name lookup into the LookupCtx.
John McCalla24dc2e2009-11-17 02:14:36 +0000888 if (LookupDirect(R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +0000889 R.resolveKind();
890 return true;
891 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000892
John McCall6e247262009-10-10 05:48:19 +0000893 // Don't descend into implied contexts for redeclarations.
894 // C++98 [namespace.qual]p6:
895 // In a declaration for a namespace member in which the
896 // declarator-id is a qualified-id, given that the qualified-id
897 // for the namespace member has the form
898 // nested-name-specifier unqualified-id
899 // the unqualified-id shall name a member of the namespace
900 // designated by the nested-name-specifier.
901 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +0000902 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +0000903 return false;
904
John McCalla24dc2e2009-11-17 02:14:36 +0000905 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +0000906 if (LookupCtx->isFileContext())
John McCalla24dc2e2009-11-17 02:14:36 +0000907 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +0000908
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000909 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +0000910 // classes, we're done.
John McCall6e247262009-10-10 05:48:19 +0000911 if (!isa<CXXRecordDecl>(LookupCtx))
John McCallf36e02d2009-10-09 21:13:30 +0000912 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000913
914 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +0000915 CXXRecordDecl *LookupRec = cast<CXXRecordDecl>(LookupCtx);
916 CXXBasePaths Paths;
917 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000918
919 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +0000920 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000921 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000922 case LookupOrdinaryName:
923 case LookupMemberName:
924 case LookupRedeclarationWithLinkage:
925 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
926 break;
927
928 case LookupTagName:
929 BaseCallback = &CXXRecordDecl::FindTagMember;
930 break;
931
932 case LookupOperatorName:
933 case LookupNamespaceName:
934 case LookupObjCProtocolName:
935 case LookupObjCImplementationName:
936 case LookupObjCCategoryImplName:
937 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +0000938 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000939
940 case LookupNestedNameSpecifierName:
941 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
942 break;
943 }
944
John McCalla24dc2e2009-11-17 02:14:36 +0000945 if (!LookupRec->lookupInBases(BaseCallback,
946 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +0000947 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000948
949 // C++ [class.member.lookup]p2:
950 // [...] If the resulting set of declarations are not all from
951 // sub-objects of the same type, or the set has a nonstatic member
952 // and includes members from distinct sub-objects, there is an
953 // ambiguity and the program is ill-formed. Otherwise that set is
954 // the result of the lookup.
955 // FIXME: support using declarations!
956 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +0000957 int SubobjectNumber = 0;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000958 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000959 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000960 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000961
962 // Determine whether we're looking at a distinct sub-object or not.
963 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +0000964 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000965 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
966 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +0000967 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +0000968 != Context.getCanonicalType(PathElement.Base->getType())) {
969 // We found members of the given name in two subobjects of
970 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +0000971 R.setAmbiguousBaseSubobjectTypes(Paths);
972 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000973 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
974 // We have a different subobject of the same type.
975
976 // C++ [class.member.lookup]p5:
977 // A static member, a nested type or an enumerator defined in
978 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +0000979 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000980 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000981 if (isa<VarDecl>(FirstDecl) ||
982 isa<TypeDecl>(FirstDecl) ||
983 isa<EnumConstantDecl>(FirstDecl))
984 continue;
985
986 if (isa<CXXMethodDecl>(FirstDecl)) {
987 // Determine whether all of the methods are static.
988 bool AllMethodsAreStatic = true;
989 for (DeclContext::lookup_iterator Func = Path->Decls.first;
990 Func != Path->Decls.second; ++Func) {
991 if (!isa<CXXMethodDecl>(*Func)) {
992 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
993 break;
994 }
995
996 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
997 AllMethodsAreStatic = false;
998 break;
999 }
1000 }
1001
1002 if (AllMethodsAreStatic)
1003 continue;
1004 }
1005
1006 // We have found a nonstatic member name in multiple, distinct
1007 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001008 R.setAmbiguousBaseSubobjects(Paths);
1009 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001010 }
1011 }
1012
1013 // Lookup in a base class succeeded; return these results.
1014
John McCallf36e02d2009-10-09 21:13:30 +00001015 DeclContext::lookup_iterator I, E;
1016 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I)
1017 R.addDecl(*I);
1018 R.resolveKind();
1019 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001020}
1021
1022/// @brief Performs name lookup for a name that was parsed in the
1023/// source code, and may contain a C++ scope specifier.
1024///
1025/// This routine is a convenience routine meant to be called from
1026/// contexts that receive a name and an optional C++ scope specifier
1027/// (e.g., "N::M::x"). It will then perform either qualified or
1028/// unqualified name lookup (with LookupQualifiedName or LookupName,
1029/// respectively) on the given name and return those results.
1030///
1031/// @param S The scope from which unqualified name lookup will
1032/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001033///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001034/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001035///
1036/// @param Name The name of the entity that name lookup will
1037/// search for.
1038///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001039/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001040/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001041/// C library functions (like "malloc") are implicitly declared.
1042///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001043/// @param EnteringContext Indicates whether we are going to enter the
1044/// context of the scope-specifier SS (if present).
1045///
John McCallf36e02d2009-10-09 21:13:30 +00001046/// @returns True if any decls were found (but possibly ambiguous)
1047bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001048 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001049 if (SS && SS->isInvalid()) {
1050 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001051 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001052 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001053 }
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Douglas Gregor495c35d2009-08-25 22:51:20 +00001055 if (SS && SS->isSet()) {
1056 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001057 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001058 // contex, and will perform name lookup in that context.
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001059 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCallf36e02d2009-10-09 21:13:30 +00001060 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001061
John McCalla24dc2e2009-11-17 02:14:36 +00001062 R.setContextRange(SS->getRange());
1063
1064 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001065 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001066
Douglas Gregor495c35d2009-08-25 22:51:20 +00001067 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001068 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001069 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001070 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001071 }
1072
Mike Stump1eb44332009-09-09 15:08:12 +00001073 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001074 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001075}
1076
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001077
Douglas Gregor7176fff2009-01-15 00:26:24 +00001078/// @brief Produce a diagnostic describing the ambiguity that resulted
1079/// from name lookup.
1080///
1081/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001082///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001083/// @param Name The name of the entity that name lookup was
1084/// searching for.
1085///
1086/// @param NameLoc The location of the name within the source code.
1087///
1088/// @param LookupRange A source range that provides more
1089/// source-location information concerning the lookup itself. For
1090/// example, this range might highlight a nested-name-specifier that
1091/// precedes the name.
1092///
1093/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001094bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001095 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1096
John McCalla24dc2e2009-11-17 02:14:36 +00001097 DeclarationName Name = Result.getLookupName();
1098 SourceLocation NameLoc = Result.getNameLoc();
1099 SourceRange LookupRange = Result.getContextRange();
1100
John McCall6e247262009-10-10 05:48:19 +00001101 switch (Result.getAmbiguityKind()) {
1102 case LookupResult::AmbiguousBaseSubobjects: {
1103 CXXBasePaths *Paths = Result.getBasePaths();
1104 QualType SubobjectType = Paths->front().back().Base->getType();
1105 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1106 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1107 << LookupRange;
1108
1109 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1110 while (isa<CXXMethodDecl>(*Found) &&
1111 cast<CXXMethodDecl>(*Found)->isStatic())
1112 ++Found;
1113
1114 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1115
1116 return true;
1117 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001118
John McCall6e247262009-10-10 05:48:19 +00001119 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001120 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1121 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001122
1123 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001124 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001125 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1126 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001127 Path != PathEnd; ++Path) {
1128 Decl *D = *Path->Decls.first;
1129 if (DeclsPrinted.insert(D).second)
1130 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1131 }
1132
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001133 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001134 }
1135
John McCall6e247262009-10-10 05:48:19 +00001136 case LookupResult::AmbiguousTagHiding: {
1137 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001138
John McCall6e247262009-10-10 05:48:19 +00001139 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1140
1141 LookupResult::iterator DI, DE = Result.end();
1142 for (DI = Result.begin(); DI != DE; ++DI)
1143 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1144 TagDecls.insert(TD);
1145 Diag(TD->getLocation(), diag::note_hidden_tag);
1146 }
1147
1148 for (DI = Result.begin(); DI != DE; ++DI)
1149 if (!isa<TagDecl>(*DI))
1150 Diag((*DI)->getLocation(), diag::note_hiding_object);
1151
1152 // For recovery purposes, go ahead and implement the hiding.
1153 Result.hideDecls(TagDecls);
1154
1155 return true;
1156 }
1157
1158 case LookupResult::AmbiguousReference: {
1159 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001160
John McCall6e247262009-10-10 05:48:19 +00001161 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1162 for (; DI != DE; ++DI)
1163 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001164
John McCall6e247262009-10-10 05:48:19 +00001165 return true;
1166 }
1167 }
1168
1169 llvm::llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001170 return true;
1171}
Douglas Gregorfa047642009-02-04 00:32:51 +00001172
Mike Stump1eb44332009-09-09 15:08:12 +00001173static void
1174addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001175 ASTContext &Context,
1176 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001177 Sema::AssociatedClassSet &AssociatedClasses);
1178
1179static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1180 DeclContext *Ctx) {
1181 if (Ctx->isFileContext())
1182 Namespaces.insert(Ctx);
1183}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001184
Mike Stump1eb44332009-09-09 15:08:12 +00001185// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001186// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001187static void
1188addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001189 ASTContext &Context,
1190 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001191 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001192 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001193 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001194 switch (Arg.getKind()) {
1195 case TemplateArgument::Null:
1196 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Douglas Gregor69be8d62009-07-08 07:51:57 +00001198 case TemplateArgument::Type:
1199 // [...] the namespaces and classes associated with the types of the
1200 // template arguments provided for template type parameters (excluding
1201 // template template parameters)
1202 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1203 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001204 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001205 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Douglas Gregor788cd062009-11-11 01:00:40 +00001207 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001208 // [...] the namespaces in which any template template arguments are
1209 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001210 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001211 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001212 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001213 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001214 DeclContext *Ctx = ClassTemplate->getDeclContext();
1215 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1216 AssociatedClasses.insert(EnclosingClass);
1217 // Add the associated namespace for this class.
1218 while (Ctx->isRecord())
1219 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001220 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001221 }
1222 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001223 }
1224
1225 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001226 case TemplateArgument::Integral:
1227 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001228 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001229 // associated namespaces. ]
1230 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Douglas Gregor69be8d62009-07-08 07:51:57 +00001232 case TemplateArgument::Pack:
1233 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1234 PEnd = Arg.pack_end();
1235 P != PEnd; ++P)
1236 addAssociatedClassesAndNamespaces(*P, Context,
1237 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001238 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001239 break;
1240 }
1241}
1242
Douglas Gregorfa047642009-02-04 00:32:51 +00001243// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001244// argument-dependent lookup with an argument of class type
1245// (C++ [basic.lookup.koenig]p2).
1246static void
1247addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregorfa047642009-02-04 00:32:51 +00001248 ASTContext &Context,
1249 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001250 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001251 // C++ [basic.lookup.koenig]p2:
1252 // [...]
1253 // -- If T is a class type (including unions), its associated
1254 // classes are: the class itself; the class of which it is a
1255 // member, if any; and its direct and indirect base
1256 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001257 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001258
1259 // Add the class of which it is a member, if any.
1260 DeclContext *Ctx = Class->getDeclContext();
1261 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1262 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001263 // Add the associated namespace for this class.
1264 while (Ctx->isRecord())
1265 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001266 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Douglas Gregorfa047642009-02-04 00:32:51 +00001268 // Add the class itself. If we've already seen this class, we don't
1269 // need to visit base classes.
1270 if (!AssociatedClasses.insert(Class))
1271 return;
1272
Mike Stump1eb44332009-09-09 15:08:12 +00001273 // -- If T is a template-id, its associated namespaces and classes are
1274 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001275 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001276 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001277 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001278 // namespaces in which any template template arguments are defined; and
1279 // the classes in which any member templates used as template template
1280 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001281 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001282 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001283 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1284 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1285 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1286 AssociatedClasses.insert(EnclosingClass);
1287 // Add the associated namespace for this class.
1288 while (Ctx->isRecord())
1289 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001290 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Douglas Gregor69be8d62009-07-08 07:51:57 +00001292 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1293 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1294 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1295 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001296 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001297 }
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Douglas Gregorfa047642009-02-04 00:32:51 +00001299 // Add direct and indirect base classes along with their associated
1300 // namespaces.
1301 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1302 Bases.push_back(Class);
1303 while (!Bases.empty()) {
1304 // Pop this class off the stack.
1305 Class = Bases.back();
1306 Bases.pop_back();
1307
1308 // Visit the base classes.
1309 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1310 BaseEnd = Class->bases_end();
1311 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001312 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001313 // In dependent contexts, we do ADL twice, and the first time around,
1314 // the base type might be a dependent TemplateSpecializationType, or a
1315 // TemplateTypeParmType. If that happens, simply ignore it.
1316 // FIXME: If we want to support export, we probably need to add the
1317 // namespace of the template in a TemplateSpecializationType, or even
1318 // the classes and namespaces of known non-dependent arguments.
1319 if (!BaseType)
1320 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001321 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1322 if (AssociatedClasses.insert(BaseDecl)) {
1323 // Find the associated namespace for this base class.
1324 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1325 while (BaseCtx->isRecord())
1326 BaseCtx = BaseCtx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001327 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001328
1329 // Make sure we visit the bases of this base class.
1330 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1331 Bases.push_back(BaseDecl);
1332 }
1333 }
1334 }
1335}
1336
1337// \brief Add the associated classes and namespaces for
1338// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001339// (C++ [basic.lookup.koenig]p2).
1340static void
1341addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregorfa047642009-02-04 00:32:51 +00001342 ASTContext &Context,
1343 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001344 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001345 // C++ [basic.lookup.koenig]p2:
1346 //
1347 // For each argument type T in the function call, there is a set
1348 // of zero or more associated namespaces and a set of zero or more
1349 // associated classes to be considered. The sets of namespaces and
1350 // classes is determined entirely by the types of the function
1351 // arguments (and the namespace of any template template
1352 // argument). Typedef names and using-declarations used to specify
1353 // the types do not contribute to this set. The sets of namespaces
1354 // and classes are determined in the following way:
1355 T = Context.getCanonicalType(T).getUnqualifiedType();
1356
1357 // -- If T is a pointer to U or an array of U, its associated
Mike Stump1eb44332009-09-09 15:08:12 +00001358 // namespaces and classes are those associated with U.
Douglas Gregorfa047642009-02-04 00:32:51 +00001359 //
1360 // We handle this by unwrapping pointer and array types immediately,
1361 // to avoid unnecessary recursion.
1362 while (true) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001363 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001364 T = Ptr->getPointeeType();
1365 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1366 T = Ptr->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001367 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001368 break;
1369 }
1370
1371 // -- If T is a fundamental type, its associated sets of
1372 // namespaces and classes are both empty.
John McCall183700f2009-09-21 23:43:11 +00001373 if (T->getAs<BuiltinType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001374 return;
1375
1376 // -- If T is a class type (including unions), its associated
1377 // classes are: the class itself; the class of which it is a
1378 // member, if any; and its direct and indirect base
1379 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001380 // which its associated classes are defined.
Ted Kremenek6217b802009-07-29 21:53:49 +00001381 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001382 if (CXXRecordDecl *ClassDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001383 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001384 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1385 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001386 AssociatedClasses);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001387 return;
1388 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001389
1390 // -- If T is an enumeration type, its associated namespace is
1391 // the namespace in which it is defined. If it is class
1392 // member, its associated class is the member’s class; else
Mike Stump1eb44332009-09-09 15:08:12 +00001393 // it has no associated class.
John McCall183700f2009-09-21 23:43:11 +00001394 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001395 EnumDecl *Enum = EnumT->getDecl();
1396
1397 DeclContext *Ctx = Enum->getDeclContext();
1398 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1399 AssociatedClasses.insert(EnclosingClass);
1400
1401 // Add the associated namespace for this class.
1402 while (Ctx->isRecord())
1403 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001404 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001405
1406 return;
1407 }
1408
1409 // -- If T is a function type, its associated namespaces and
1410 // classes are those associated with the function parameter
1411 // types and those associated with the return type.
John McCall183700f2009-09-21 23:43:11 +00001412 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001413 // Return type
John McCall183700f2009-09-21 23:43:11 +00001414 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001415 Context,
John McCall6ff07852009-08-07 22:18:02 +00001416 AssociatedNamespaces, AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001417
John McCall183700f2009-09-21 23:43:11 +00001418 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001419 if (!Proto)
1420 return;
1421
1422 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001423 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001424 ArgEnd = Proto->arg_type_end();
Douglas Gregorfa047642009-02-04 00:32:51 +00001425 Arg != ArgEnd; ++Arg)
1426 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCall6ff07852009-08-07 22:18:02 +00001427 AssociatedNamespaces, AssociatedClasses);
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Douglas Gregorfa047642009-02-04 00:32:51 +00001429 return;
1430 }
1431
1432 // -- If T is a pointer to a member function of a class X, its
1433 // associated namespaces and classes are those associated
1434 // with the function parameter types and return type,
Mike Stump1eb44332009-09-09 15:08:12 +00001435 // together with those associated with X.
Douglas Gregorfa047642009-02-04 00:32:51 +00001436 //
1437 // -- If T is a pointer to a data member of class X, its
1438 // associated namespaces and classes are those associated
1439 // with the member type together with those associated with
Mike Stump1eb44332009-09-09 15:08:12 +00001440 // X.
Ted Kremenek6217b802009-07-29 21:53:49 +00001441 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001442 // Handle the type that the pointer to member points to.
1443 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1444 Context,
John McCall6ff07852009-08-07 22:18:02 +00001445 AssociatedNamespaces,
1446 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001447
1448 // Handle the class type into which this points.
Ted Kremenek6217b802009-07-29 21:53:49 +00001449 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001450 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1451 Context,
John McCall6ff07852009-08-07 22:18:02 +00001452 AssociatedNamespaces,
1453 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001454
1455 return;
1456 }
1457
1458 // FIXME: What about block pointers?
1459 // FIXME: What about Objective-C message sends?
1460}
1461
1462/// \brief Find the associated classes and namespaces for
1463/// argument-dependent lookup for a call with the given set of
1464/// arguments.
1465///
1466/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001467/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001468/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001469void
Douglas Gregorfa047642009-02-04 00:32:51 +00001470Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1471 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001472 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001473 AssociatedNamespaces.clear();
1474 AssociatedClasses.clear();
1475
1476 // C++ [basic.lookup.koenig]p2:
1477 // For each argument type T in the function call, there is a set
1478 // of zero or more associated namespaces and a set of zero or more
1479 // associated classes to be considered. The sets of namespaces and
1480 // classes is determined entirely by the types of the function
1481 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001482 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001483 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1484 Expr *Arg = Args[ArgIdx];
1485
1486 if (Arg->getType() != Context.OverloadTy) {
1487 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001488 AssociatedNamespaces,
1489 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001490 continue;
1491 }
1492
1493 // [...] In addition, if the argument is the name or address of a
1494 // set of overloaded functions and/or function templates, its
1495 // associated classes and namespaces are the union of those
1496 // associated with each of the members of the set: the namespace
1497 // in which the function or function template is defined and the
1498 // classes and namespaces associated with its (non-dependent)
1499 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001500 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001501 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1502 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1503 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001504
John McCallba135432009-11-21 08:51:07 +00001505 // TODO: avoid the copies. This should be easy when the cases
1506 // share a storage implementation.
1507 llvm::SmallVector<NamedDecl*, 8> Functions;
1508
1509 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1510 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00001511 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001512 continue;
1513
John McCallba135432009-11-21 08:51:07 +00001514 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1515 E = Functions.end(); I != E; ++I) {
1516 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I);
Douglas Gregore53060f2009-06-25 22:08:12 +00001517 if (!FDecl)
John McCallba135432009-11-21 08:51:07 +00001518 FDecl = cast<FunctionTemplateDecl>(*I)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001519
1520 // Add the namespace in which this function was defined. Note
1521 // that, if this is a member function, we do *not* consider the
1522 // enclosing namespace of its class.
1523 DeclContext *Ctx = FDecl->getDeclContext();
John McCall6ff07852009-08-07 22:18:02 +00001524 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001525
1526 // Add the classes and namespaces associated with the parameter
1527 // types and return type of this function.
1528 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001529 AssociatedNamespaces,
1530 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001531 }
1532 }
1533}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001534
1535/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1536/// an acceptable non-member overloaded operator for a call whose
1537/// arguments have types T1 (and, if non-empty, T2). This routine
1538/// implements the check in C++ [over.match.oper]p3b2 concerning
1539/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001540static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001541IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1542 QualType T1, QualType T2,
1543 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001544 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1545 return true;
1546
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001547 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1548 return true;
1549
John McCall183700f2009-09-21 23:43:11 +00001550 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001551 if (Proto->getNumArgs() < 1)
1552 return false;
1553
1554 if (T1->isEnumeralType()) {
1555 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001556 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001557 return true;
1558 }
1559
1560 if (Proto->getNumArgs() < 2)
1561 return false;
1562
1563 if (!T2.isNull() && T2->isEnumeralType()) {
1564 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001565 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001566 return true;
1567 }
1568
1569 return false;
1570}
1571
John McCall7d384dd2009-11-18 07:57:50 +00001572NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1573 LookupNameKind NameKind,
1574 RedeclarationKind Redecl) {
1575 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1576 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00001577 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00001578}
1579
Douglas Gregor6e378de2009-04-23 23:18:26 +00001580/// \brief Find the protocol with the given name, if any.
1581ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCallf36e02d2009-10-09 21:13:30 +00001582 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001583 return cast_or_null<ObjCProtocolDecl>(D);
1584}
1585
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001586/// \brief Find the Objective-C category implementation with the given
1587/// name, if any.
1588ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
John McCallf36e02d2009-10-09 21:13:30 +00001589 Decl *D = LookupSingleName(TUScope, II, LookupObjCCategoryImplName);
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001590 return cast_or_null<ObjCCategoryImplDecl>(D);
1591}
1592
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001593void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001594 QualType T1, QualType T2,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001595 FunctionSet &Functions) {
1596 // C++ [over.match.oper]p3:
1597 // -- The set of non-member candidates is the result of the
1598 // unqualified lookup of operator@ in the context of the
1599 // expression according to the usual rules for name lookup in
1600 // unqualified function calls (3.4.2) except that all member
1601 // functions are ignored. However, if no operand has a class
1602 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00001603 // that have a first parameter of type T1 or "reference to
1604 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001605 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00001606 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001607 // when T2 is an enumeration type, are candidate functions.
1608 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00001609 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1610 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001612 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1613
John McCallf36e02d2009-10-09 21:13:30 +00001614 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001615 return;
1616
1617 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1618 Op != OpEnd; ++Op) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001619 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001620 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1621 Functions.insert(FD); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00001622 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor364e0212009-06-27 21:05:07 +00001623 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1624 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00001625 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00001626 // later?
1627 if (!FunTmpl->getDeclContext()->isRecord())
1628 Functions.insert(FunTmpl);
1629 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001630 }
1631}
1632
John McCall6ff07852009-08-07 22:18:02 +00001633static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1634 Decl *D) {
1635 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1636 Functions.insert(Func);
1637 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1638 Functions.insert(FunTmpl);
1639}
1640
Sebastian Redl644be852009-10-23 19:23:15 +00001641void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001642 Expr **Args, unsigned NumArgs,
1643 FunctionSet &Functions) {
1644 // Find all of the associated namespaces and classes based on the
1645 // arguments we have.
1646 AssociatedNamespaceSet AssociatedNamespaces;
1647 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00001648 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00001649 AssociatedNamespaces,
1650 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001651
Sebastian Redl644be852009-10-23 19:23:15 +00001652 QualType T1, T2;
1653 if (Operator) {
1654 T1 = Args[0]->getType();
1655 if (NumArgs >= 2)
1656 T2 = Args[1]->getType();
1657 }
1658
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001659 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001660 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1661 // and let Y be the lookup set produced by argument dependent
1662 // lookup (defined as follows). If X contains [...] then Y is
1663 // empty. Otherwise Y is the set of declarations found in the
1664 // namespaces associated with the argument types as described
1665 // below. The set of declarations found by the lookup of the name
1666 // is the union of X and Y.
1667 //
1668 // Here, we compute Y and add its members to the overloaded
1669 // candidate set.
1670 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001671 NSEnd = AssociatedNamespaces.end();
1672 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001673 // When considering an associated namespace, the lookup is the
1674 // same as the lookup performed when the associated namespace is
1675 // used as a qualifier (3.4.3.2) except that:
1676 //
1677 // -- Any using-directives in the associated namespace are
1678 // ignored.
1679 //
John McCall6ff07852009-08-07 22:18:02 +00001680 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001681 // associated classes are visible within their respective
1682 // namespaces even if they are not visible during an ordinary
1683 // lookup (11.4).
1684 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00001685 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6ff07852009-08-07 22:18:02 +00001686 Decl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00001687 // If the only declaration here is an ordinary friend, consider
1688 // it only if it was declared in an associated classes.
1689 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00001690 DeclContext *LexDC = D->getLexicalDeclContext();
1691 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1692 continue;
1693 }
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Sebastian Redl644be852009-10-23 19:23:15 +00001695 FunctionDecl *Fn;
1696 if (!Operator || !(Fn = dyn_cast<FunctionDecl>(D)) ||
1697 IsAcceptableNonMemberOperatorCandidate(Fn, T1, T2, Context))
1698 CollectFunctionDecl(Functions, D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001699 }
1700 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001701}