blob: 1957d7ff11b7c1a7aaec1131aa44f36a4dfa82a5 [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor34074322009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6538c932009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor1c846b02009-01-16 00:38:09 +000030#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000031#include <vector>
32#include <iterator>
33#include <utility>
34#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000035
36using namespace clang;
37
John McCallf6c8a4e2009-11-10 07:01:13 +000038namespace {
39 class UnqualUsingEntry {
40 const DeclContext *Nominated;
41 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000042
John McCallf6c8a4e2009-11-10 07:01:13 +000043 public:
44 UnqualUsingEntry(const DeclContext *Nominated,
45 const DeclContext *CommonAncestor)
46 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
47 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000048
John McCallf6c8a4e2009-11-10 07:01:13 +000049 const DeclContext *getCommonAncestor() const {
50 return CommonAncestor;
51 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000052
John McCallf6c8a4e2009-11-10 07:01:13 +000053 const DeclContext *getNominatedNamespace() const {
54 return Nominated;
55 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000056
John McCallf6c8a4e2009-11-10 07:01:13 +000057 // Sort by the pointer value of the common ancestor.
58 struct Comparator {
59 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
60 return L.getCommonAncestor() < R.getCommonAncestor();
61 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000062
John McCallf6c8a4e2009-11-10 07:01:13 +000063 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
64 return E.getCommonAncestor() < DC;
65 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000066
John McCallf6c8a4e2009-11-10 07:01:13 +000067 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
68 return DC < E.getCommonAncestor();
69 }
70 };
71 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000072
John McCallf6c8a4e2009-11-10 07:01:13 +000073 /// A collection of using directives, as used by C++ unqualified
74 /// lookup.
75 class UnqualUsingDirectiveSet {
76 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000077
John McCallf6c8a4e2009-11-10 07:01:13 +000078 ListTy list;
79 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000080
John McCallf6c8a4e2009-11-10 07:01:13 +000081 public:
82 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000083
John McCallf6c8a4e2009-11-10 07:01:13 +000084 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
85 // C++ [namespace.udir]p1:
86 // During unqualified name lookup, the names appear as if they
87 // were declared in the nearest enclosing namespace which contains
88 // both the using-directive and the nominated namespace.
89 DeclContext *InnermostFileDC
90 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
91 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000092
John McCallf6c8a4e2009-11-10 07:01:13 +000093 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +000094 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
95 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
96 visit(Ctx, EffectiveDC);
97 } else {
98 Scope::udir_iterator I = S->using_directives_begin(),
99 End = S->using_directives_end();
100
101 for (; I != End; ++I)
102 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
103 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000104 }
105 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000106
107 // Visits a context and collect all of its using directives
108 // recursively. Treats all using directives as if they were
109 // declared in the context.
110 //
111 // A given context is only every visited once, so it is important
112 // that contexts be visited from the inside out in order to get
113 // the effective DCs right.
114 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
115 if (!visited.insert(DC))
116 return;
117
118 addUsingDirectives(DC, EffectiveDC);
119 }
120
121 // Visits a using directive and collects all of its using
122 // directives recursively. Treats all using directives as if they
123 // were declared in the effective DC.
124 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
125 DeclContext *NS = UD->getNominatedNamespace();
126 if (!visited.insert(NS))
127 return;
128
129 addUsingDirective(UD, EffectiveDC);
130 addUsingDirectives(NS, EffectiveDC);
131 }
132
133 // Adds all the using directives in a context (and those nominated
134 // by its using directives, transitively) as if they appeared in
135 // the given effective context.
136 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
137 llvm::SmallVector<DeclContext*,4> queue;
138 while (true) {
139 DeclContext::udir_iterator I, End;
140 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
141 UsingDirectiveDecl *UD = *I;
142 DeclContext *NS = UD->getNominatedNamespace();
143 if (visited.insert(NS)) {
144 addUsingDirective(UD, EffectiveDC);
145 queue.push_back(NS);
146 }
147 }
148
149 if (queue.empty())
150 return;
151
152 DC = queue.back();
153 queue.pop_back();
154 }
155 }
156
157 // Add a using directive as if it had been declared in the given
158 // context. This helps implement C++ [namespace.udir]p3:
159 // The using-directive is transitive: if a scope contains a
160 // using-directive that nominates a second namespace that itself
161 // contains using-directives, the effect is as if the
162 // using-directives from the second namespace also appeared in
163 // the first.
164 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
165 // Find the common ancestor between the effective context and
166 // the nominated namespace.
167 DeclContext *Common = UD->getNominatedNamespace();
168 while (!Common->Encloses(EffectiveDC))
169 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000170 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000171
172 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
173 }
174
175 void done() {
176 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
177 }
178
179 typedef ListTy::iterator iterator;
180 typedef ListTy::const_iterator const_iterator;
181
182 iterator begin() { return list.begin(); }
183 iterator end() { return list.end(); }
184 const_iterator begin() const { return list.begin(); }
185 const_iterator end() const { return list.end(); }
186
187 std::pair<const_iterator,const_iterator>
188 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000189 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000190 UnqualUsingEntry::Comparator());
191 }
192 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000193}
194
Douglas Gregor889ceb72009-02-03 19:21:40 +0000195// Retrieve the set of identifier namespaces that correspond to a
196// specific kind of name lookup.
Mike Stump11289f42009-09-09 15:08:12 +0000197inline unsigned
198getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
Douglas Gregor889ceb72009-02-03 19:21:40 +0000199 bool CPlusPlus) {
200 unsigned IDNS = 0;
201 switch (NameKind) {
202 case Sema::LookupOrdinaryName:
Douglas Gregor94eabf32009-02-04 16:44:47 +0000203 case Sema::LookupOperatorName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000204 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205 IDNS = Decl::IDNS_Ordinary;
206 if (CPlusPlus)
207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
208 break;
209
210 case Sema::LookupTagName:
211 IDNS = Decl::IDNS_Tag;
212 break;
213
214 case Sema::LookupMemberName:
215 IDNS = Decl::IDNS_Member;
216 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000217 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000218 break;
219
220 case Sema::LookupNestedNameSpecifierName:
221 case Sema::LookupNamespaceName:
222 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
223 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000224
Douglas Gregor79947a22009-04-24 00:11:27 +0000225 case Sema::LookupObjCProtocolName:
226 IDNS = Decl::IDNS_ObjCProtocol;
227 break;
228
229 case Sema::LookupObjCImplementationName:
230 IDNS = Decl::IDNS_ObjCImplementation;
231 break;
232
233 case Sema::LookupObjCCategoryImplName:
234 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000235 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000236 }
237 return IDNS;
238}
239
John McCall9f3059a2009-10-09 21:13:30 +0000240// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000241void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000242 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000243}
244
John McCall5cebab12009-11-18 07:57:50 +0000245void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000246 unsigned N = Decls.size();
Douglas Gregorf23311d2009-01-17 01:13:24 +0000247
John McCall9f3059a2009-10-09 21:13:30 +0000248 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000249 if (N == 0) {
250 assert(ResultKind == NotFound);
251 return;
252 }
253
John McCalle61f2ba2009-11-18 02:36:19 +0000254 if (N == 1) {
255 if (isa<UnresolvedUsingValueDecl>(Decls[0]))
256 ResultKind = FoundUnresolvedValue;
257 return;
258 }
John McCall9f3059a2009-10-09 21:13:30 +0000259
John McCall6538c932009-10-10 05:48:19 +0000260 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000261 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000262
John McCall9f3059a2009-10-09 21:13:30 +0000263 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
264
265 bool Ambiguous = false;
266 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCalle61f2ba2009-11-18 02:36:19 +0000267 bool HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000268
269 unsigned UniqueTagIndex = 0;
270
271 unsigned I = 0;
272 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000273 NamedDecl *D = Decls[I]->getUnderlyingDecl();
274 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000275
John McCallf0f1cf02009-11-17 07:50:12 +0000276 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000277 // If it's not unique, pull something off the back (and
278 // continue at this index).
279 Decls[I] = Decls[--N];
John McCalle61f2ba2009-11-18 02:36:19 +0000280 } else if (isa<UnresolvedUsingValueDecl>(D)) {
281 // FIXME: support unresolved using value declarations
John McCall9f3059a2009-10-09 21:13:30 +0000282 Decls[I] = Decls[--N];
283 } else {
284 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000285
286 if (isa<UnresolvedUsingValueDecl>(D)) {
287 HasUnresolved = true;
288 } else if (isa<TagDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000289 if (HasTag)
290 Ambiguous = true;
291 UniqueTagIndex = I;
292 HasTag = true;
293 } else if (D->isFunctionOrFunctionTemplate()) {
294 HasFunction = true;
295 } else {
296 if (HasNonFunction)
297 Ambiguous = true;
298 HasNonFunction = true;
299 }
300 I++;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000301 }
Mike Stump11289f42009-09-09 15:08:12 +0000302 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000303
John McCall9f3059a2009-10-09 21:13:30 +0000304 // C++ [basic.scope.hiding]p2:
305 // A class name or enumeration name can be hidden by the name of
306 // an object, function, or enumerator declared in the same
307 // scope. If a class or enumeration name and an object, function,
308 // or enumerator are declared in the same scope (in any order)
309 // with the same name, the class or enumeration name is hidden
310 // wherever the object, function, or enumerator name is visible.
311 // But it's still an error if there are distinct tag types found,
312 // even if they're not visible. (ref?)
John McCalle61f2ba2009-11-18 02:36:19 +0000313 if (HideTags && HasTag && !Ambiguous && !HasUnresolved &&
314 (HasFunction || HasNonFunction))
John McCall9f3059a2009-10-09 21:13:30 +0000315 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000316
John McCall9f3059a2009-10-09 21:13:30 +0000317 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000318
John McCall9f3059a2009-10-09 21:13:30 +0000319 if (HasFunction && HasNonFunction)
320 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000321
John McCall9f3059a2009-10-09 21:13:30 +0000322 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000323 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000324 else if (HasUnresolved)
325 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall9f3059a2009-10-09 21:13:30 +0000326 else if (N > 1)
John McCall27b18f82009-11-17 02:14:36 +0000327 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000328 else
John McCall27b18f82009-11-17 02:14:36 +0000329 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000330}
331
332/// @brief Converts the result of name lookup into a single (possible
333/// NULL) pointer to a declaration.
334///
335/// The resulting declaration will either be the declaration we found
336/// (if only a single declaration was found), an
337/// OverloadedFunctionDecl (if an overloaded function was found), or
338/// NULL (if no declaration was found). This conversion must not be
Mike Stump11289f42009-09-09 15:08:12 +0000339/// used anywhere where name lookup could result in an ambiguity.
Douglas Gregor34074322009-01-14 22:20:51 +0000340///
341/// The OverloadedFunctionDecl conversion is meant as a stop-gap
342/// solution, since it causes the OverloadedFunctionDecl to be
343/// leaked. FIXME: Eventually, there will be a better way to iterate
344/// over the set of overloaded functions returned by name lookup.
John McCall5cebab12009-11-18 07:57:50 +0000345NamedDecl *LookupResult::getAsSingleDecl(ASTContext &C) const {
John McCall9f3059a2009-10-09 21:13:30 +0000346 size_t size = Decls.size();
347 if (size == 0) return 0;
John McCallf0f1cf02009-11-17 07:50:12 +0000348 if (size == 1) return (*begin())->getUnderlyingDecl();
Douglas Gregor34074322009-01-14 22:20:51 +0000349
John McCall9f3059a2009-10-09 21:13:30 +0000350 if (isAmbiguous()) return 0;
Douglas Gregor34074322009-01-14 22:20:51 +0000351
John McCall9f3059a2009-10-09 21:13:30 +0000352 iterator I = begin(), E = end();
Douglas Gregor34074322009-01-14 22:20:51 +0000353
John McCall9f3059a2009-10-09 21:13:30 +0000354 OverloadedFunctionDecl *Ovl
355 = OverloadedFunctionDecl::Create(C, (*I)->getDeclContext(),
356 (*I)->getDeclName());
357 for (; I != E; ++I) {
John McCallf0f1cf02009-11-17 07:50:12 +0000358 NamedDecl *ND = (*I)->getUnderlyingDecl();
John McCall9f3059a2009-10-09 21:13:30 +0000359 assert(ND->isFunctionOrFunctionTemplate());
360 if (isa<FunctionDecl>(ND))
361 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000362 else
John McCall9f3059a2009-10-09 21:13:30 +0000363 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
364 // FIXME: UnresolvedUsingDecls.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000365 }
John McCall9f3059a2009-10-09 21:13:30 +0000366
367 return Ovl;
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000368}
369
John McCall5cebab12009-11-18 07:57:50 +0000370void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000371 CXXBasePaths::paths_iterator I, E;
372 DeclContext::lookup_iterator DI, DE;
373 for (I = P.begin(), E = P.end(); I != E; ++I)
374 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
375 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000376}
377
John McCall5cebab12009-11-18 07:57:50 +0000378void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000379 Paths = new CXXBasePaths;
380 Paths->swap(P);
381 addDeclsFromBasePaths(*Paths);
382 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000383 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000384}
385
John McCall5cebab12009-11-18 07:57:50 +0000386void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000387 Paths = new CXXBasePaths;
388 Paths->swap(P);
389 addDeclsFromBasePaths(*Paths);
390 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000391 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000392}
393
John McCall5cebab12009-11-18 07:57:50 +0000394void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000395 Out << Decls.size() << " result(s)";
396 if (isAmbiguous()) Out << ", ambiguous";
397 if (Paths) Out << ", base paths present";
398
399 for (iterator I = begin(), E = end(); I != E; ++I) {
400 Out << "\n";
401 (*I)->print(Out, 2);
402 }
403}
404
405// Adds all qualifying matches for a name within a decl context to the
406// given lookup result. Returns true if any matches were found.
John McCall5cebab12009-11-18 07:57:50 +0000407static bool LookupDirect(LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000408 bool Found = false;
409
John McCallf6c8a4e2009-11-10 07:01:13 +0000410 DeclContext::lookup_const_iterator I, E;
John McCall27b18f82009-11-17 02:14:36 +0000411 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I)
412 if (Sema::isAcceptableLookupResult(*I, R.getLookupKind(),
413 R.getIdentifierNamespace()))
John McCall9f3059a2009-10-09 21:13:30 +0000414 R.addDecl(*I), Found = true;
415
416 return Found;
417}
418
John McCallf6c8a4e2009-11-10 07:01:13 +0000419// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000420static bool
John McCall5cebab12009-11-18 07:57:50 +0000421CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCall27b18f82009-11-17 02:14:36 +0000422 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000423
424 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
425
John McCallf6c8a4e2009-11-10 07:01:13 +0000426 // Perform direct name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000427 bool Found = LookupDirect(R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000428
John McCallf6c8a4e2009-11-10 07:01:13 +0000429 // Perform direct name lookup into the namespaces nominated by the
430 // using directives whose common ancestor is this namespace.
431 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
432 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000433
John McCallf6c8a4e2009-11-10 07:01:13 +0000434 for (; UI != UEnd; ++UI)
John McCall27b18f82009-11-17 02:14:36 +0000435 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000436 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000437
438 R.resolveKind();
439
440 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000441}
442
443static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000444 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000445 return Ctx->isFileContext();
446 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000447}
Douglas Gregored8f2882009-01-30 01:04:22 +0000448
Douglas Gregor7f737c02009-09-10 16:57:35 +0000449// Find the next outer declaration context corresponding to this scope.
450static DeclContext *findOuterContext(Scope *S) {
451 for (S = S->getParent(); S; S = S->getParent())
452 if (S->getEntity())
453 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
454
455 return 0;
456}
457
John McCall27b18f82009-11-17 02:14:36 +0000458bool Sema::CppLookupName(LookupResult &R, Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000459 assert(getLangOptions().CPlusPlus &&
460 "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000461 LookupNameKind NameKind = R.getLookupKind();
Mike Stump11289f42009-09-09 15:08:12 +0000462 unsigned IDNS
Douglas Gregor2ada0482009-02-04 17:27:36 +0000463 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
John McCallaa74a0c2009-08-28 07:59:38 +0000464
465 // If we're testing for redeclarations, also look in the friend namespaces.
John McCall27b18f82009-11-17 02:14:36 +0000466 if (R.isForRedeclaration()) {
John McCallaa74a0c2009-08-28 07:59:38 +0000467 if (IDNS & Decl::IDNS_Tag) IDNS |= Decl::IDNS_TagFriend;
468 if (IDNS & Decl::IDNS_Ordinary) IDNS |= Decl::IDNS_OrdinaryFriend;
469 }
470
John McCall27b18f82009-11-17 02:14:36 +0000471 R.setIdentifierNamespace(IDNS);
472
473 DeclarationName Name = R.getLookupName();
474
Douglas Gregor889ceb72009-02-03 19:21:40 +0000475 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000476 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000477 I = IdResolver.begin(Name),
478 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000479
Douglas Gregor889ceb72009-02-03 19:21:40 +0000480 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000481 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000482 // ...During unqualified name lookup (3.4.1), the names appear as if
483 // they were declared in the nearest enclosing namespace which contains
484 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000485 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000486 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000487 //
488 // For example:
489 // namespace A { int i; }
490 // void foo() {
491 // int i;
492 // {
493 // using namespace A;
494 // ++i; // finds local 'i', A::i appears at global scope
495 // }
496 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000497 //
Douglas Gregor700792c2009-02-05 19:25:20 +0000498 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000499 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000500 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000501 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000502 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
John McCall9f3059a2009-10-09 21:13:30 +0000503 Found = true;
504 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000505 }
506 }
John McCall9f3059a2009-10-09 21:13:30 +0000507 if (Found) {
508 R.resolveKind();
509 return true;
510 }
511
Douglas Gregor700792c2009-02-05 19:25:20 +0000512 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregor7f737c02009-09-10 16:57:35 +0000513 DeclContext *OuterCtx = findOuterContext(S);
514 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
515 Ctx = Ctx->getLookupParent()) {
516 if (Ctx->isFunctionOrMethod())
517 continue;
518
519 // Perform qualified name lookup into this context.
520 // FIXME: In some cases, we know that every name that could be found by
521 // this qualified name lookup will also be on the identifier chain. For
522 // example, inside a class without any base classes, we never need to
523 // perform qualified lookup because all of the members are on top of the
524 // identifier chain.
John McCall27b18f82009-11-17 02:14:36 +0000525 if (LookupQualifiedName(R, Ctx))
John McCall9f3059a2009-10-09 21:13:30 +0000526 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000527 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000528 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000529 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000530
John McCallf6c8a4e2009-11-10 07:01:13 +0000531 // Stop if we ran out of scopes.
532 // FIXME: This really, really shouldn't be happening.
533 if (!S) return false;
534
Douglas Gregor700792c2009-02-05 19:25:20 +0000535 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000536 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000537 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000538 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
539 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000540
John McCallf6c8a4e2009-11-10 07:01:13 +0000541 UnqualUsingDirectiveSet UDirs;
542 UDirs.visitScopeChain(Initial, S);
543 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000544
Douglas Gregor700792c2009-02-05 19:25:20 +0000545 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000546 // Unqualified name lookup in C++ requires looking into scopes
547 // that aren't strictly lexical, and therefore we walk through the
548 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000549
Douglas Gregor889ceb72009-02-03 19:21:40 +0000550 for (; S; S = S->getParent()) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000551 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregorf2270432009-08-24 18:55:03 +0000552 if (Ctx->isTransparentContext())
553 continue;
554
Douglas Gregor700792c2009-02-05 19:25:20 +0000555 assert(Ctx && Ctx->isFileContext() &&
556 "We should have been looking only at file context here already.");
Douglas Gregor889ceb72009-02-03 19:21:40 +0000557
558 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000559 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000560 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000561 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
562 // We found something. Look for anything else in our scope
563 // with this same name and in an acceptable identifier
564 // namespace, so that we can construct an overload set if we
565 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000566 Found = true;
567 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000568 }
569 }
570
Douglas Gregor700792c2009-02-05 19:25:20 +0000571 // Look into context considering using-directives.
John McCall27b18f82009-11-17 02:14:36 +0000572 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
John McCall9f3059a2009-10-09 21:13:30 +0000573 Found = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000574
John McCall9f3059a2009-10-09 21:13:30 +0000575 if (Found) {
576 R.resolveKind();
577 return true;
578 }
579
John McCall27b18f82009-11-17 02:14:36 +0000580 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000581 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000582 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000583
John McCall9f3059a2009-10-09 21:13:30 +0000584 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000585}
586
Douglas Gregor34074322009-01-14 22:20:51 +0000587/// @brief Perform unqualified name lookup starting from a given
588/// scope.
589///
590/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
591/// used to find names within the current scope. For example, 'x' in
592/// @code
593/// int x;
594/// int f() {
595/// return x; // unqualified name look finds 'x' in the global scope
596/// }
597/// @endcode
598///
599/// Different lookup criteria can find different names. For example, a
600/// particular scope can have both a struct and a function of the same
601/// name, and each can be found by certain lookup criteria. For more
602/// information about lookup criteria, see the documentation for the
603/// class LookupCriteria.
604///
605/// @param S The scope from which unqualified name lookup will
606/// begin. If the lookup criteria permits, name lookup may also search
607/// in the parent scopes.
608///
609/// @param Name The name of the entity that we are searching for.
610///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000611/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000612/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000613/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000614///
615/// @returns The result of name lookup, which includes zero or more
616/// declarations and possibly additional information used to diagnose
617/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000618bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
619 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +0000620 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000621
John McCall27b18f82009-11-17 02:14:36 +0000622 LookupNameKind NameKind = R.getLookupKind();
623
Douglas Gregor34074322009-01-14 22:20:51 +0000624 if (!getLangOptions().CPlusPlus) {
625 // Unqualified name lookup in C/Objective-C is purely lexical, so
626 // search in the declarations attached to the name.
Douglas Gregored8f2882009-01-30 01:04:22 +0000627 unsigned IDNS = 0;
628 switch (NameKind) {
629 case Sema::LookupOrdinaryName:
630 IDNS = Decl::IDNS_Ordinary;
631 break;
Douglas Gregor34074322009-01-14 22:20:51 +0000632
Douglas Gregored8f2882009-01-30 01:04:22 +0000633 case Sema::LookupTagName:
634 IDNS = Decl::IDNS_Tag;
635 break;
636
637 case Sema::LookupMemberName:
638 IDNS = Decl::IDNS_Member;
639 break;
640
Douglas Gregor94eabf32009-02-04 16:44:47 +0000641 case Sema::LookupOperatorName:
Douglas Gregored8f2882009-01-30 01:04:22 +0000642 case Sema::LookupNestedNameSpecifierName:
643 case Sema::LookupNamespaceName:
644 assert(false && "C does not perform these kinds of name lookup");
645 break;
Douglas Gregoreddf4332009-02-24 20:03:32 +0000646
647 case Sema::LookupRedeclarationWithLinkage:
648 // Find the nearest non-transparent declaration scope.
649 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000650 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000651 static_cast<DeclContext *>(S->getEntity())
652 ->isTransparentContext()))
653 S = S->getParent();
654 IDNS = Decl::IDNS_Ordinary;
655 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000656
Douglas Gregor79947a22009-04-24 00:11:27 +0000657 case Sema::LookupObjCProtocolName:
658 IDNS = Decl::IDNS_ObjCProtocol;
659 break;
660
661 case Sema::LookupObjCImplementationName:
662 IDNS = Decl::IDNS_ObjCImplementation;
663 break;
Mike Stump11289f42009-09-09 15:08:12 +0000664
Douglas Gregor79947a22009-04-24 00:11:27 +0000665 case Sema::LookupObjCCategoryImplName:
666 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000667 break;
Douglas Gregored8f2882009-01-30 01:04:22 +0000668 }
669
Douglas Gregor34074322009-01-14 22:20:51 +0000670 // Scan up the scope chain looking for a decl that matches this
671 // identifier that is in the appropriate namespace. This search
672 // should not take long, as shadowing of names is uncommon, and
673 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000674 bool LeftStartingScope = false;
675
Douglas Gregored8f2882009-01-30 01:04:22 +0000676 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000677 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000678 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000679 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000680 if (NameKind == LookupRedeclarationWithLinkage) {
681 // Determine whether this (or a previous) declaration is
682 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000683 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000684 LeftStartingScope = true;
685
686 // If we found something outside of our starting scope that
687 // does not have linkage, skip it.
688 if (LeftStartingScope && !((*I)->hasLinkage()))
689 continue;
690 }
691
John McCall9f3059a2009-10-09 21:13:30 +0000692 R.addDecl(*I);
693
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000694 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000695 // If this declaration has the "overloadable" attribute, we
696 // might have a set of overloaded functions.
697
698 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000699 while (!(S->getFlags() & Scope::DeclScope) ||
700 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000701 S = S->getParent();
702
703 // Find the last declaration in this scope (with the same
704 // name, naturally).
705 IdentifierResolver::iterator LastI = I;
706 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000707 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000708 break;
John McCall9f3059a2009-10-09 21:13:30 +0000709 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000710 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000711 }
712
John McCall9f3059a2009-10-09 21:13:30 +0000713 R.resolveKind();
714
715 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000716 }
Douglas Gregor34074322009-01-14 22:20:51 +0000717 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000718 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000719 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +0000720 return true;
Douglas Gregor34074322009-01-14 22:20:51 +0000721 }
722
723 // If we didn't find a use of this identifier, and if the identifier
724 // corresponds to a compiler builtin, create the decl object for the builtin
725 // now, injecting it into translation unit scope, and return it.
Mike Stump11289f42009-09-09 15:08:12 +0000726 if (NameKind == LookupOrdinaryName ||
Douglas Gregoreddf4332009-02-24 20:03:32 +0000727 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor34074322009-01-14 22:20:51 +0000728 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000729 if (II && AllowBuiltinCreation) {
Douglas Gregor34074322009-01-14 22:20:51 +0000730 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000731 if (unsigned BuiltinID = II->getBuiltinID()) {
732 // In C++, we don't have any predefined library functions like
733 // 'malloc'. Instead, we'll just error.
Mike Stump11289f42009-09-09 15:08:12 +0000734 if (getLangOptions().CPlusPlus &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000735 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCall9f3059a2009-10-09 21:13:30 +0000736 return false;
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000737
John McCall9f3059a2009-10-09 21:13:30 +0000738 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCall27b18f82009-11-17 02:14:36 +0000739 S, R.isForRedeclaration(),
740 R.getNameLoc());
John McCall9f3059a2009-10-09 21:13:30 +0000741 if (D) R.addDecl(D);
742 return (D != NULL);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000743 }
Douglas Gregor34074322009-01-14 22:20:51 +0000744 }
Douglas Gregor34074322009-01-14 22:20:51 +0000745 }
John McCall9f3059a2009-10-09 21:13:30 +0000746 return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000747}
748
John McCall6538c932009-10-10 05:48:19 +0000749/// @brief Perform qualified name lookup in the namespaces nominated by
750/// using directives by the given context.
751///
752/// C++98 [namespace.qual]p2:
753/// Given X::m (where X is a user-declared namespace), or given ::m
754/// (where X is the global namespace), let S be the set of all
755/// declarations of m in X and in the transitive closure of all
756/// namespaces nominated by using-directives in X and its used
757/// namespaces, except that using-directives are ignored in any
758/// namespace, including X, directly containing one or more
759/// declarations of m. No namespace is searched more than once in
760/// the lookup of a name. If S is the empty set, the program is
761/// ill-formed. Otherwise, if S has exactly one member, or if the
762/// context of the reference is a using-declaration
763/// (namespace.udecl), S is the required set of declarations of
764/// m. Otherwise if the use of m is not one that allows a unique
765/// declaration to be chosen from S, the program is ill-formed.
766/// C++98 [namespace.qual]p5:
767/// During the lookup of a qualified namespace member name, if the
768/// lookup finds more than one declaration of the member, and if one
769/// declaration introduces a class name or enumeration name and the
770/// other declarations either introduce the same object, the same
771/// enumerator or a set of functions, the non-type name hides the
772/// class or enumeration name if and only if the declarations are
773/// from the same namespace; otherwise (the declarations are from
774/// different namespaces), the program is ill-formed.
John McCall5cebab12009-11-18 07:57:50 +0000775static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +0000776 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +0000777 assert(StartDC->isFileContext() && "start context is not a file context");
778
779 DeclContext::udir_iterator I = StartDC->using_directives_begin();
780 DeclContext::udir_iterator E = StartDC->using_directives_end();
781
782 if (I == E) return false;
783
784 // We have at least added all these contexts to the queue.
785 llvm::DenseSet<DeclContext*> Visited;
786 Visited.insert(StartDC);
787
788 // We have not yet looked into these namespaces, much less added
789 // their "using-children" to the queue.
790 llvm::SmallVector<NamespaceDecl*, 8> Queue;
791
792 // We have already looked into the initial namespace; seed the queue
793 // with its using-children.
794 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +0000795 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +0000796 if (Visited.insert(ND).second)
797 Queue.push_back(ND);
798 }
799
800 // The easiest way to implement the restriction in [namespace.qual]p5
801 // is to check whether any of the individual results found a tag
802 // and, if so, to declare an ambiguity if the final result is not
803 // a tag.
804 bool FoundTag = false;
805 bool FoundNonTag = false;
806
John McCall5cebab12009-11-18 07:57:50 +0000807 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +0000808
809 bool Found = false;
810 while (!Queue.empty()) {
811 NamespaceDecl *ND = Queue.back();
812 Queue.pop_back();
813
814 // We go through some convolutions here to avoid copying results
815 // between LookupResults.
816 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +0000817 LookupResult &DirectR = UseLocal ? LocalR : R;
John McCall27b18f82009-11-17 02:14:36 +0000818 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +0000819
820 if (FoundDirect) {
821 // First do any local hiding.
822 DirectR.resolveKind();
823
824 // If the local result is a tag, remember that.
825 if (DirectR.isSingleTagDecl())
826 FoundTag = true;
827 else
828 FoundNonTag = true;
829
830 // Append the local results to the total results if necessary.
831 if (UseLocal) {
832 R.addAllDecls(LocalR);
833 LocalR.clear();
834 }
835 }
836
837 // If we find names in this namespace, ignore its using directives.
838 if (FoundDirect) {
839 Found = true;
840 continue;
841 }
842
843 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
844 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
845 if (Visited.insert(Nom).second)
846 Queue.push_back(Nom);
847 }
848 }
849
850 if (Found) {
851 if (FoundTag && FoundNonTag)
852 R.setAmbiguousQualifiedTagHiding();
853 else
854 R.resolveKind();
855 }
856
857 return Found;
858}
859
Douglas Gregor34074322009-01-14 22:20:51 +0000860/// @brief Perform qualified name lookup into a given context.
861///
862/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
863/// names when the context of those names is explicit specified, e.g.,
864/// "std::vector" or "x->member".
865///
866/// Different lookup criteria can find different names. For example, a
867/// particular scope can have both a struct and a function of the same
868/// name, and each can be found by certain lookup criteria. For more
869/// information about lookup criteria, see the documentation for the
870/// class LookupCriteria.
871///
872/// @param LookupCtx The context in which qualified name lookup will
873/// search. If the lookup criteria permits, name lookup may also search
874/// in the parent contexts or (for C++ classes) base classes.
875///
876/// @param Name The name of the entity that we are searching for.
877///
878/// @param Criteria The criteria that this routine will use to
879/// determine which names are visible and which names will be
880/// found. Note that name lookup will find a name that is visible by
881/// the given criteria, but the entity itself may not be semantically
882/// correct or even the kind of entity expected based on the
883/// lookup. For example, searching for a nested-name-specifier name
884/// might result in an EnumDecl, which is visible but is not permitted
885/// as a nested-name-specifier in C++03.
886///
887/// @returns The result of name lookup, which includes zero or more
888/// declarations and possibly additional information used to diagnose
889/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000890bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx) {
Douglas Gregor34074322009-01-14 22:20:51 +0000891 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +0000892
John McCall27b18f82009-11-17 02:14:36 +0000893 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +0000894 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000895
Douglas Gregor34074322009-01-14 22:20:51 +0000896 // If we're performing qualified name lookup (e.g., lookup into a
897 // struct), find fields as part of ordinary name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000898 LookupNameKind NameKind = R.getLookupKind();
Douglas Gregored8f2882009-01-30 01:04:22 +0000899 unsigned IDNS
Mike Stump11289f42009-09-09 15:08:12 +0000900 = getIdentifierNamespacesFromLookupNameKind(NameKind,
Douglas Gregored8f2882009-01-30 01:04:22 +0000901 getLangOptions().CPlusPlus);
902 if (NameKind == LookupOrdinaryName)
903 IDNS |= Decl::IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000904
John McCall27b18f82009-11-17 02:14:36 +0000905 R.setIdentifierNamespace(IDNS);
906
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000907 // Make sure that the declaration context is complete.
908 assert((!isa<TagDecl>(LookupCtx) ||
909 LookupCtx->isDependentContext() ||
910 cast<TagDecl>(LookupCtx)->isDefinition() ||
911 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
912 ->isBeingDefined()) &&
913 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +0000914
Douglas Gregor34074322009-01-14 22:20:51 +0000915 // Perform qualified name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000916 if (LookupDirect(R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +0000917 R.resolveKind();
918 return true;
919 }
Douglas Gregor34074322009-01-14 22:20:51 +0000920
John McCall6538c932009-10-10 05:48:19 +0000921 // Don't descend into implied contexts for redeclarations.
922 // C++98 [namespace.qual]p6:
923 // In a declaration for a namespace member in which the
924 // declarator-id is a qualified-id, given that the qualified-id
925 // for the namespace member has the form
926 // nested-name-specifier unqualified-id
927 // the unqualified-id shall name a member of the namespace
928 // designated by the nested-name-specifier.
929 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +0000930 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +0000931 return false;
932
John McCall27b18f82009-11-17 02:14:36 +0000933 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +0000934 if (LookupCtx->isFileContext())
John McCall27b18f82009-11-17 02:14:36 +0000935 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +0000936
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000937 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +0000938 // classes, we're done.
John McCall6538c932009-10-10 05:48:19 +0000939 if (!isa<CXXRecordDecl>(LookupCtx))
John McCall9f3059a2009-10-09 21:13:30 +0000940 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000941
942 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +0000943 CXXRecordDecl *LookupRec = cast<CXXRecordDecl>(LookupCtx);
944 CXXBasePaths Paths;
945 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000946
947 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +0000948 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +0000949 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000950 case LookupOrdinaryName:
951 case LookupMemberName:
952 case LookupRedeclarationWithLinkage:
953 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
954 break;
955
956 case LookupTagName:
957 BaseCallback = &CXXRecordDecl::FindTagMember;
958 break;
959
960 case LookupOperatorName:
961 case LookupNamespaceName:
962 case LookupObjCProtocolName:
963 case LookupObjCImplementationName:
964 case LookupObjCCategoryImplName:
965 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +0000966 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000967
968 case LookupNestedNameSpecifierName:
969 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
970 break;
971 }
972
John McCall27b18f82009-11-17 02:14:36 +0000973 if (!LookupRec->lookupInBases(BaseCallback,
974 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +0000975 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000976
977 // C++ [class.member.lookup]p2:
978 // [...] If the resulting set of declarations are not all from
979 // sub-objects of the same type, or the set has a nonstatic member
980 // and includes members from distinct sub-objects, there is an
981 // ambiguity and the program is ill-formed. Otherwise that set is
982 // the result of the lookup.
983 // FIXME: support using declarations!
984 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +0000985 int SubobjectNumber = 0;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000986 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000987 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000988 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000989
990 // Determine whether we're looking at a distinct sub-object or not.
991 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +0000992 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000993 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
994 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +0000995 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000996 != Context.getCanonicalType(PathElement.Base->getType())) {
997 // We found members of the given name in two subobjects of
998 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +0000999 R.setAmbiguousBaseSubobjectTypes(Paths);
1000 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001001 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1002 // We have a different subobject of the same type.
1003
1004 // C++ [class.member.lookup]p5:
1005 // A static member, a nested type or an enumerator defined in
1006 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001007 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001008 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001009 if (isa<VarDecl>(FirstDecl) ||
1010 isa<TypeDecl>(FirstDecl) ||
1011 isa<EnumConstantDecl>(FirstDecl))
1012 continue;
1013
1014 if (isa<CXXMethodDecl>(FirstDecl)) {
1015 // Determine whether all of the methods are static.
1016 bool AllMethodsAreStatic = true;
1017 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1018 Func != Path->Decls.second; ++Func) {
1019 if (!isa<CXXMethodDecl>(*Func)) {
1020 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1021 break;
1022 }
1023
1024 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1025 AllMethodsAreStatic = false;
1026 break;
1027 }
1028 }
1029
1030 if (AllMethodsAreStatic)
1031 continue;
1032 }
1033
1034 // We have found a nonstatic member name in multiple, distinct
1035 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001036 R.setAmbiguousBaseSubobjects(Paths);
1037 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001038 }
1039 }
1040
1041 // Lookup in a base class succeeded; return these results.
1042
John McCall9f3059a2009-10-09 21:13:30 +00001043 DeclContext::lookup_iterator I, E;
1044 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I)
1045 R.addDecl(*I);
1046 R.resolveKind();
1047 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001048}
1049
1050/// @brief Performs name lookup for a name that was parsed in the
1051/// source code, and may contain a C++ scope specifier.
1052///
1053/// This routine is a convenience routine meant to be called from
1054/// contexts that receive a name and an optional C++ scope specifier
1055/// (e.g., "N::M::x"). It will then perform either qualified or
1056/// unqualified name lookup (with LookupQualifiedName or LookupName,
1057/// respectively) on the given name and return those results.
1058///
1059/// @param S The scope from which unqualified name lookup will
1060/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001061///
Douglas Gregore861bac2009-08-25 22:51:20 +00001062/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001063///
1064/// @param Name The name of the entity that name lookup will
1065/// search for.
1066///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001067/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001068/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001069/// C library functions (like "malloc") are implicitly declared.
1070///
Douglas Gregore861bac2009-08-25 22:51:20 +00001071/// @param EnteringContext Indicates whether we are going to enter the
1072/// context of the scope-specifier SS (if present).
1073///
John McCall9f3059a2009-10-09 21:13:30 +00001074/// @returns True if any decls were found (but possibly ambiguous)
1075bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001076 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001077 if (SS && SS->isInvalid()) {
1078 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001079 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001080 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001081 }
Mike Stump11289f42009-09-09 15:08:12 +00001082
Douglas Gregore861bac2009-08-25 22:51:20 +00001083 if (SS && SS->isSet()) {
1084 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001085 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001086 // contex, and will perform name lookup in that context.
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001087 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCall9f3059a2009-10-09 21:13:30 +00001088 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001089
John McCall27b18f82009-11-17 02:14:36 +00001090 R.setContextRange(SS->getRange());
1091
1092 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001093 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001094
Douglas Gregore861bac2009-08-25 22:51:20 +00001095 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001096 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001097 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001098 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001099 }
1100
Mike Stump11289f42009-09-09 15:08:12 +00001101 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001102 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001103}
1104
Douglas Gregor889ceb72009-02-03 19:21:40 +00001105
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001106/// @brief Produce a diagnostic describing the ambiguity that resulted
1107/// from name lookup.
1108///
1109/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001110///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001111/// @param Name The name of the entity that name lookup was
1112/// searching for.
1113///
1114/// @param NameLoc The location of the name within the source code.
1115///
1116/// @param LookupRange A source range that provides more
1117/// source-location information concerning the lookup itself. For
1118/// example, this range might highlight a nested-name-specifier that
1119/// precedes the name.
1120///
1121/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001122bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001123 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1124
John McCall27b18f82009-11-17 02:14:36 +00001125 DeclarationName Name = Result.getLookupName();
1126 SourceLocation NameLoc = Result.getNameLoc();
1127 SourceRange LookupRange = Result.getContextRange();
1128
John McCall6538c932009-10-10 05:48:19 +00001129 switch (Result.getAmbiguityKind()) {
1130 case LookupResult::AmbiguousBaseSubobjects: {
1131 CXXBasePaths *Paths = Result.getBasePaths();
1132 QualType SubobjectType = Paths->front().back().Base->getType();
1133 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1134 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1135 << LookupRange;
1136
1137 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1138 while (isa<CXXMethodDecl>(*Found) &&
1139 cast<CXXMethodDecl>(*Found)->isStatic())
1140 ++Found;
1141
1142 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1143
1144 return true;
1145 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001146
John McCall6538c932009-10-10 05:48:19 +00001147 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001148 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1149 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001150
1151 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001152 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001153 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1154 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001155 Path != PathEnd; ++Path) {
1156 Decl *D = *Path->Decls.first;
1157 if (DeclsPrinted.insert(D).second)
1158 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1159 }
1160
Douglas Gregor1c846b02009-01-16 00:38:09 +00001161 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001162 }
1163
John McCall6538c932009-10-10 05:48:19 +00001164 case LookupResult::AmbiguousTagHiding: {
1165 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001166
John McCall6538c932009-10-10 05:48:19 +00001167 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1168
1169 LookupResult::iterator DI, DE = Result.end();
1170 for (DI = Result.begin(); DI != DE; ++DI)
1171 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1172 TagDecls.insert(TD);
1173 Diag(TD->getLocation(), diag::note_hidden_tag);
1174 }
1175
1176 for (DI = Result.begin(); DI != DE; ++DI)
1177 if (!isa<TagDecl>(*DI))
1178 Diag((*DI)->getLocation(), diag::note_hiding_object);
1179
1180 // For recovery purposes, go ahead and implement the hiding.
1181 Result.hideDecls(TagDecls);
1182
1183 return true;
1184 }
1185
1186 case LookupResult::AmbiguousReference: {
1187 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001188
John McCall6538c932009-10-10 05:48:19 +00001189 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1190 for (; DI != DE; ++DI)
1191 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001192
John McCall6538c932009-10-10 05:48:19 +00001193 return true;
1194 }
1195 }
1196
1197 llvm::llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001198 return true;
1199}
Douglas Gregore254f902009-02-04 00:32:51 +00001200
Mike Stump11289f42009-09-09 15:08:12 +00001201static void
1202addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001203 ASTContext &Context,
1204 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001205 Sema::AssociatedClassSet &AssociatedClasses);
1206
1207static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1208 DeclContext *Ctx) {
1209 if (Ctx->isFileContext())
1210 Namespaces.insert(Ctx);
1211}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001212
Mike Stump11289f42009-09-09 15:08:12 +00001213// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001214// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001215static void
1216addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001217 ASTContext &Context,
1218 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001219 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001220 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001221 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001222 switch (Arg.getKind()) {
1223 case TemplateArgument::Null:
1224 break;
Mike Stump11289f42009-09-09 15:08:12 +00001225
Douglas Gregor197e5f72009-07-08 07:51:57 +00001226 case TemplateArgument::Type:
1227 // [...] the namespaces and classes associated with the types of the
1228 // template arguments provided for template type parameters (excluding
1229 // template template parameters)
1230 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1231 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001232 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001233 break;
Mike Stump11289f42009-09-09 15:08:12 +00001234
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001235 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001236 // [...] the namespaces in which any template template arguments are
1237 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001238 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001239 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001240 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001241 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001242 DeclContext *Ctx = ClassTemplate->getDeclContext();
1243 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1244 AssociatedClasses.insert(EnclosingClass);
1245 // Add the associated namespace for this class.
1246 while (Ctx->isRecord())
1247 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001248 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001249 }
1250 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001251 }
1252
1253 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001254 case TemplateArgument::Integral:
1255 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001256 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001257 // associated namespaces. ]
1258 break;
Mike Stump11289f42009-09-09 15:08:12 +00001259
Douglas Gregor197e5f72009-07-08 07:51:57 +00001260 case TemplateArgument::Pack:
1261 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1262 PEnd = Arg.pack_end();
1263 P != PEnd; ++P)
1264 addAssociatedClassesAndNamespaces(*P, Context,
1265 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001266 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001267 break;
1268 }
1269}
1270
Douglas Gregore254f902009-02-04 00:32:51 +00001271// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001272// argument-dependent lookup with an argument of class type
1273// (C++ [basic.lookup.koenig]p2).
1274static void
1275addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregore254f902009-02-04 00:32:51 +00001276 ASTContext &Context,
1277 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001278 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001279 // C++ [basic.lookup.koenig]p2:
1280 // [...]
1281 // -- If T is a class type (including unions), its associated
1282 // classes are: the class itself; the class of which it is a
1283 // member, if any; and its direct and indirect base
1284 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001285 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001286
1287 // Add the class of which it is a member, if any.
1288 DeclContext *Ctx = Class->getDeclContext();
1289 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1290 AssociatedClasses.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001291 // Add the associated namespace for this class.
1292 while (Ctx->isRecord())
1293 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001294 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001295
Douglas Gregore254f902009-02-04 00:32:51 +00001296 // Add the class itself. If we've already seen this class, we don't
1297 // need to visit base classes.
1298 if (!AssociatedClasses.insert(Class))
1299 return;
1300
Mike Stump11289f42009-09-09 15:08:12 +00001301 // -- If T is a template-id, its associated namespaces and classes are
1302 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001303 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001304 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001305 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001306 // namespaces in which any template template arguments are defined; and
1307 // the classes in which any member templates used as template template
1308 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001309 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001310 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001311 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1312 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1313 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1314 AssociatedClasses.insert(EnclosingClass);
1315 // Add the associated namespace for this class.
1316 while (Ctx->isRecord())
1317 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001318 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001319
Douglas Gregor197e5f72009-07-08 07:51:57 +00001320 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1321 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1322 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1323 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001324 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001325 }
Mike Stump11289f42009-09-09 15:08:12 +00001326
Douglas Gregore254f902009-02-04 00:32:51 +00001327 // Add direct and indirect base classes along with their associated
1328 // namespaces.
1329 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1330 Bases.push_back(Class);
1331 while (!Bases.empty()) {
1332 // Pop this class off the stack.
1333 Class = Bases.back();
1334 Bases.pop_back();
1335
1336 // Visit the base classes.
1337 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1338 BaseEnd = Class->bases_end();
1339 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001340 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001341 // In dependent contexts, we do ADL twice, and the first time around,
1342 // the base type might be a dependent TemplateSpecializationType, or a
1343 // TemplateTypeParmType. If that happens, simply ignore it.
1344 // FIXME: If we want to support export, we probably need to add the
1345 // namespace of the template in a TemplateSpecializationType, or even
1346 // the classes and namespaces of known non-dependent arguments.
1347 if (!BaseType)
1348 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001349 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1350 if (AssociatedClasses.insert(BaseDecl)) {
1351 // Find the associated namespace for this base class.
1352 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1353 while (BaseCtx->isRecord())
1354 BaseCtx = BaseCtx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001355 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001356
1357 // Make sure we visit the bases of this base class.
1358 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1359 Bases.push_back(BaseDecl);
1360 }
1361 }
1362 }
1363}
1364
1365// \brief Add the associated classes and namespaces for
1366// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001367// (C++ [basic.lookup.koenig]p2).
1368static void
1369addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregore254f902009-02-04 00:32:51 +00001370 ASTContext &Context,
1371 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001372 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001373 // C++ [basic.lookup.koenig]p2:
1374 //
1375 // For each argument type T in the function call, there is a set
1376 // of zero or more associated namespaces and a set of zero or more
1377 // associated classes to be considered. The sets of namespaces and
1378 // classes is determined entirely by the types of the function
1379 // arguments (and the namespace of any template template
1380 // argument). Typedef names and using-declarations used to specify
1381 // the types do not contribute to this set. The sets of namespaces
1382 // and classes are determined in the following way:
1383 T = Context.getCanonicalType(T).getUnqualifiedType();
1384
1385 // -- If T is a pointer to U or an array of U, its associated
Mike Stump11289f42009-09-09 15:08:12 +00001386 // namespaces and classes are those associated with U.
Douglas Gregore254f902009-02-04 00:32:51 +00001387 //
1388 // We handle this by unwrapping pointer and array types immediately,
1389 // to avoid unnecessary recursion.
1390 while (true) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001391 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001392 T = Ptr->getPointeeType();
1393 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1394 T = Ptr->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001395 else
Douglas Gregore254f902009-02-04 00:32:51 +00001396 break;
1397 }
1398
1399 // -- If T is a fundamental type, its associated sets of
1400 // namespaces and classes are both empty.
John McCall9dd450b2009-09-21 23:43:11 +00001401 if (T->getAs<BuiltinType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001402 return;
1403
1404 // -- If T is a class type (including unions), its associated
1405 // classes are: the class itself; the class of which it is a
1406 // member, if any; and its direct and indirect base
1407 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001408 // which its associated classes are defined.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001409 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump11289f42009-09-09 15:08:12 +00001410 if (CXXRecordDecl *ClassDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001411 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001412 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1413 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001414 AssociatedClasses);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001415 return;
1416 }
Douglas Gregore254f902009-02-04 00:32:51 +00001417
1418 // -- If T is an enumeration type, its associated namespace is
1419 // the namespace in which it is defined. If it is class
1420 // member, its associated class is the member’s class; else
Mike Stump11289f42009-09-09 15:08:12 +00001421 // it has no associated class.
John McCall9dd450b2009-09-21 23:43:11 +00001422 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001423 EnumDecl *Enum = EnumT->getDecl();
1424
1425 DeclContext *Ctx = Enum->getDeclContext();
1426 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1427 AssociatedClasses.insert(EnclosingClass);
1428
1429 // Add the associated namespace for this class.
1430 while (Ctx->isRecord())
1431 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001432 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001433
1434 return;
1435 }
1436
1437 // -- If T is a function type, its associated namespaces and
1438 // classes are those associated with the function parameter
1439 // types and those associated with the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001440 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001441 // Return type
John McCall9dd450b2009-09-21 23:43:11 +00001442 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregore254f902009-02-04 00:32:51 +00001443 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001444 AssociatedNamespaces, AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001445
John McCall9dd450b2009-09-21 23:43:11 +00001446 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregore254f902009-02-04 00:32:51 +00001447 if (!Proto)
1448 return;
1449
1450 // Argument types
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001451 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001452 ArgEnd = Proto->arg_type_end();
Douglas Gregore254f902009-02-04 00:32:51 +00001453 Arg != ArgEnd; ++Arg)
1454 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallc7e8e792009-08-07 22:18:02 +00001455 AssociatedNamespaces, AssociatedClasses);
Mike Stump11289f42009-09-09 15:08:12 +00001456
Douglas Gregore254f902009-02-04 00:32:51 +00001457 return;
1458 }
1459
1460 // -- If T is a pointer to a member function of a class X, its
1461 // associated namespaces and classes are those associated
1462 // with the function parameter types and return type,
Mike Stump11289f42009-09-09 15:08:12 +00001463 // together with those associated with X.
Douglas Gregore254f902009-02-04 00:32:51 +00001464 //
1465 // -- If T is a pointer to a data member of class X, its
1466 // associated namespaces and classes are those associated
1467 // with the member type together with those associated with
Mike Stump11289f42009-09-09 15:08:12 +00001468 // X.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001469 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001470 // Handle the type that the pointer to member points to.
1471 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1472 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001473 AssociatedNamespaces,
1474 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001475
1476 // Handle the class type into which this points.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001477 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001478 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1479 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001480 AssociatedNamespaces,
1481 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001482
1483 return;
1484 }
1485
1486 // FIXME: What about block pointers?
1487 // FIXME: What about Objective-C message sends?
1488}
1489
1490/// \brief Find the associated classes and namespaces for
1491/// argument-dependent lookup for a call with the given set of
1492/// arguments.
1493///
1494/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001495/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001496/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001497void
Douglas Gregore254f902009-02-04 00:32:51 +00001498Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1499 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001500 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001501 AssociatedNamespaces.clear();
1502 AssociatedClasses.clear();
1503
1504 // C++ [basic.lookup.koenig]p2:
1505 // For each argument type T in the function call, there is a set
1506 // of zero or more associated namespaces and a set of zero or more
1507 // associated classes to be considered. The sets of namespaces and
1508 // classes is determined entirely by the types of the function
1509 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001510 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001511 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1512 Expr *Arg = Args[ArgIdx];
1513
1514 if (Arg->getType() != Context.OverloadTy) {
1515 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001516 AssociatedNamespaces,
1517 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001518 continue;
1519 }
1520
1521 // [...] In addition, if the argument is the name or address of a
1522 // set of overloaded functions and/or function templates, its
1523 // associated classes and namespaces are the union of those
1524 // associated with each of the members of the set: the namespace
1525 // in which the function or function template is defined and the
1526 // classes and namespaces associated with its (non-dependent)
1527 // parameter types and return type.
1528 DeclRefExpr *DRE = 0;
Douglas Gregorbe759252009-07-08 10:57:20 +00001529 TemplateIdRefExpr *TIRE = 0;
1530 Arg = Arg->IgnoreParens();
Douglas Gregore254f902009-02-04 00:32:51 +00001531 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorbe759252009-07-08 10:57:20 +00001532 if (unaryOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregore254f902009-02-04 00:32:51 +00001533 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
Douglas Gregorbe759252009-07-08 10:57:20 +00001534 TIRE = dyn_cast<TemplateIdRefExpr>(unaryOp->getSubExpr());
1535 }
1536 } else {
Douglas Gregore254f902009-02-04 00:32:51 +00001537 DRE = dyn_cast<DeclRefExpr>(Arg);
Douglas Gregorbe759252009-07-08 10:57:20 +00001538 TIRE = dyn_cast<TemplateIdRefExpr>(Arg);
1539 }
Mike Stump11289f42009-09-09 15:08:12 +00001540
Douglas Gregorbe759252009-07-08 10:57:20 +00001541 OverloadedFunctionDecl *Ovl = 0;
1542 if (DRE)
1543 Ovl = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1544 else if (TIRE)
Douglas Gregoraa87ebc2009-07-29 18:26:50 +00001545 Ovl = TIRE->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001546 if (!Ovl)
1547 continue;
1548
1549 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1550 FuncEnd = Ovl->function_end();
1551 Func != FuncEnd; ++Func) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001552 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func);
1553 if (!FDecl)
1554 FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001555
1556 // Add the namespace in which this function was defined. Note
1557 // that, if this is a member function, we do *not* consider the
1558 // enclosing namespace of its class.
1559 DeclContext *Ctx = FDecl->getDeclContext();
John McCallc7e8e792009-08-07 22:18:02 +00001560 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001561
1562 // Add the classes and namespaces associated with the parameter
1563 // types and return type of this function.
1564 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001565 AssociatedNamespaces,
1566 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001567 }
1568 }
1569}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001570
1571/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1572/// an acceptable non-member overloaded operator for a call whose
1573/// arguments have types T1 (and, if non-empty, T2). This routine
1574/// implements the check in C++ [over.match.oper]p3b2 concerning
1575/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001576static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001577IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1578 QualType T1, QualType T2,
1579 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001580 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1581 return true;
1582
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001583 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1584 return true;
1585
John McCall9dd450b2009-09-21 23:43:11 +00001586 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001587 if (Proto->getNumArgs() < 1)
1588 return false;
1589
1590 if (T1->isEnumeralType()) {
1591 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001592 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001593 return true;
1594 }
1595
1596 if (Proto->getNumArgs() < 2)
1597 return false;
1598
1599 if (!T2.isNull() && T2->isEnumeralType()) {
1600 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001601 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001602 return true;
1603 }
1604
1605 return false;
1606}
1607
John McCall5cebab12009-11-18 07:57:50 +00001608NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1609 LookupNameKind NameKind,
1610 RedeclarationKind Redecl) {
1611 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1612 LookupName(R, S);
1613 return R.getAsSingleDecl(Context);
1614}
1615
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001616/// \brief Find the protocol with the given name, if any.
1617ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001618 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001619 return cast_or_null<ObjCProtocolDecl>(D);
1620}
1621
Douglas Gregor79947a22009-04-24 00:11:27 +00001622/// \brief Find the Objective-C category implementation with the given
1623/// name, if any.
1624ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001625 Decl *D = LookupSingleName(TUScope, II, LookupObjCCategoryImplName);
Douglas Gregor79947a22009-04-24 00:11:27 +00001626 return cast_or_null<ObjCCategoryImplDecl>(D);
1627}
1628
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001629void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001630 QualType T1, QualType T2,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001631 FunctionSet &Functions) {
1632 // C++ [over.match.oper]p3:
1633 // -- The set of non-member candidates is the result of the
1634 // unqualified lookup of operator@ in the context of the
1635 // expression according to the usual rules for name lookup in
1636 // unqualified function calls (3.4.2) except that all member
1637 // functions are ignored. However, if no operand has a class
1638 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001639 // that have a first parameter of type T1 or "reference to
1640 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001641 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001642 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001643 // when T2 is an enumeration type, are candidate functions.
1644 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00001645 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1646 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00001647
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001648 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1649
John McCall9f3059a2009-10-09 21:13:30 +00001650 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001651 return;
1652
1653 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1654 Op != OpEnd; ++Op) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001655 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001656 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1657 Functions.insert(FD); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001658 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor15448f82009-06-27 21:05:07 +00001659 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1660 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001661 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001662 // later?
1663 if (!FunTmpl->getDeclContext()->isRecord())
1664 Functions.insert(FunTmpl);
1665 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001666 }
1667}
1668
John McCallc7e8e792009-08-07 22:18:02 +00001669static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1670 Decl *D) {
1671 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1672 Functions.insert(Func);
1673 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1674 Functions.insert(FunTmpl);
1675}
1676
Sebastian Redlc057f422009-10-23 19:23:15 +00001677void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001678 Expr **Args, unsigned NumArgs,
1679 FunctionSet &Functions) {
1680 // Find all of the associated namespaces and classes based on the
1681 // arguments we have.
1682 AssociatedNamespaceSet AssociatedNamespaces;
1683 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00001684 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00001685 AssociatedNamespaces,
1686 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001687
Sebastian Redlc057f422009-10-23 19:23:15 +00001688 QualType T1, T2;
1689 if (Operator) {
1690 T1 = Args[0]->getType();
1691 if (NumArgs >= 2)
1692 T2 = Args[1]->getType();
1693 }
1694
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001695 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001696 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1697 // and let Y be the lookup set produced by argument dependent
1698 // lookup (defined as follows). If X contains [...] then Y is
1699 // empty. Otherwise Y is the set of declarations found in the
1700 // namespaces associated with the argument types as described
1701 // below. The set of declarations found by the lookup of the name
1702 // is the union of X and Y.
1703 //
1704 // Here, we compute Y and add its members to the overloaded
1705 // candidate set.
1706 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001707 NSEnd = AssociatedNamespaces.end();
1708 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001709 // When considering an associated namespace, the lookup is the
1710 // same as the lookup performed when the associated namespace is
1711 // used as a qualifier (3.4.3.2) except that:
1712 //
1713 // -- Any using-directives in the associated namespace are
1714 // ignored.
1715 //
John McCallc7e8e792009-08-07 22:18:02 +00001716 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001717 // associated classes are visible within their respective
1718 // namespaces even if they are not visible during an ordinary
1719 // lookup (11.4).
1720 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00001721 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCallc7e8e792009-08-07 22:18:02 +00001722 Decl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00001723 // If the only declaration here is an ordinary friend, consider
1724 // it only if it was declared in an associated classes.
1725 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00001726 DeclContext *LexDC = D->getLexicalDeclContext();
1727 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1728 continue;
1729 }
Mike Stump11289f42009-09-09 15:08:12 +00001730
Sebastian Redlc057f422009-10-23 19:23:15 +00001731 FunctionDecl *Fn;
1732 if (!Operator || !(Fn = dyn_cast<FunctionDecl>(D)) ||
1733 IsAcceptableNonMemberOperatorCandidate(Fn, T1, T2, Context))
1734 CollectFunctionDecl(Functions, D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00001735 }
1736 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001737}