blob: 66c846b078fb36484aaa30935b29b2cac10f6ad9 [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor34074322009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6538c932009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor1c846b02009-01-16 00:38:09 +000030#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000031#include <vector>
32#include <iterator>
33#include <utility>
34#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000035
36using namespace clang;
37
John McCallf6c8a4e2009-11-10 07:01:13 +000038namespace {
39 class UnqualUsingEntry {
40 const DeclContext *Nominated;
41 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000042
John McCallf6c8a4e2009-11-10 07:01:13 +000043 public:
44 UnqualUsingEntry(const DeclContext *Nominated,
45 const DeclContext *CommonAncestor)
46 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
47 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000048
John McCallf6c8a4e2009-11-10 07:01:13 +000049 const DeclContext *getCommonAncestor() const {
50 return CommonAncestor;
51 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000052
John McCallf6c8a4e2009-11-10 07:01:13 +000053 const DeclContext *getNominatedNamespace() const {
54 return Nominated;
55 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000056
John McCallf6c8a4e2009-11-10 07:01:13 +000057 // Sort by the pointer value of the common ancestor.
58 struct Comparator {
59 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
60 return L.getCommonAncestor() < R.getCommonAncestor();
61 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000062
John McCallf6c8a4e2009-11-10 07:01:13 +000063 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
64 return E.getCommonAncestor() < DC;
65 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000066
John McCallf6c8a4e2009-11-10 07:01:13 +000067 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
68 return DC < E.getCommonAncestor();
69 }
70 };
71 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000072
John McCallf6c8a4e2009-11-10 07:01:13 +000073 /// A collection of using directives, as used by C++ unqualified
74 /// lookup.
75 class UnqualUsingDirectiveSet {
76 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000077
John McCallf6c8a4e2009-11-10 07:01:13 +000078 ListTy list;
79 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000080
John McCallf6c8a4e2009-11-10 07:01:13 +000081 public:
82 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000083
John McCallf6c8a4e2009-11-10 07:01:13 +000084 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
85 // C++ [namespace.udir]p1:
86 // During unqualified name lookup, the names appear as if they
87 // were declared in the nearest enclosing namespace which contains
88 // both the using-directive and the nominated namespace.
89 DeclContext *InnermostFileDC
90 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
91 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000092
John McCallf6c8a4e2009-11-10 07:01:13 +000093 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +000094 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
95 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
96 visit(Ctx, EffectiveDC);
97 } else {
98 Scope::udir_iterator I = S->using_directives_begin(),
99 End = S->using_directives_end();
100
101 for (; I != End; ++I)
102 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
103 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000104 }
105 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000106
107 // Visits a context and collect all of its using directives
108 // recursively. Treats all using directives as if they were
109 // declared in the context.
110 //
111 // A given context is only every visited once, so it is important
112 // that contexts be visited from the inside out in order to get
113 // the effective DCs right.
114 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
115 if (!visited.insert(DC))
116 return;
117
118 addUsingDirectives(DC, EffectiveDC);
119 }
120
121 // Visits a using directive and collects all of its using
122 // directives recursively. Treats all using directives as if they
123 // were declared in the effective DC.
124 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
125 DeclContext *NS = UD->getNominatedNamespace();
126 if (!visited.insert(NS))
127 return;
128
129 addUsingDirective(UD, EffectiveDC);
130 addUsingDirectives(NS, EffectiveDC);
131 }
132
133 // Adds all the using directives in a context (and those nominated
134 // by its using directives, transitively) as if they appeared in
135 // the given effective context.
136 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
137 llvm::SmallVector<DeclContext*,4> queue;
138 while (true) {
139 DeclContext::udir_iterator I, End;
140 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
141 UsingDirectiveDecl *UD = *I;
142 DeclContext *NS = UD->getNominatedNamespace();
143 if (visited.insert(NS)) {
144 addUsingDirective(UD, EffectiveDC);
145 queue.push_back(NS);
146 }
147 }
148
149 if (queue.empty())
150 return;
151
152 DC = queue.back();
153 queue.pop_back();
154 }
155 }
156
157 // Add a using directive as if it had been declared in the given
158 // context. This helps implement C++ [namespace.udir]p3:
159 // The using-directive is transitive: if a scope contains a
160 // using-directive that nominates a second namespace that itself
161 // contains using-directives, the effect is as if the
162 // using-directives from the second namespace also appeared in
163 // the first.
164 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
165 // Find the common ancestor between the effective context and
166 // the nominated namespace.
167 DeclContext *Common = UD->getNominatedNamespace();
168 while (!Common->Encloses(EffectiveDC))
169 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000170 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000171
172 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
173 }
174
175 void done() {
176 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
177 }
178
179 typedef ListTy::iterator iterator;
180 typedef ListTy::const_iterator const_iterator;
181
182 iterator begin() { return list.begin(); }
183 iterator end() { return list.end(); }
184 const_iterator begin() const { return list.begin(); }
185 const_iterator end() const { return list.end(); }
186
187 std::pair<const_iterator,const_iterator>
188 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000189 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000190 UnqualUsingEntry::Comparator());
191 }
192 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000193}
194
Douglas Gregor889ceb72009-02-03 19:21:40 +0000195// Retrieve the set of identifier namespaces that correspond to a
196// specific kind of name lookup.
Mike Stump11289f42009-09-09 15:08:12 +0000197inline unsigned
198getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
Douglas Gregor889ceb72009-02-03 19:21:40 +0000199 bool CPlusPlus) {
200 unsigned IDNS = 0;
201 switch (NameKind) {
202 case Sema::LookupOrdinaryName:
Douglas Gregor94eabf32009-02-04 16:44:47 +0000203 case Sema::LookupOperatorName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000204 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205 IDNS = Decl::IDNS_Ordinary;
206 if (CPlusPlus)
207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
208 break;
209
210 case Sema::LookupTagName:
211 IDNS = Decl::IDNS_Tag;
212 break;
213
214 case Sema::LookupMemberName:
215 IDNS = Decl::IDNS_Member;
216 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000217 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000218 break;
219
220 case Sema::LookupNestedNameSpecifierName:
221 case Sema::LookupNamespaceName:
222 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
223 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000224
John McCall84d87672009-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 Gregor79947a22009-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;
237
238 case Sema::LookupObjCCategoryImplName:
239 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000240 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000241 }
242 return IDNS;
243}
244
John McCall9f3059a2009-10-09 21:13:30 +0000245// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000246void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000247 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000248}
249
John McCall283b9012009-11-22 00:44:51 +0000250/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000251void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000252 unsigned N = Decls.size();
John McCall84d87672009-12-10 09:41:52 +0000253
John McCall9f3059a2009-10-09 21:13:30 +0000254 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000255 if (N == 0) {
256 assert(ResultKind == NotFound);
257 return;
258 }
259
John McCall283b9012009-11-22 00:44:51 +0000260 // If there's a single decl, we need to examine it to decide what
261 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000262 if (N == 1) {
John McCall283b9012009-11-22 00:44:51 +0000263 if (isa<FunctionTemplateDecl>(Decls[0]))
264 ResultKind = FoundOverloaded;
265 else if (isa<UnresolvedUsingValueDecl>(Decls[0]))
John McCalle61f2ba2009-11-18 02:36:19 +0000266 ResultKind = FoundUnresolvedValue;
267 return;
268 }
John McCall9f3059a2009-10-09 21:13:30 +0000269
John McCall6538c932009-10-10 05:48:19 +0000270 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000271 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000272
John McCall9f3059a2009-10-09 21:13:30 +0000273 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
274
275 bool Ambiguous = false;
276 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000277 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000278
279 unsigned UniqueTagIndex = 0;
280
281 unsigned I = 0;
282 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000283 NamedDecl *D = Decls[I]->getUnderlyingDecl();
284 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000285
John McCallf0f1cf02009-11-17 07:50:12 +0000286 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000287 // If it's not unique, pull something off the back (and
288 // continue at this index).
289 Decls[I] = Decls[--N];
John McCall9f3059a2009-10-09 21:13:30 +0000290 } else {
291 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000292
293 if (isa<UnresolvedUsingValueDecl>(D)) {
294 HasUnresolved = true;
295 } else if (isa<TagDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000296 if (HasTag)
297 Ambiguous = true;
298 UniqueTagIndex = I;
299 HasTag = true;
John McCall283b9012009-11-22 00:44:51 +0000300 } else if (isa<FunctionTemplateDecl>(D)) {
301 HasFunction = true;
302 HasFunctionTemplate = true;
303 } else if (isa<FunctionDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000304 HasFunction = true;
305 } else {
306 if (HasNonFunction)
307 Ambiguous = true;
308 HasNonFunction = true;
309 }
310 I++;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000311 }
Mike Stump11289f42009-09-09 15:08:12 +0000312 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000313
John McCall9f3059a2009-10-09 21:13:30 +0000314 // C++ [basic.scope.hiding]p2:
315 // A class name or enumeration name can be hidden by the name of
316 // an object, function, or enumerator declared in the same
317 // scope. If a class or enumeration name and an object, function,
318 // or enumerator are declared in the same scope (in any order)
319 // with the same name, the class or enumeration name is hidden
320 // wherever the object, function, or enumerator name is visible.
321 // But it's still an error if there are distinct tag types found,
322 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000323 if (HideTags && HasTag && !Ambiguous &&
324 (HasFunction || HasNonFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000325 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000326
John McCall9f3059a2009-10-09 21:13:30 +0000327 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000328
John McCall80053822009-12-03 00:58:24 +0000329 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000330 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000331
John McCall9f3059a2009-10-09 21:13:30 +0000332 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000333 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000334 else if (HasUnresolved)
335 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000336 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000337 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000338 else
John McCall27b18f82009-11-17 02:14:36 +0000339 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000340}
341
John McCall5cebab12009-11-18 07:57:50 +0000342void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000343 CXXBasePaths::paths_iterator I, E;
344 DeclContext::lookup_iterator DI, DE;
345 for (I = P.begin(), E = P.end(); I != E; ++I)
346 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
347 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000348}
349
John McCall5cebab12009-11-18 07:57:50 +0000350void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000351 Paths = new CXXBasePaths;
352 Paths->swap(P);
353 addDeclsFromBasePaths(*Paths);
354 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000355 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000356}
357
John McCall5cebab12009-11-18 07:57:50 +0000358void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000359 Paths = new CXXBasePaths;
360 Paths->swap(P);
361 addDeclsFromBasePaths(*Paths);
362 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000363 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000364}
365
John McCall5cebab12009-11-18 07:57:50 +0000366void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000367 Out << Decls.size() << " result(s)";
368 if (isAmbiguous()) Out << ", ambiguous";
369 if (Paths) Out << ", base paths present";
370
371 for (iterator I = begin(), E = end(); I != E; ++I) {
372 Out << "\n";
373 (*I)->print(Out, 2);
374 }
375}
376
377// Adds all qualifying matches for a name within a decl context to the
378// given lookup result. Returns true if any matches were found.
John McCall5cebab12009-11-18 07:57:50 +0000379static bool LookupDirect(LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000380 bool Found = false;
381
John McCallf6c8a4e2009-11-10 07:01:13 +0000382 DeclContext::lookup_const_iterator I, E;
John McCall27b18f82009-11-17 02:14:36 +0000383 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I)
384 if (Sema::isAcceptableLookupResult(*I, R.getLookupKind(),
385 R.getIdentifierNamespace()))
John McCall9f3059a2009-10-09 21:13:30 +0000386 R.addDecl(*I), Found = true;
387
388 return Found;
389}
390
John McCallf6c8a4e2009-11-10 07:01:13 +0000391// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000392static bool
John McCall5cebab12009-11-18 07:57:50 +0000393CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCall27b18f82009-11-17 02:14:36 +0000394 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000395
396 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
397
John McCallf6c8a4e2009-11-10 07:01:13 +0000398 // Perform direct name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000399 bool Found = LookupDirect(R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000400
John McCallf6c8a4e2009-11-10 07:01:13 +0000401 // Perform direct name lookup into the namespaces nominated by the
402 // using directives whose common ancestor is this namespace.
403 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
404 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000405
John McCallf6c8a4e2009-11-10 07:01:13 +0000406 for (; UI != UEnd; ++UI)
John McCall27b18f82009-11-17 02:14:36 +0000407 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000408 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000409
410 R.resolveKind();
411
412 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000413}
414
415static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000416 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000417 return Ctx->isFileContext();
418 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000419}
Douglas Gregored8f2882009-01-30 01:04:22 +0000420
Douglas Gregor7f737c02009-09-10 16:57:35 +0000421// Find the next outer declaration context corresponding to this scope.
422static DeclContext *findOuterContext(Scope *S) {
423 for (S = S->getParent(); S; S = S->getParent())
424 if (S->getEntity())
425 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
426
427 return 0;
428}
429
John McCall27b18f82009-11-17 02:14:36 +0000430bool Sema::CppLookupName(LookupResult &R, Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000431 assert(getLangOptions().CPlusPlus &&
432 "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000433 LookupNameKind NameKind = R.getLookupKind();
Mike Stump11289f42009-09-09 15:08:12 +0000434 unsigned IDNS
Douglas Gregor2ada0482009-02-04 17:27:36 +0000435 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
John McCallaa74a0c2009-08-28 07:59:38 +0000436
437 // If we're testing for redeclarations, also look in the friend namespaces.
John McCall27b18f82009-11-17 02:14:36 +0000438 if (R.isForRedeclaration()) {
John McCallaa74a0c2009-08-28 07:59:38 +0000439 if (IDNS & Decl::IDNS_Tag) IDNS |= Decl::IDNS_TagFriend;
440 if (IDNS & Decl::IDNS_Ordinary) IDNS |= Decl::IDNS_OrdinaryFriend;
441 }
442
John McCall27b18f82009-11-17 02:14:36 +0000443 R.setIdentifierNamespace(IDNS);
444
445 DeclarationName Name = R.getLookupName();
446
Douglas Gregor889ceb72009-02-03 19:21:40 +0000447 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000448 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000449 I = IdResolver.begin(Name),
450 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000451
Douglas Gregor889ceb72009-02-03 19:21:40 +0000452 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000453 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000454 // ...During unqualified name lookup (3.4.1), the names appear as if
455 // they were declared in the nearest enclosing namespace which contains
456 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000457 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000458 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000459 //
460 // For example:
461 // namespace A { int i; }
462 // void foo() {
463 // int i;
464 // {
465 // using namespace A;
466 // ++i; // finds local 'i', A::i appears at global scope
467 // }
468 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000469 //
Douglas Gregor700792c2009-02-05 19:25:20 +0000470 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000471 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000472 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000473 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000474 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
John McCall9f3059a2009-10-09 21:13:30 +0000475 Found = true;
476 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000477 }
478 }
John McCall9f3059a2009-10-09 21:13:30 +0000479 if (Found) {
480 R.resolveKind();
481 return true;
482 }
483
Douglas Gregor700792c2009-02-05 19:25:20 +0000484 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregor7f737c02009-09-10 16:57:35 +0000485 DeclContext *OuterCtx = findOuterContext(S);
486 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
487 Ctx = Ctx->getLookupParent()) {
Douglas Gregora64c1e52009-12-08 15:38:36 +0000488 // We do not directly look into function or method contexts
489 // (since all local variables are found via the identifier
490 // changes) or in transparent contexts (since those entities
491 // will be found in the nearest enclosing non-transparent
492 // context).
493 if (Ctx->isFunctionOrMethod() || Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000494 continue;
495
496 // Perform qualified name lookup into this context.
497 // FIXME: In some cases, we know that every name that could be found by
498 // this qualified name lookup will also be on the identifier chain. For
499 // example, inside a class without any base classes, we never need to
500 // perform qualified lookup because all of the members are on top of the
501 // identifier chain.
John McCall27b18f82009-11-17 02:14:36 +0000502 if (LookupQualifiedName(R, Ctx))
John McCall9f3059a2009-10-09 21:13:30 +0000503 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000504 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000505 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000506 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000507
John McCallf6c8a4e2009-11-10 07:01:13 +0000508 // Stop if we ran out of scopes.
509 // FIXME: This really, really shouldn't be happening.
510 if (!S) return false;
511
Douglas Gregor700792c2009-02-05 19:25:20 +0000512 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000513 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000514 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000515 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
516 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000517
John McCallf6c8a4e2009-11-10 07:01:13 +0000518 UnqualUsingDirectiveSet UDirs;
519 UDirs.visitScopeChain(Initial, S);
520 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000521
Douglas Gregor700792c2009-02-05 19:25:20 +0000522 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000523 // Unqualified name lookup in C++ requires looking into scopes
524 // that aren't strictly lexical, and therefore we walk through the
525 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000526
Douglas Gregor889ceb72009-02-03 19:21:40 +0000527 for (; S; S = S->getParent()) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000528 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregorf2270432009-08-24 18:55:03 +0000529 if (Ctx->isTransparentContext())
530 continue;
531
Douglas Gregor700792c2009-02-05 19:25:20 +0000532 assert(Ctx && Ctx->isFileContext() &&
533 "We should have been looking only at file context here already.");
Douglas Gregor889ceb72009-02-03 19:21:40 +0000534
535 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000536 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000537 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000538 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
539 // We found something. Look for anything else in our scope
540 // with this same name and in an acceptable identifier
541 // namespace, so that we can construct an overload set if we
542 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000543 Found = true;
544 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000545 }
546 }
547
Douglas Gregor700792c2009-02-05 19:25:20 +0000548 // Look into context considering using-directives.
John McCall27b18f82009-11-17 02:14:36 +0000549 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
John McCall9f3059a2009-10-09 21:13:30 +0000550 Found = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000551
John McCall9f3059a2009-10-09 21:13:30 +0000552 if (Found) {
553 R.resolveKind();
554 return true;
555 }
556
John McCall27b18f82009-11-17 02:14:36 +0000557 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000558 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000559 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000560
John McCall9f3059a2009-10-09 21:13:30 +0000561 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000562}
563
Douglas Gregor34074322009-01-14 22:20:51 +0000564/// @brief Perform unqualified name lookup starting from a given
565/// scope.
566///
567/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
568/// used to find names within the current scope. For example, 'x' in
569/// @code
570/// int x;
571/// int f() {
572/// return x; // unqualified name look finds 'x' in the global scope
573/// }
574/// @endcode
575///
576/// Different lookup criteria can find different names. For example, a
577/// particular scope can have both a struct and a function of the same
578/// name, and each can be found by certain lookup criteria. For more
579/// information about lookup criteria, see the documentation for the
580/// class LookupCriteria.
581///
582/// @param S The scope from which unqualified name lookup will
583/// begin. If the lookup criteria permits, name lookup may also search
584/// in the parent scopes.
585///
586/// @param Name The name of the entity that we are searching for.
587///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000588/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000589/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000590/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000591///
592/// @returns The result of name lookup, which includes zero or more
593/// declarations and possibly additional information used to diagnose
594/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000595bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
596 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +0000597 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000598
John McCall27b18f82009-11-17 02:14:36 +0000599 LookupNameKind NameKind = R.getLookupKind();
600
Douglas Gregor34074322009-01-14 22:20:51 +0000601 if (!getLangOptions().CPlusPlus) {
602 // Unqualified name lookup in C/Objective-C is purely lexical, so
603 // search in the declarations attached to the name.
Douglas Gregored8f2882009-01-30 01:04:22 +0000604 unsigned IDNS = 0;
605 switch (NameKind) {
606 case Sema::LookupOrdinaryName:
607 IDNS = Decl::IDNS_Ordinary;
608 break;
Douglas Gregor34074322009-01-14 22:20:51 +0000609
Douglas Gregored8f2882009-01-30 01:04:22 +0000610 case Sema::LookupTagName:
611 IDNS = Decl::IDNS_Tag;
612 break;
613
614 case Sema::LookupMemberName:
615 IDNS = Decl::IDNS_Member;
616 break;
617
Douglas Gregor94eabf32009-02-04 16:44:47 +0000618 case Sema::LookupOperatorName:
Douglas Gregored8f2882009-01-30 01:04:22 +0000619 case Sema::LookupNestedNameSpecifierName:
620 case Sema::LookupNamespaceName:
John McCall84d87672009-12-10 09:41:52 +0000621 case Sema::LookupUsingDeclName:
Douglas Gregored8f2882009-01-30 01:04:22 +0000622 assert(false && "C does not perform these kinds of name lookup");
623 break;
Douglas Gregoreddf4332009-02-24 20:03:32 +0000624
625 case Sema::LookupRedeclarationWithLinkage:
626 // Find the nearest non-transparent declaration scope.
627 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000628 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000629 static_cast<DeclContext *>(S->getEntity())
630 ->isTransparentContext()))
631 S = S->getParent();
632 IDNS = Decl::IDNS_Ordinary;
633 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000634
Douglas Gregor79947a22009-04-24 00:11:27 +0000635 case Sema::LookupObjCProtocolName:
636 IDNS = Decl::IDNS_ObjCProtocol;
637 break;
638
639 case Sema::LookupObjCImplementationName:
640 IDNS = Decl::IDNS_ObjCImplementation;
641 break;
Mike Stump11289f42009-09-09 15:08:12 +0000642
Douglas Gregor79947a22009-04-24 00:11:27 +0000643 case Sema::LookupObjCCategoryImplName:
644 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000645 break;
Douglas Gregored8f2882009-01-30 01:04:22 +0000646 }
647
Douglas Gregor34074322009-01-14 22:20:51 +0000648 // Scan up the scope chain looking for a decl that matches this
649 // identifier that is in the appropriate namespace. This search
650 // should not take long, as shadowing of names is uncommon, and
651 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000652 bool LeftStartingScope = false;
653
Douglas Gregored8f2882009-01-30 01:04:22 +0000654 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000655 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000656 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000657 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000658 if (NameKind == LookupRedeclarationWithLinkage) {
659 // Determine whether this (or a previous) declaration is
660 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000661 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000662 LeftStartingScope = true;
663
664 // If we found something outside of our starting scope that
665 // does not have linkage, skip it.
666 if (LeftStartingScope && !((*I)->hasLinkage()))
667 continue;
668 }
669
John McCall9f3059a2009-10-09 21:13:30 +0000670 R.addDecl(*I);
671
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000672 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000673 // If this declaration has the "overloadable" attribute, we
674 // might have a set of overloaded functions.
675
676 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000677 while (!(S->getFlags() & Scope::DeclScope) ||
678 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000679 S = S->getParent();
680
681 // Find the last declaration in this scope (with the same
682 // name, naturally).
683 IdentifierResolver::iterator LastI = I;
684 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000685 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000686 break;
John McCall9f3059a2009-10-09 21:13:30 +0000687 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000688 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000689 }
690
John McCall9f3059a2009-10-09 21:13:30 +0000691 R.resolveKind();
692
693 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000694 }
Douglas Gregor34074322009-01-14 22:20:51 +0000695 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000696 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000697 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +0000698 return true;
Douglas Gregor34074322009-01-14 22:20:51 +0000699 }
700
701 // If we didn't find a use of this identifier, and if the identifier
702 // corresponds to a compiler builtin, create the decl object for the builtin
703 // now, injecting it into translation unit scope, and return it.
Mike Stump11289f42009-09-09 15:08:12 +0000704 if (NameKind == LookupOrdinaryName ||
Douglas Gregoreddf4332009-02-24 20:03:32 +0000705 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor34074322009-01-14 22:20:51 +0000706 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000707 if (II && AllowBuiltinCreation) {
Douglas Gregor34074322009-01-14 22:20:51 +0000708 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000709 if (unsigned BuiltinID = II->getBuiltinID()) {
710 // In C++, we don't have any predefined library functions like
711 // 'malloc'. Instead, we'll just error.
Mike Stump11289f42009-09-09 15:08:12 +0000712 if (getLangOptions().CPlusPlus &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000713 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCall9f3059a2009-10-09 21:13:30 +0000714 return false;
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000715
John McCall9f3059a2009-10-09 21:13:30 +0000716 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCall27b18f82009-11-17 02:14:36 +0000717 S, R.isForRedeclaration(),
718 R.getNameLoc());
John McCall9f3059a2009-10-09 21:13:30 +0000719 if (D) R.addDecl(D);
720 return (D != NULL);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000721 }
Douglas Gregor34074322009-01-14 22:20:51 +0000722 }
Douglas Gregor34074322009-01-14 22:20:51 +0000723 }
John McCall9f3059a2009-10-09 21:13:30 +0000724 return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000725}
726
John McCall6538c932009-10-10 05:48:19 +0000727/// @brief Perform qualified name lookup in the namespaces nominated by
728/// using directives by the given context.
729///
730/// C++98 [namespace.qual]p2:
731/// Given X::m (where X is a user-declared namespace), or given ::m
732/// (where X is the global namespace), let S be the set of all
733/// declarations of m in X and in the transitive closure of all
734/// namespaces nominated by using-directives in X and its used
735/// namespaces, except that using-directives are ignored in any
736/// namespace, including X, directly containing one or more
737/// declarations of m. No namespace is searched more than once in
738/// the lookup of a name. If S is the empty set, the program is
739/// ill-formed. Otherwise, if S has exactly one member, or if the
740/// context of the reference is a using-declaration
741/// (namespace.udecl), S is the required set of declarations of
742/// m. Otherwise if the use of m is not one that allows a unique
743/// declaration to be chosen from S, the program is ill-formed.
744/// C++98 [namespace.qual]p5:
745/// During the lookup of a qualified namespace member name, if the
746/// lookup finds more than one declaration of the member, and if one
747/// declaration introduces a class name or enumeration name and the
748/// other declarations either introduce the same object, the same
749/// enumerator or a set of functions, the non-type name hides the
750/// class or enumeration name if and only if the declarations are
751/// from the same namespace; otherwise (the declarations are from
752/// different namespaces), the program is ill-formed.
John McCall5cebab12009-11-18 07:57:50 +0000753static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +0000754 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +0000755 assert(StartDC->isFileContext() && "start context is not a file context");
756
757 DeclContext::udir_iterator I = StartDC->using_directives_begin();
758 DeclContext::udir_iterator E = StartDC->using_directives_end();
759
760 if (I == E) return false;
761
762 // We have at least added all these contexts to the queue.
763 llvm::DenseSet<DeclContext*> Visited;
764 Visited.insert(StartDC);
765
766 // We have not yet looked into these namespaces, much less added
767 // their "using-children" to the queue.
768 llvm::SmallVector<NamespaceDecl*, 8> Queue;
769
770 // We have already looked into the initial namespace; seed the queue
771 // with its using-children.
772 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +0000773 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +0000774 if (Visited.insert(ND).second)
775 Queue.push_back(ND);
776 }
777
778 // The easiest way to implement the restriction in [namespace.qual]p5
779 // is to check whether any of the individual results found a tag
780 // and, if so, to declare an ambiguity if the final result is not
781 // a tag.
782 bool FoundTag = false;
783 bool FoundNonTag = false;
784
John McCall5cebab12009-11-18 07:57:50 +0000785 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +0000786
787 bool Found = false;
788 while (!Queue.empty()) {
789 NamespaceDecl *ND = Queue.back();
790 Queue.pop_back();
791
792 // We go through some convolutions here to avoid copying results
793 // between LookupResults.
794 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +0000795 LookupResult &DirectR = UseLocal ? LocalR : R;
John McCall27b18f82009-11-17 02:14:36 +0000796 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +0000797
798 if (FoundDirect) {
799 // First do any local hiding.
800 DirectR.resolveKind();
801
802 // If the local result is a tag, remember that.
803 if (DirectR.isSingleTagDecl())
804 FoundTag = true;
805 else
806 FoundNonTag = true;
807
808 // Append the local results to the total results if necessary.
809 if (UseLocal) {
810 R.addAllDecls(LocalR);
811 LocalR.clear();
812 }
813 }
814
815 // If we find names in this namespace, ignore its using directives.
816 if (FoundDirect) {
817 Found = true;
818 continue;
819 }
820
821 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
822 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
823 if (Visited.insert(Nom).second)
824 Queue.push_back(Nom);
825 }
826 }
827
828 if (Found) {
829 if (FoundTag && FoundNonTag)
830 R.setAmbiguousQualifiedTagHiding();
831 else
832 R.resolveKind();
833 }
834
835 return Found;
836}
837
Douglas Gregor34074322009-01-14 22:20:51 +0000838/// @brief Perform qualified name lookup into a given context.
839///
840/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
841/// names when the context of those names is explicit specified, e.g.,
842/// "std::vector" or "x->member".
843///
844/// Different lookup criteria can find different names. For example, a
845/// particular scope can have both a struct and a function of the same
846/// name, and each can be found by certain lookup criteria. For more
847/// information about lookup criteria, see the documentation for the
848/// class LookupCriteria.
849///
850/// @param LookupCtx The context in which qualified name lookup will
851/// search. If the lookup criteria permits, name lookup may also search
852/// in the parent contexts or (for C++ classes) base classes.
853///
854/// @param Name The name of the entity that we are searching for.
855///
856/// @param Criteria The criteria that this routine will use to
857/// determine which names are visible and which names will be
858/// found. Note that name lookup will find a name that is visible by
859/// the given criteria, but the entity itself may not be semantically
860/// correct or even the kind of entity expected based on the
861/// lookup. For example, searching for a nested-name-specifier name
862/// might result in an EnumDecl, which is visible but is not permitted
863/// as a nested-name-specifier in C++03.
864///
865/// @returns The result of name lookup, which includes zero or more
866/// declarations and possibly additional information used to diagnose
867/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000868bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx) {
Douglas Gregor34074322009-01-14 22:20:51 +0000869 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +0000870
John McCall27b18f82009-11-17 02:14:36 +0000871 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +0000872 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000873
Douglas Gregor34074322009-01-14 22:20:51 +0000874 // If we're performing qualified name lookup (e.g., lookup into a
875 // struct), find fields as part of ordinary name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000876 LookupNameKind NameKind = R.getLookupKind();
Douglas Gregored8f2882009-01-30 01:04:22 +0000877 unsigned IDNS
Mike Stump11289f42009-09-09 15:08:12 +0000878 = getIdentifierNamespacesFromLookupNameKind(NameKind,
Douglas Gregored8f2882009-01-30 01:04:22 +0000879 getLangOptions().CPlusPlus);
880 if (NameKind == LookupOrdinaryName)
881 IDNS |= Decl::IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000882
John McCall27b18f82009-11-17 02:14:36 +0000883 R.setIdentifierNamespace(IDNS);
884
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000885 // Make sure that the declaration context is complete.
886 assert((!isa<TagDecl>(LookupCtx) ||
887 LookupCtx->isDependentContext() ||
888 cast<TagDecl>(LookupCtx)->isDefinition() ||
889 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
890 ->isBeingDefined()) &&
891 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +0000892
Douglas Gregor34074322009-01-14 22:20:51 +0000893 // Perform qualified name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000894 if (LookupDirect(R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +0000895 R.resolveKind();
896 return true;
897 }
Douglas Gregor34074322009-01-14 22:20:51 +0000898
John McCall6538c932009-10-10 05:48:19 +0000899 // Don't descend into implied contexts for redeclarations.
900 // C++98 [namespace.qual]p6:
901 // In a declaration for a namespace member in which the
902 // declarator-id is a qualified-id, given that the qualified-id
903 // for the namespace member has the form
904 // nested-name-specifier unqualified-id
905 // the unqualified-id shall name a member of the namespace
906 // designated by the nested-name-specifier.
907 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +0000908 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +0000909 return false;
910
John McCall27b18f82009-11-17 02:14:36 +0000911 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +0000912 if (LookupCtx->isFileContext())
John McCall27b18f82009-11-17 02:14:36 +0000913 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +0000914
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000915 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +0000916 // classes, we're done.
John McCall6538c932009-10-10 05:48:19 +0000917 if (!isa<CXXRecordDecl>(LookupCtx))
John McCall9f3059a2009-10-09 21:13:30 +0000918 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000919
920 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +0000921 CXXRecordDecl *LookupRec = cast<CXXRecordDecl>(LookupCtx);
922 CXXBasePaths Paths;
923 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000924
925 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +0000926 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +0000927 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000928 case LookupOrdinaryName:
929 case LookupMemberName:
930 case LookupRedeclarationWithLinkage:
931 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
932 break;
933
934 case LookupTagName:
935 BaseCallback = &CXXRecordDecl::FindTagMember;
936 break;
John McCall84d87672009-12-10 09:41:52 +0000937
938 case LookupUsingDeclName:
939 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +0000940
941 case LookupOperatorName:
942 case LookupNamespaceName:
943 case LookupObjCProtocolName:
944 case LookupObjCImplementationName:
945 case LookupObjCCategoryImplName:
946 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +0000947 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000948
949 case LookupNestedNameSpecifierName:
950 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
951 break;
952 }
953
John McCall27b18f82009-11-17 02:14:36 +0000954 if (!LookupRec->lookupInBases(BaseCallback,
955 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +0000956 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000957
958 // C++ [class.member.lookup]p2:
959 // [...] If the resulting set of declarations are not all from
960 // sub-objects of the same type, or the set has a nonstatic member
961 // and includes members from distinct sub-objects, there is an
962 // ambiguity and the program is ill-formed. Otherwise that set is
963 // the result of the lookup.
964 // FIXME: support using declarations!
965 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +0000966 int SubobjectNumber = 0;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000967 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000968 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000969 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000970
971 // Determine whether we're looking at a distinct sub-object or not.
972 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +0000973 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000974 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
975 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +0000976 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000977 != Context.getCanonicalType(PathElement.Base->getType())) {
978 // We found members of the given name in two subobjects of
979 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +0000980 R.setAmbiguousBaseSubobjectTypes(Paths);
981 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000982 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
983 // We have a different subobject of the same type.
984
985 // C++ [class.member.lookup]p5:
986 // A static member, a nested type or an enumerator defined in
987 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +0000988 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000989 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000990 if (isa<VarDecl>(FirstDecl) ||
991 isa<TypeDecl>(FirstDecl) ||
992 isa<EnumConstantDecl>(FirstDecl))
993 continue;
994
995 if (isa<CXXMethodDecl>(FirstDecl)) {
996 // Determine whether all of the methods are static.
997 bool AllMethodsAreStatic = true;
998 for (DeclContext::lookup_iterator Func = Path->Decls.first;
999 Func != Path->Decls.second; ++Func) {
1000 if (!isa<CXXMethodDecl>(*Func)) {
1001 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1002 break;
1003 }
1004
1005 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1006 AllMethodsAreStatic = false;
1007 break;
1008 }
1009 }
1010
1011 if (AllMethodsAreStatic)
1012 continue;
1013 }
1014
1015 // We have found a nonstatic member name in multiple, distinct
1016 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001017 R.setAmbiguousBaseSubobjects(Paths);
1018 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001019 }
1020 }
1021
1022 // Lookup in a base class succeeded; return these results.
1023
John McCall9f3059a2009-10-09 21:13:30 +00001024 DeclContext::lookup_iterator I, E;
1025 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I)
1026 R.addDecl(*I);
1027 R.resolveKind();
1028 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001029}
1030
1031/// @brief Performs name lookup for a name that was parsed in the
1032/// source code, and may contain a C++ scope specifier.
1033///
1034/// This routine is a convenience routine meant to be called from
1035/// contexts that receive a name and an optional C++ scope specifier
1036/// (e.g., "N::M::x"). It will then perform either qualified or
1037/// unqualified name lookup (with LookupQualifiedName or LookupName,
1038/// respectively) on the given name and return those results.
1039///
1040/// @param S The scope from which unqualified name lookup will
1041/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001042///
Douglas Gregore861bac2009-08-25 22:51:20 +00001043/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001044///
1045/// @param Name The name of the entity that name lookup will
1046/// search for.
1047///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001048/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001049/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001050/// C library functions (like "malloc") are implicitly declared.
1051///
Douglas Gregore861bac2009-08-25 22:51:20 +00001052/// @param EnteringContext Indicates whether we are going to enter the
1053/// context of the scope-specifier SS (if present).
1054///
John McCall9f3059a2009-10-09 21:13:30 +00001055/// @returns True if any decls were found (but possibly ambiguous)
1056bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001057 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001058 if (SS && SS->isInvalid()) {
1059 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001060 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001061 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001062 }
Mike Stump11289f42009-09-09 15:08:12 +00001063
Douglas Gregore861bac2009-08-25 22:51:20 +00001064 if (SS && SS->isSet()) {
1065 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001066 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001067 // contex, and will perform name lookup in that context.
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001068 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCall9f3059a2009-10-09 21:13:30 +00001069 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001070
John McCall27b18f82009-11-17 02:14:36 +00001071 R.setContextRange(SS->getRange());
1072
1073 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001074 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001075
Douglas Gregore861bac2009-08-25 22:51:20 +00001076 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001077 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001078 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001079 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001080 }
1081
Mike Stump11289f42009-09-09 15:08:12 +00001082 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001083 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001084}
1085
Douglas Gregor889ceb72009-02-03 19:21:40 +00001086
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001087/// @brief Produce a diagnostic describing the ambiguity that resulted
1088/// from name lookup.
1089///
1090/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001091///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001092/// @param Name The name of the entity that name lookup was
1093/// searching for.
1094///
1095/// @param NameLoc The location of the name within the source code.
1096///
1097/// @param LookupRange A source range that provides more
1098/// source-location information concerning the lookup itself. For
1099/// example, this range might highlight a nested-name-specifier that
1100/// precedes the name.
1101///
1102/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001103bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001104 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1105
John McCall27b18f82009-11-17 02:14:36 +00001106 DeclarationName Name = Result.getLookupName();
1107 SourceLocation NameLoc = Result.getNameLoc();
1108 SourceRange LookupRange = Result.getContextRange();
1109
John McCall6538c932009-10-10 05:48:19 +00001110 switch (Result.getAmbiguityKind()) {
1111 case LookupResult::AmbiguousBaseSubobjects: {
1112 CXXBasePaths *Paths = Result.getBasePaths();
1113 QualType SubobjectType = Paths->front().back().Base->getType();
1114 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1115 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1116 << LookupRange;
1117
1118 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1119 while (isa<CXXMethodDecl>(*Found) &&
1120 cast<CXXMethodDecl>(*Found)->isStatic())
1121 ++Found;
1122
1123 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1124
1125 return true;
1126 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001127
John McCall6538c932009-10-10 05:48:19 +00001128 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001129 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1130 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001131
1132 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001133 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001134 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1135 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001136 Path != PathEnd; ++Path) {
1137 Decl *D = *Path->Decls.first;
1138 if (DeclsPrinted.insert(D).second)
1139 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1140 }
1141
Douglas Gregor1c846b02009-01-16 00:38:09 +00001142 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001143 }
1144
John McCall6538c932009-10-10 05:48:19 +00001145 case LookupResult::AmbiguousTagHiding: {
1146 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001147
John McCall6538c932009-10-10 05:48:19 +00001148 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1149
1150 LookupResult::iterator DI, DE = Result.end();
1151 for (DI = Result.begin(); DI != DE; ++DI)
1152 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1153 TagDecls.insert(TD);
1154 Diag(TD->getLocation(), diag::note_hidden_tag);
1155 }
1156
1157 for (DI = Result.begin(); DI != DE; ++DI)
1158 if (!isa<TagDecl>(*DI))
1159 Diag((*DI)->getLocation(), diag::note_hiding_object);
1160
1161 // For recovery purposes, go ahead and implement the hiding.
1162 Result.hideDecls(TagDecls);
1163
1164 return true;
1165 }
1166
1167 case LookupResult::AmbiguousReference: {
1168 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001169
John McCall6538c932009-10-10 05:48:19 +00001170 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1171 for (; DI != DE; ++DI)
1172 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001173
John McCall6538c932009-10-10 05:48:19 +00001174 return true;
1175 }
1176 }
1177
1178 llvm::llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001179 return true;
1180}
Douglas Gregore254f902009-02-04 00:32:51 +00001181
Mike Stump11289f42009-09-09 15:08:12 +00001182static void
1183addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001184 ASTContext &Context,
1185 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001186 Sema::AssociatedClassSet &AssociatedClasses);
1187
1188static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1189 DeclContext *Ctx) {
1190 if (Ctx->isFileContext())
1191 Namespaces.insert(Ctx);
1192}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001193
Mike Stump11289f42009-09-09 15:08:12 +00001194// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001195// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001196static void
1197addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001198 ASTContext &Context,
1199 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001200 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001201 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001202 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001203 switch (Arg.getKind()) {
1204 case TemplateArgument::Null:
1205 break;
Mike Stump11289f42009-09-09 15:08:12 +00001206
Douglas Gregor197e5f72009-07-08 07:51:57 +00001207 case TemplateArgument::Type:
1208 // [...] the namespaces and classes associated with the types of the
1209 // template arguments provided for template type parameters (excluding
1210 // template template parameters)
1211 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1212 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001213 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001214 break;
Mike Stump11289f42009-09-09 15:08:12 +00001215
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001216 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001217 // [...] the namespaces in which any template template arguments are
1218 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001219 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001220 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001221 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001222 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001223 DeclContext *Ctx = ClassTemplate->getDeclContext();
1224 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1225 AssociatedClasses.insert(EnclosingClass);
1226 // Add the associated namespace for this class.
1227 while (Ctx->isRecord())
1228 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001229 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001230 }
1231 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001232 }
1233
1234 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001235 case TemplateArgument::Integral:
1236 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001237 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001238 // associated namespaces. ]
1239 break;
Mike Stump11289f42009-09-09 15:08:12 +00001240
Douglas Gregor197e5f72009-07-08 07:51:57 +00001241 case TemplateArgument::Pack:
1242 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1243 PEnd = Arg.pack_end();
1244 P != PEnd; ++P)
1245 addAssociatedClassesAndNamespaces(*P, Context,
1246 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001247 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001248 break;
1249 }
1250}
1251
Douglas Gregore254f902009-02-04 00:32:51 +00001252// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001253// argument-dependent lookup with an argument of class type
1254// (C++ [basic.lookup.koenig]p2).
1255static void
1256addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregore254f902009-02-04 00:32:51 +00001257 ASTContext &Context,
1258 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001259 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001260 // C++ [basic.lookup.koenig]p2:
1261 // [...]
1262 // -- If T is a class type (including unions), its associated
1263 // classes are: the class itself; the class of which it is a
1264 // member, if any; and its direct and indirect base
1265 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001266 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001267
1268 // Add the class of which it is a member, if any.
1269 DeclContext *Ctx = Class->getDeclContext();
1270 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1271 AssociatedClasses.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001272 // Add the associated namespace for this class.
1273 while (Ctx->isRecord())
1274 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001275 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001276
Douglas Gregore254f902009-02-04 00:32:51 +00001277 // Add the class itself. If we've already seen this class, we don't
1278 // need to visit base classes.
1279 if (!AssociatedClasses.insert(Class))
1280 return;
1281
Mike Stump11289f42009-09-09 15:08:12 +00001282 // -- If T is a template-id, its associated namespaces and classes are
1283 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001284 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001285 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001286 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001287 // namespaces in which any template template arguments are defined; and
1288 // the classes in which any member templates used as template template
1289 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001290 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001291 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001292 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1293 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1294 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1295 AssociatedClasses.insert(EnclosingClass);
1296 // Add the associated namespace for this class.
1297 while (Ctx->isRecord())
1298 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001299 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001300
Douglas Gregor197e5f72009-07-08 07:51:57 +00001301 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1302 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1303 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1304 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001305 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001306 }
Mike Stump11289f42009-09-09 15:08:12 +00001307
Douglas Gregore254f902009-02-04 00:32:51 +00001308 // Add direct and indirect base classes along with their associated
1309 // namespaces.
1310 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1311 Bases.push_back(Class);
1312 while (!Bases.empty()) {
1313 // Pop this class off the stack.
1314 Class = Bases.back();
1315 Bases.pop_back();
1316
1317 // Visit the base classes.
1318 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1319 BaseEnd = Class->bases_end();
1320 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001321 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001322 // In dependent contexts, we do ADL twice, and the first time around,
1323 // the base type might be a dependent TemplateSpecializationType, or a
1324 // TemplateTypeParmType. If that happens, simply ignore it.
1325 // FIXME: If we want to support export, we probably need to add the
1326 // namespace of the template in a TemplateSpecializationType, or even
1327 // the classes and namespaces of known non-dependent arguments.
1328 if (!BaseType)
1329 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001330 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1331 if (AssociatedClasses.insert(BaseDecl)) {
1332 // Find the associated namespace for this base class.
1333 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1334 while (BaseCtx->isRecord())
1335 BaseCtx = BaseCtx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001336 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001337
1338 // Make sure we visit the bases of this base class.
1339 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1340 Bases.push_back(BaseDecl);
1341 }
1342 }
1343 }
1344}
1345
1346// \brief Add the associated classes and namespaces for
1347// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001348// (C++ [basic.lookup.koenig]p2).
1349static void
1350addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregore254f902009-02-04 00:32:51 +00001351 ASTContext &Context,
1352 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001353 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001354 // C++ [basic.lookup.koenig]p2:
1355 //
1356 // For each argument type T in the function call, there is a set
1357 // of zero or more associated namespaces and a set of zero or more
1358 // associated classes to be considered. The sets of namespaces and
1359 // classes is determined entirely by the types of the function
1360 // arguments (and the namespace of any template template
1361 // argument). Typedef names and using-declarations used to specify
1362 // the types do not contribute to this set. The sets of namespaces
1363 // and classes are determined in the following way:
1364 T = Context.getCanonicalType(T).getUnqualifiedType();
1365
1366 // -- If T is a pointer to U or an array of U, its associated
Mike Stump11289f42009-09-09 15:08:12 +00001367 // namespaces and classes are those associated with U.
Douglas Gregore254f902009-02-04 00:32:51 +00001368 //
1369 // We handle this by unwrapping pointer and array types immediately,
1370 // to avoid unnecessary recursion.
1371 while (true) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001372 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001373 T = Ptr->getPointeeType();
1374 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1375 T = Ptr->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001376 else
Douglas Gregore254f902009-02-04 00:32:51 +00001377 break;
1378 }
1379
1380 // -- If T is a fundamental type, its associated sets of
1381 // namespaces and classes are both empty.
John McCall9dd450b2009-09-21 23:43:11 +00001382 if (T->getAs<BuiltinType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001383 return;
1384
1385 // -- If T is a class type (including unions), its associated
1386 // classes are: the class itself; the class of which it is a
1387 // member, if any; and its direct and indirect base
1388 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001389 // which its associated classes are defined.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001390 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump11289f42009-09-09 15:08:12 +00001391 if (CXXRecordDecl *ClassDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001392 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001393 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1394 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001395 AssociatedClasses);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001396 return;
1397 }
Douglas Gregore254f902009-02-04 00:32:51 +00001398
1399 // -- If T is an enumeration type, its associated namespace is
1400 // the namespace in which it is defined. If it is class
1401 // member, its associated class is the member’s class; else
Mike Stump11289f42009-09-09 15:08:12 +00001402 // it has no associated class.
John McCall9dd450b2009-09-21 23:43:11 +00001403 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001404 EnumDecl *Enum = EnumT->getDecl();
1405
1406 DeclContext *Ctx = Enum->getDeclContext();
1407 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1408 AssociatedClasses.insert(EnclosingClass);
1409
1410 // Add the associated namespace for this class.
1411 while (Ctx->isRecord())
1412 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001413 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001414
1415 return;
1416 }
1417
1418 // -- If T is a function type, its associated namespaces and
1419 // classes are those associated with the function parameter
1420 // types and those associated with the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001421 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001422 // Return type
John McCall9dd450b2009-09-21 23:43:11 +00001423 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregore254f902009-02-04 00:32:51 +00001424 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001425 AssociatedNamespaces, AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001426
John McCall9dd450b2009-09-21 23:43:11 +00001427 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregore254f902009-02-04 00:32:51 +00001428 if (!Proto)
1429 return;
1430
1431 // Argument types
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001432 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001433 ArgEnd = Proto->arg_type_end();
Douglas Gregore254f902009-02-04 00:32:51 +00001434 Arg != ArgEnd; ++Arg)
1435 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallc7e8e792009-08-07 22:18:02 +00001436 AssociatedNamespaces, AssociatedClasses);
Mike Stump11289f42009-09-09 15:08:12 +00001437
Douglas Gregore254f902009-02-04 00:32:51 +00001438 return;
1439 }
1440
1441 // -- If T is a pointer to a member function of a class X, its
1442 // associated namespaces and classes are those associated
1443 // with the function parameter types and return type,
Mike Stump11289f42009-09-09 15:08:12 +00001444 // together with those associated with X.
Douglas Gregore254f902009-02-04 00:32:51 +00001445 //
1446 // -- If T is a pointer to a data member of class X, its
1447 // associated namespaces and classes are those associated
1448 // with the member type together with those associated with
Mike Stump11289f42009-09-09 15:08:12 +00001449 // X.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001450 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001451 // Handle the type that the pointer to member points to.
1452 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1453 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001454 AssociatedNamespaces,
1455 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001456
1457 // Handle the class type into which this points.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001458 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001459 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1460 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001461 AssociatedNamespaces,
1462 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001463
1464 return;
1465 }
1466
1467 // FIXME: What about block pointers?
1468 // FIXME: What about Objective-C message sends?
1469}
1470
1471/// \brief Find the associated classes and namespaces for
1472/// argument-dependent lookup for a call with the given set of
1473/// arguments.
1474///
1475/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001476/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001477/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001478void
Douglas Gregore254f902009-02-04 00:32:51 +00001479Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1480 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001481 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001482 AssociatedNamespaces.clear();
1483 AssociatedClasses.clear();
1484
1485 // C++ [basic.lookup.koenig]p2:
1486 // For each argument type T in the function call, there is a set
1487 // of zero or more associated namespaces and a set of zero or more
1488 // associated classes to be considered. The sets of namespaces and
1489 // classes is determined entirely by the types of the function
1490 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001491 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001492 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1493 Expr *Arg = Args[ArgIdx];
1494
1495 if (Arg->getType() != Context.OverloadTy) {
1496 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001497 AssociatedNamespaces,
1498 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001499 continue;
1500 }
1501
1502 // [...] In addition, if the argument is the name or address of a
1503 // set of overloaded functions and/or function templates, its
1504 // associated classes and namespaces are the union of those
1505 // associated with each of the members of the set: the namespace
1506 // in which the function or function template is defined and the
1507 // classes and namespaces associated with its (non-dependent)
1508 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001509 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001510 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1511 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1512 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001513
John McCalld14a8642009-11-21 08:51:07 +00001514 // TODO: avoid the copies. This should be easy when the cases
1515 // share a storage implementation.
1516 llvm::SmallVector<NamedDecl*, 8> Functions;
1517
1518 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1519 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00001520 else
Douglas Gregore254f902009-02-04 00:32:51 +00001521 continue;
1522
John McCalld14a8642009-11-21 08:51:07 +00001523 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1524 E = Functions.end(); I != E; ++I) {
1525 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001526 if (!FDecl)
John McCalld14a8642009-11-21 08:51:07 +00001527 FDecl = cast<FunctionTemplateDecl>(*I)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001528
1529 // Add the namespace in which this function was defined. Note
1530 // that, if this is a member function, we do *not* consider the
1531 // enclosing namespace of its class.
1532 DeclContext *Ctx = FDecl->getDeclContext();
John McCallc7e8e792009-08-07 22:18:02 +00001533 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001534
1535 // Add the classes and namespaces associated with the parameter
1536 // types and return type of this function.
1537 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001538 AssociatedNamespaces,
1539 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001540 }
1541 }
1542}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001543
1544/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1545/// an acceptable non-member overloaded operator for a call whose
1546/// arguments have types T1 (and, if non-empty, T2). This routine
1547/// implements the check in C++ [over.match.oper]p3b2 concerning
1548/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001549static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001550IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1551 QualType T1, QualType T2,
1552 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001553 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1554 return true;
1555
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001556 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1557 return true;
1558
John McCall9dd450b2009-09-21 23:43:11 +00001559 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001560 if (Proto->getNumArgs() < 1)
1561 return false;
1562
1563 if (T1->isEnumeralType()) {
1564 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001565 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001566 return true;
1567 }
1568
1569 if (Proto->getNumArgs() < 2)
1570 return false;
1571
1572 if (!T2.isNull() && T2->isEnumeralType()) {
1573 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001574 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001575 return true;
1576 }
1577
1578 return false;
1579}
1580
John McCall5cebab12009-11-18 07:57:50 +00001581NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1582 LookupNameKind NameKind,
1583 RedeclarationKind Redecl) {
1584 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1585 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00001586 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00001587}
1588
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001589/// \brief Find the protocol with the given name, if any.
1590ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001591 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001592 return cast_or_null<ObjCProtocolDecl>(D);
1593}
1594
Douglas Gregor79947a22009-04-24 00:11:27 +00001595/// \brief Find the Objective-C category implementation with the given
1596/// name, if any.
1597ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001598 Decl *D = LookupSingleName(TUScope, II, LookupObjCCategoryImplName);
Douglas Gregor79947a22009-04-24 00:11:27 +00001599 return cast_or_null<ObjCCategoryImplDecl>(D);
1600}
1601
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001602void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001603 QualType T1, QualType T2,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001604 FunctionSet &Functions) {
1605 // C++ [over.match.oper]p3:
1606 // -- The set of non-member candidates is the result of the
1607 // unqualified lookup of operator@ in the context of the
1608 // expression according to the usual rules for name lookup in
1609 // unqualified function calls (3.4.2) except that all member
1610 // functions are ignored. However, if no operand has a class
1611 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001612 // that have a first parameter of type T1 or "reference to
1613 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001614 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001615 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001616 // when T2 is an enumeration type, are candidate functions.
1617 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00001618 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1619 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00001620
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001621 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1622
John McCall9f3059a2009-10-09 21:13:30 +00001623 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001624 return;
1625
1626 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1627 Op != OpEnd; ++Op) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001628 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001629 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1630 Functions.insert(FD); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001631 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor15448f82009-06-27 21:05:07 +00001632 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1633 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001634 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001635 // later?
1636 if (!FunTmpl->getDeclContext()->isRecord())
1637 Functions.insert(FunTmpl);
1638 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001639 }
1640}
1641
John McCallc7e8e792009-08-07 22:18:02 +00001642static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1643 Decl *D) {
1644 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1645 Functions.insert(Func);
1646 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1647 Functions.insert(FunTmpl);
1648}
1649
Sebastian Redlc057f422009-10-23 19:23:15 +00001650void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001651 Expr **Args, unsigned NumArgs,
1652 FunctionSet &Functions) {
1653 // Find all of the associated namespaces and classes based on the
1654 // arguments we have.
1655 AssociatedNamespaceSet AssociatedNamespaces;
1656 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00001657 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00001658 AssociatedNamespaces,
1659 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001660
Sebastian Redlc057f422009-10-23 19:23:15 +00001661 QualType T1, T2;
1662 if (Operator) {
1663 T1 = Args[0]->getType();
1664 if (NumArgs >= 2)
1665 T2 = Args[1]->getType();
1666 }
1667
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001668 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001669 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1670 // and let Y be the lookup set produced by argument dependent
1671 // lookup (defined as follows). If X contains [...] then Y is
1672 // empty. Otherwise Y is the set of declarations found in the
1673 // namespaces associated with the argument types as described
1674 // below. The set of declarations found by the lookup of the name
1675 // is the union of X and Y.
1676 //
1677 // Here, we compute Y and add its members to the overloaded
1678 // candidate set.
1679 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001680 NSEnd = AssociatedNamespaces.end();
1681 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001682 // When considering an associated namespace, the lookup is the
1683 // same as the lookup performed when the associated namespace is
1684 // used as a qualifier (3.4.3.2) except that:
1685 //
1686 // -- Any using-directives in the associated namespace are
1687 // ignored.
1688 //
John McCallc7e8e792009-08-07 22:18:02 +00001689 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001690 // associated classes are visible within their respective
1691 // namespaces even if they are not visible during an ordinary
1692 // lookup (11.4).
1693 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00001694 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCallc7e8e792009-08-07 22:18:02 +00001695 Decl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00001696 // If the only declaration here is an ordinary friend, consider
1697 // it only if it was declared in an associated classes.
1698 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00001699 DeclContext *LexDC = D->getLexicalDeclContext();
1700 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1701 continue;
1702 }
Mike Stump11289f42009-09-09 15:08:12 +00001703
Sebastian Redlc057f422009-10-23 19:23:15 +00001704 FunctionDecl *Fn;
1705 if (!Operator || !(Fn = dyn_cast<FunctionDecl>(D)) ||
1706 IsAcceptableNonMemberOperatorCandidate(Fn, T1, T2, Context))
1707 CollectFunctionDecl(Functions, D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00001708 }
1709 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001710}