blob: 9b91e2273925c8e4a14ff8e8c8e3492ca39ad8a0 [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 Gregor2d435302009-12-30 17:04:44 +000030#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000031#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000032#include <vector>
33#include <iterator>
34#include <utility>
35#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000036
37using namespace clang;
38
John McCallf6c8a4e2009-11-10 07:01:13 +000039namespace {
40 class UnqualUsingEntry {
41 const DeclContext *Nominated;
42 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000043
John McCallf6c8a4e2009-11-10 07:01:13 +000044 public:
45 UnqualUsingEntry(const DeclContext *Nominated,
46 const DeclContext *CommonAncestor)
47 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
48 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000049
John McCallf6c8a4e2009-11-10 07:01:13 +000050 const DeclContext *getCommonAncestor() const {
51 return CommonAncestor;
52 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000053
John McCallf6c8a4e2009-11-10 07:01:13 +000054 const DeclContext *getNominatedNamespace() const {
55 return Nominated;
56 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 // Sort by the pointer value of the common ancestor.
59 struct Comparator {
60 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
61 return L.getCommonAncestor() < R.getCommonAncestor();
62 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
65 return E.getCommonAncestor() < DC;
66 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000067
John McCallf6c8a4e2009-11-10 07:01:13 +000068 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
69 return DC < E.getCommonAncestor();
70 }
71 };
72 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 /// A collection of using directives, as used by C++ unqualified
75 /// lookup.
76 class UnqualUsingDirectiveSet {
77 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000078
John McCallf6c8a4e2009-11-10 07:01:13 +000079 ListTy list;
80 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 public:
83 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000084
John McCallf6c8a4e2009-11-10 07:01:13 +000085 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
86 // C++ [namespace.udir]p1:
87 // During unqualified name lookup, the names appear as if they
88 // were declared in the nearest enclosing namespace which contains
89 // both the using-directive and the nominated namespace.
90 DeclContext *InnermostFileDC
91 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
92 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +000095 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
96 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
97 visit(Ctx, EffectiveDC);
98 } else {
99 Scope::udir_iterator I = S->using_directives_begin(),
100 End = S->using_directives_end();
101
102 for (; I != End; ++I)
103 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
104 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000105 }
106 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000107
108 // Visits a context and collect all of its using directives
109 // recursively. Treats all using directives as if they were
110 // declared in the context.
111 //
112 // A given context is only every visited once, so it is important
113 // that contexts be visited from the inside out in order to get
114 // the effective DCs right.
115 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
116 if (!visited.insert(DC))
117 return;
118
119 addUsingDirectives(DC, EffectiveDC);
120 }
121
122 // Visits a using directive and collects all of its using
123 // directives recursively. Treats all using directives as if they
124 // were declared in the effective DC.
125 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
126 DeclContext *NS = UD->getNominatedNamespace();
127 if (!visited.insert(NS))
128 return;
129
130 addUsingDirective(UD, EffectiveDC);
131 addUsingDirectives(NS, EffectiveDC);
132 }
133
134 // Adds all the using directives in a context (and those nominated
135 // by its using directives, transitively) as if they appeared in
136 // the given effective context.
137 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
138 llvm::SmallVector<DeclContext*,4> queue;
139 while (true) {
140 DeclContext::udir_iterator I, End;
141 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
142 UsingDirectiveDecl *UD = *I;
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (visited.insert(NS)) {
145 addUsingDirective(UD, EffectiveDC);
146 queue.push_back(NS);
147 }
148 }
149
150 if (queue.empty())
151 return;
152
153 DC = queue.back();
154 queue.pop_back();
155 }
156 }
157
158 // Add a using directive as if it had been declared in the given
159 // context. This helps implement C++ [namespace.udir]p3:
160 // The using-directive is transitive: if a scope contains a
161 // using-directive that nominates a second namespace that itself
162 // contains using-directives, the effect is as if the
163 // using-directives from the second namespace also appeared in
164 // the first.
165 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
166 // Find the common ancestor between the effective context and
167 // the nominated namespace.
168 DeclContext *Common = UD->getNominatedNamespace();
169 while (!Common->Encloses(EffectiveDC))
170 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000171 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000172
173 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
174 }
175
176 void done() {
177 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
178 }
179
180 typedef ListTy::iterator iterator;
181 typedef ListTy::const_iterator const_iterator;
182
183 iterator begin() { return list.begin(); }
184 iterator end() { return list.end(); }
185 const_iterator begin() const { return list.begin(); }
186 const_iterator end() const { return list.end(); }
187
188 std::pair<const_iterator,const_iterator>
189 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000190 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000191 UnqualUsingEntry::Comparator());
192 }
193 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000194}
195
John McCallea305ed2009-12-18 10:40:03 +0000196static bool IsAcceptableIDNS(NamedDecl *D, unsigned IDNS) {
197 return D->isInIdentifierNamespace(IDNS);
198}
199
200static bool IsAcceptableOperatorName(NamedDecl *D, unsigned IDNS) {
201 return D->isInIdentifierNamespace(IDNS) &&
202 !D->getDeclContext()->isRecord();
203}
204
205static bool IsAcceptableNestedNameSpecifierName(NamedDecl *D, unsigned IDNS) {
John McCallc3f09ad2009-12-18 10:48:10 +0000206 // This lookup ignores everything that isn't a type.
207
208 // This is a fast check for the far most common case.
209 if (D->isInIdentifierNamespace(Decl::IDNS_Tag))
210 return true;
211
212 if (isa<UsingShadowDecl>(D))
213 D = cast<UsingShadowDecl>(D)->getTargetDecl();
214
215 return isa<TypeDecl>(D);
John McCallea305ed2009-12-18 10:40:03 +0000216}
217
218static bool IsAcceptableNamespaceName(NamedDecl *D, unsigned IDNS) {
John McCallc3f09ad2009-12-18 10:48:10 +0000219 // We don't need to look through using decls here because
220 // using decls aren't allowed to name namespaces.
221
John McCallea305ed2009-12-18 10:40:03 +0000222 return isa<NamespaceDecl>(D) || isa<NamespaceAliasDecl>(D);
223}
224
225/// Gets the default result filter for the given lookup.
226static inline
227LookupResult::ResultFilter getResultFilter(Sema::LookupNameKind NameKind) {
228 switch (NameKind) {
229 case Sema::LookupOrdinaryName:
230 case Sema::LookupTagName:
231 case Sema::LookupMemberName:
232 case Sema::LookupRedeclarationWithLinkage: // FIXME: check linkage, scoping
233 case Sema::LookupUsingDeclName:
234 case Sema::LookupObjCProtocolName:
235 case Sema::LookupObjCImplementationName:
236 return &IsAcceptableIDNS;
237
238 case Sema::LookupOperatorName:
239 return &IsAcceptableOperatorName;
240
241 case Sema::LookupNestedNameSpecifierName:
242 return &IsAcceptableNestedNameSpecifierName;
243
244 case Sema::LookupNamespaceName:
245 return &IsAcceptableNamespaceName;
246 }
247
248 llvm_unreachable("unkknown lookup kind");
249 return 0;
250}
251
Douglas Gregor889ceb72009-02-03 19:21:40 +0000252// Retrieve the set of identifier namespaces that correspond to a
253// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000254static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
255 bool CPlusPlus,
256 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000257 unsigned IDNS = 0;
258 switch (NameKind) {
259 case Sema::LookupOrdinaryName:
Douglas Gregor94eabf32009-02-04 16:44:47 +0000260 case Sema::LookupOperatorName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000261 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000262 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000263 if (CPlusPlus) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000264 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
John McCallea305ed2009-12-18 10:40:03 +0000265 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
266 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000267 break;
268
269 case Sema::LookupTagName:
270 IDNS = Decl::IDNS_Tag;
John McCallea305ed2009-12-18 10:40:03 +0000271 if (CPlusPlus && Redeclaration)
272 IDNS |= Decl::IDNS_TagFriend;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000273 break;
274
275 case Sema::LookupMemberName:
276 IDNS = Decl::IDNS_Member;
277 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000278 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000279 break;
280
281 case Sema::LookupNestedNameSpecifierName:
282 case Sema::LookupNamespaceName:
283 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
284 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000285
John McCall84d87672009-12-10 09:41:52 +0000286 case Sema::LookupUsingDeclName:
287 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
288 | Decl::IDNS_Member | Decl::IDNS_Using;
289 break;
290
Douglas Gregor79947a22009-04-24 00:11:27 +0000291 case Sema::LookupObjCProtocolName:
292 IDNS = Decl::IDNS_ObjCProtocol;
293 break;
294
295 case Sema::LookupObjCImplementationName:
296 IDNS = Decl::IDNS_ObjCImplementation;
297 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000298 }
299 return IDNS;
300}
301
John McCallea305ed2009-12-18 10:40:03 +0000302void LookupResult::configure() {
303 IDNS = getIDNS(LookupKind,
304 SemaRef.getLangOptions().CPlusPlus,
305 isForRedeclaration());
306 IsAcceptableFn = getResultFilter(LookupKind);
307}
308
John McCall9f3059a2009-10-09 21:13:30 +0000309// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000310void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000311 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000312}
313
John McCall283b9012009-11-22 00:44:51 +0000314/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000315void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000316 unsigned N = Decls.size();
John McCall84d87672009-12-10 09:41:52 +0000317
John McCall9f3059a2009-10-09 21:13:30 +0000318 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000319 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000320 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000321 return;
322 }
323
John McCall283b9012009-11-22 00:44:51 +0000324 // If there's a single decl, we need to examine it to decide what
325 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000326 if (N == 1) {
John McCallad371252010-01-20 00:46:10 +0000327 if (isa<FunctionTemplateDecl>(*Decls.begin()))
John McCall283b9012009-11-22 00:44:51 +0000328 ResultKind = FoundOverloaded;
John McCallad371252010-01-20 00:46:10 +0000329 else if (isa<UnresolvedUsingValueDecl>(*Decls.begin()))
John McCalle61f2ba2009-11-18 02:36:19 +0000330 ResultKind = FoundUnresolvedValue;
331 return;
332 }
John McCall9f3059a2009-10-09 21:13:30 +0000333
John McCall6538c932009-10-10 05:48:19 +0000334 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000335 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000336
John McCall9f3059a2009-10-09 21:13:30 +0000337 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
338
339 bool Ambiguous = false;
340 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000341 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000342
343 unsigned UniqueTagIndex = 0;
344
345 unsigned I = 0;
346 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000347 NamedDecl *D = Decls[I]->getUnderlyingDecl();
348 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000349
John McCallf0f1cf02009-11-17 07:50:12 +0000350 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000351 // If it's not unique, pull something off the back (and
352 // continue at this index).
353 Decls[I] = Decls[--N];
John McCall9f3059a2009-10-09 21:13:30 +0000354 } else {
355 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000356
357 if (isa<UnresolvedUsingValueDecl>(D)) {
358 HasUnresolved = true;
359 } else if (isa<TagDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000360 if (HasTag)
361 Ambiguous = true;
362 UniqueTagIndex = I;
363 HasTag = true;
John McCall283b9012009-11-22 00:44:51 +0000364 } else if (isa<FunctionTemplateDecl>(D)) {
365 HasFunction = true;
366 HasFunctionTemplate = true;
367 } else if (isa<FunctionDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000368 HasFunction = true;
369 } else {
370 if (HasNonFunction)
371 Ambiguous = true;
372 HasNonFunction = true;
373 }
374 I++;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000375 }
Mike Stump11289f42009-09-09 15:08:12 +0000376 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000377
John McCall9f3059a2009-10-09 21:13:30 +0000378 // C++ [basic.scope.hiding]p2:
379 // A class name or enumeration name can be hidden by the name of
380 // an object, function, or enumerator declared in the same
381 // scope. If a class or enumeration name and an object, function,
382 // or enumerator are declared in the same scope (in any order)
383 // with the same name, the class or enumeration name is hidden
384 // wherever the object, function, or enumerator name is visible.
385 // But it's still an error if there are distinct tag types found,
386 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000387 if (HideTags && HasTag && !Ambiguous &&
388 (HasFunction || HasNonFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000389 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000390
John McCall9f3059a2009-10-09 21:13:30 +0000391 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000392
John McCall80053822009-12-03 00:58:24 +0000393 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000394 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000395
John McCall9f3059a2009-10-09 21:13:30 +0000396 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000397 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000398 else if (HasUnresolved)
399 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000400 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000401 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000402 else
John McCall27b18f82009-11-17 02:14:36 +0000403 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000404}
405
John McCall5cebab12009-11-18 07:57:50 +0000406void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000407 CXXBasePaths::paths_iterator I, E;
408 DeclContext::lookup_iterator DI, DE;
409 for (I = P.begin(), E = P.end(); I != E; ++I)
410 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
411 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000412}
413
John McCall5cebab12009-11-18 07:57:50 +0000414void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000415 Paths = new CXXBasePaths;
416 Paths->swap(P);
417 addDeclsFromBasePaths(*Paths);
418 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000419 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000420}
421
John McCall5cebab12009-11-18 07:57:50 +0000422void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000423 Paths = new CXXBasePaths;
424 Paths->swap(P);
425 addDeclsFromBasePaths(*Paths);
426 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000427 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000428}
429
John McCall5cebab12009-11-18 07:57:50 +0000430void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000431 Out << Decls.size() << " result(s)";
432 if (isAmbiguous()) Out << ", ambiguous";
433 if (Paths) Out << ", base paths present";
434
435 for (iterator I = begin(), E = end(); I != E; ++I) {
436 Out << "\n";
437 (*I)->print(Out, 2);
438 }
439}
440
441// Adds all qualifying matches for a name within a decl context to the
442// given lookup result. Returns true if any matches were found.
John McCall5cebab12009-11-18 07:57:50 +0000443static bool LookupDirect(LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000444 bool Found = false;
445
John McCallf6c8a4e2009-11-10 07:01:13 +0000446 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000447 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000448 NamedDecl *D = *I;
449 if (R.isAcceptableDecl(D)) {
450 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000451 Found = true;
452 }
453 }
John McCall9f3059a2009-10-09 21:13:30 +0000454
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000455 if (R.getLookupName().getNameKind()
456 == DeclarationName::CXXConversionFunctionName &&
457 !R.getLookupName().getCXXNameType()->isDependentType() &&
458 isa<CXXRecordDecl>(DC)) {
459 // C++ [temp.mem]p6:
460 // A specialization of a conversion function template is not found by
461 // name lookup. Instead, any conversion function templates visible in the
462 // context of the use are considered. [...]
463 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregor3c96a462010-01-12 01:17:50 +0000464 if (!Record->isDefinition())
465 return Found;
466
John McCallad371252010-01-20 00:46:10 +0000467 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
468 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
469 UEnd = Unresolved->end(); U != UEnd; ++U) {
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000470 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
471 if (!ConvTemplate)
472 continue;
473
474 // When we're performing lookup for the purposes of redeclaration, just
475 // add the conversion function template. When we deduce template
476 // arguments for specializations, we'll end up unifying the return
477 // type of the new declaration with the type of the function template.
478 if (R.isForRedeclaration()) {
479 R.addDecl(ConvTemplate);
480 Found = true;
481 continue;
482 }
483
484 // C++ [temp.mem]p6:
485 // [...] For each such operator, if argument deduction succeeds
486 // (14.9.2.3), the resulting specialization is used as if found by
487 // name lookup.
488 //
489 // When referencing a conversion function for any purpose other than
490 // a redeclaration (such that we'll be building an expression with the
491 // result), perform template argument deduction and place the
492 // specialization into the result set. We do this to avoid forcing all
493 // callers to perform special deduction for conversion functions.
494 Sema::TemplateDeductionInfo Info(R.getSema().Context);
495 FunctionDecl *Specialization = 0;
496
497 const FunctionProtoType *ConvProto
498 = ConvTemplate->getTemplatedDecl()->getType()
499 ->getAs<FunctionProtoType>();
500 assert(ConvProto && "Nonsensical conversion function template type");
501
502 // Compute the type of the function that we would expect the conversion
503 // function to have, if it were to match the name given.
504 // FIXME: Calling convention!
505 QualType ExpectedType
506 = R.getSema().Context.getFunctionType(
507 R.getLookupName().getCXXNameType(),
508 0, 0, ConvProto->isVariadic(),
509 ConvProto->getTypeQuals(),
510 false, false, 0, 0,
511 ConvProto->getNoReturnAttr());
512
513 // Perform template argument deduction against the type that we would
514 // expect the function to have.
515 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
516 Specialization, Info)
517 == Sema::TDK_Success) {
518 R.addDecl(Specialization);
519 Found = true;
520 }
521 }
522 }
523
John McCall9f3059a2009-10-09 21:13:30 +0000524 return Found;
525}
526
John McCallf6c8a4e2009-11-10 07:01:13 +0000527// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000528static bool
John McCall5cebab12009-11-18 07:57:50 +0000529CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCall27b18f82009-11-17 02:14:36 +0000530 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000531
532 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
533
John McCallf6c8a4e2009-11-10 07:01:13 +0000534 // Perform direct name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000535 bool Found = LookupDirect(R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000536
John McCallf6c8a4e2009-11-10 07:01:13 +0000537 // Perform direct name lookup into the namespaces nominated by the
538 // using directives whose common ancestor is this namespace.
539 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
540 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000541
John McCallf6c8a4e2009-11-10 07:01:13 +0000542 for (; UI != UEnd; ++UI)
John McCall27b18f82009-11-17 02:14:36 +0000543 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000544 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000545
546 R.resolveKind();
547
548 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000549}
550
551static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000552 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000553 return Ctx->isFileContext();
554 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000555}
Douglas Gregored8f2882009-01-30 01:04:22 +0000556
Douglas Gregor7f737c02009-09-10 16:57:35 +0000557// Find the next outer declaration context corresponding to this scope.
558static DeclContext *findOuterContext(Scope *S) {
559 for (S = S->getParent(); S; S = S->getParent())
560 if (S->getEntity())
561 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
562
563 return 0;
564}
565
John McCall27b18f82009-11-17 02:14:36 +0000566bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000567 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000568
569 DeclarationName Name = R.getLookupName();
570
Douglas Gregor889ceb72009-02-03 19:21:40 +0000571 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000572 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000573 I = IdResolver.begin(Name),
574 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000575
Douglas Gregor889ceb72009-02-03 19:21:40 +0000576 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000577 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000578 // ...During unqualified name lookup (3.4.1), the names appear as if
579 // they were declared in the nearest enclosing namespace which contains
580 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000581 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000582 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000583 //
584 // For example:
585 // namespace A { int i; }
586 // void foo() {
587 // int i;
588 // {
589 // using namespace A;
590 // ++i; // finds local 'i', A::i appears at global scope
591 // }
592 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000593 //
Douglas Gregor700792c2009-02-05 19:25:20 +0000594 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000595 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000596 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000597 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000598 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000599 Found = true;
600 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000601 }
602 }
John McCall9f3059a2009-10-09 21:13:30 +0000603 if (Found) {
604 R.resolveKind();
605 return true;
606 }
607
Douglas Gregor700792c2009-02-05 19:25:20 +0000608 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregor7f737c02009-09-10 16:57:35 +0000609 DeclContext *OuterCtx = findOuterContext(S);
610 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
611 Ctx = Ctx->getLookupParent()) {
Douglas Gregora64c1e52009-12-08 15:38:36 +0000612 // We do not directly look into function or method contexts
613 // (since all local variables are found via the identifier
614 // changes) or in transparent contexts (since those entities
615 // will be found in the nearest enclosing non-transparent
616 // context).
617 if (Ctx->isFunctionOrMethod() || Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000618 continue;
619
620 // Perform qualified name lookup into this context.
621 // FIXME: In some cases, we know that every name that could be found by
622 // this qualified name lookup will also be on the identifier chain. For
623 // example, inside a class without any base classes, we never need to
624 // perform qualified lookup because all of the members are on top of the
625 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000626 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000627 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000628 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000629 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000630 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000631
John McCallf6c8a4e2009-11-10 07:01:13 +0000632 // Stop if we ran out of scopes.
633 // FIXME: This really, really shouldn't be happening.
634 if (!S) return false;
635
Douglas Gregor700792c2009-02-05 19:25:20 +0000636 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000637 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000638 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000639 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
640 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000641
John McCallf6c8a4e2009-11-10 07:01:13 +0000642 UnqualUsingDirectiveSet UDirs;
643 UDirs.visitScopeChain(Initial, S);
644 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000645
Douglas Gregor700792c2009-02-05 19:25:20 +0000646 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000647 // Unqualified name lookup in C++ requires looking into scopes
648 // that aren't strictly lexical, and therefore we walk through the
649 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000650
Douglas Gregor889ceb72009-02-03 19:21:40 +0000651 for (; S; S = S->getParent()) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000652 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregor88f3eb82010-01-11 22:40:45 +0000653 if (!Ctx || Ctx->isTransparentContext())
Douglas Gregorf2270432009-08-24 18:55:03 +0000654 continue;
655
Douglas Gregor700792c2009-02-05 19:25:20 +0000656 assert(Ctx && Ctx->isFileContext() &&
657 "We should have been looking only at file context here already.");
Douglas Gregor889ceb72009-02-03 19:21:40 +0000658
659 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000660 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000661 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000662 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000663 // We found something. Look for anything else in our scope
664 // with this same name and in an acceptable identifier
665 // namespace, so that we can construct an overload set if we
666 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000667 Found = true;
668 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000669 }
670 }
671
Douglas Gregor700792c2009-02-05 19:25:20 +0000672 // Look into context considering using-directives.
John McCall27b18f82009-11-17 02:14:36 +0000673 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
John McCall9f3059a2009-10-09 21:13:30 +0000674 Found = true;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000675
John McCall9f3059a2009-10-09 21:13:30 +0000676 if (Found) {
677 R.resolveKind();
678 return true;
679 }
680
John McCall27b18f82009-11-17 02:14:36 +0000681 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000682 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000683 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000684
John McCall9f3059a2009-10-09 21:13:30 +0000685 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000686}
687
Douglas Gregor34074322009-01-14 22:20:51 +0000688/// @brief Perform unqualified name lookup starting from a given
689/// scope.
690///
691/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
692/// used to find names within the current scope. For example, 'x' in
693/// @code
694/// int x;
695/// int f() {
696/// return x; // unqualified name look finds 'x' in the global scope
697/// }
698/// @endcode
699///
700/// Different lookup criteria can find different names. For example, a
701/// particular scope can have both a struct and a function of the same
702/// name, and each can be found by certain lookup criteria. For more
703/// information about lookup criteria, see the documentation for the
704/// class LookupCriteria.
705///
706/// @param S The scope from which unqualified name lookup will
707/// begin. If the lookup criteria permits, name lookup may also search
708/// in the parent scopes.
709///
710/// @param Name The name of the entity that we are searching for.
711///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000712/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000713/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000714/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000715///
716/// @returns The result of name lookup, which includes zero or more
717/// declarations and possibly additional information used to diagnose
718/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000719bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
720 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +0000721 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000722
John McCall27b18f82009-11-17 02:14:36 +0000723 LookupNameKind NameKind = R.getLookupKind();
724
Douglas Gregor34074322009-01-14 22:20:51 +0000725 if (!getLangOptions().CPlusPlus) {
726 // Unqualified name lookup in C/Objective-C is purely lexical, so
727 // search in the declarations attached to the name.
728
John McCallea305ed2009-12-18 10:40:03 +0000729 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000730 // Find the nearest non-transparent declaration scope.
731 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000732 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000733 static_cast<DeclContext *>(S->getEntity())
734 ->isTransparentContext()))
735 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +0000736 }
737
John McCallea305ed2009-12-18 10:40:03 +0000738 unsigned IDNS = R.getIdentifierNamespace();
739
Douglas Gregor34074322009-01-14 22:20:51 +0000740 // Scan up the scope chain looking for a decl that matches this
741 // identifier that is in the appropriate namespace. This search
742 // should not take long, as shadowing of names is uncommon, and
743 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000744 bool LeftStartingScope = false;
745
Douglas Gregored8f2882009-01-30 01:04:22 +0000746 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000747 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000748 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000749 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000750 if (NameKind == LookupRedeclarationWithLinkage) {
751 // Determine whether this (or a previous) declaration is
752 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000753 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000754 LeftStartingScope = true;
755
756 // If we found something outside of our starting scope that
757 // does not have linkage, skip it.
758 if (LeftStartingScope && !((*I)->hasLinkage()))
759 continue;
760 }
761
John McCall9f3059a2009-10-09 21:13:30 +0000762 R.addDecl(*I);
763
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000764 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000765 // If this declaration has the "overloadable" attribute, we
766 // might have a set of overloaded functions.
767
768 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000769 while (!(S->getFlags() & Scope::DeclScope) ||
770 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000771 S = S->getParent();
772
773 // Find the last declaration in this scope (with the same
774 // name, naturally).
775 IdentifierResolver::iterator LastI = I;
776 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000777 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000778 break;
John McCall9f3059a2009-10-09 21:13:30 +0000779 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000780 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000781 }
782
John McCall9f3059a2009-10-09 21:13:30 +0000783 R.resolveKind();
784
785 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000786 }
Douglas Gregor34074322009-01-14 22:20:51 +0000787 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000788 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000789 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +0000790 return true;
Douglas Gregor34074322009-01-14 22:20:51 +0000791 }
792
793 // If we didn't find a use of this identifier, and if the identifier
794 // corresponds to a compiler builtin, create the decl object for the builtin
795 // now, injecting it into translation unit scope, and return it.
Mike Stump11289f42009-09-09 15:08:12 +0000796 if (NameKind == LookupOrdinaryName ||
Douglas Gregoreddf4332009-02-24 20:03:32 +0000797 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor34074322009-01-14 22:20:51 +0000798 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000799 if (II && AllowBuiltinCreation) {
Douglas Gregor34074322009-01-14 22:20:51 +0000800 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000801 if (unsigned BuiltinID = II->getBuiltinID()) {
802 // In C++, we don't have any predefined library functions like
803 // 'malloc'. Instead, we'll just error.
Mike Stump11289f42009-09-09 15:08:12 +0000804 if (getLangOptions().CPlusPlus &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000805 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCall9f3059a2009-10-09 21:13:30 +0000806 return false;
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000807
John McCall9f3059a2009-10-09 21:13:30 +0000808 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCall27b18f82009-11-17 02:14:36 +0000809 S, R.isForRedeclaration(),
810 R.getNameLoc());
John McCall9f3059a2009-10-09 21:13:30 +0000811 if (D) R.addDecl(D);
812 return (D != NULL);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000813 }
Douglas Gregor34074322009-01-14 22:20:51 +0000814 }
Douglas Gregor34074322009-01-14 22:20:51 +0000815 }
John McCall9f3059a2009-10-09 21:13:30 +0000816 return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000817}
818
John McCall6538c932009-10-10 05:48:19 +0000819/// @brief Perform qualified name lookup in the namespaces nominated by
820/// using directives by the given context.
821///
822/// C++98 [namespace.qual]p2:
823/// Given X::m (where X is a user-declared namespace), or given ::m
824/// (where X is the global namespace), let S be the set of all
825/// declarations of m in X and in the transitive closure of all
826/// namespaces nominated by using-directives in X and its used
827/// namespaces, except that using-directives are ignored in any
828/// namespace, including X, directly containing one or more
829/// declarations of m. No namespace is searched more than once in
830/// the lookup of a name. If S is the empty set, the program is
831/// ill-formed. Otherwise, if S has exactly one member, or if the
832/// context of the reference is a using-declaration
833/// (namespace.udecl), S is the required set of declarations of
834/// m. Otherwise if the use of m is not one that allows a unique
835/// declaration to be chosen from S, the program is ill-formed.
836/// C++98 [namespace.qual]p5:
837/// During the lookup of a qualified namespace member name, if the
838/// lookup finds more than one declaration of the member, and if one
839/// declaration introduces a class name or enumeration name and the
840/// other declarations either introduce the same object, the same
841/// enumerator or a set of functions, the non-type name hides the
842/// class or enumeration name if and only if the declarations are
843/// from the same namespace; otherwise (the declarations are from
844/// different namespaces), the program is ill-formed.
John McCall5cebab12009-11-18 07:57:50 +0000845static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +0000846 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +0000847 assert(StartDC->isFileContext() && "start context is not a file context");
848
849 DeclContext::udir_iterator I = StartDC->using_directives_begin();
850 DeclContext::udir_iterator E = StartDC->using_directives_end();
851
852 if (I == E) return false;
853
854 // We have at least added all these contexts to the queue.
855 llvm::DenseSet<DeclContext*> Visited;
856 Visited.insert(StartDC);
857
858 // We have not yet looked into these namespaces, much less added
859 // their "using-children" to the queue.
860 llvm::SmallVector<NamespaceDecl*, 8> Queue;
861
862 // We have already looked into the initial namespace; seed the queue
863 // with its using-children.
864 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +0000865 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +0000866 if (Visited.insert(ND).second)
867 Queue.push_back(ND);
868 }
869
870 // The easiest way to implement the restriction in [namespace.qual]p5
871 // is to check whether any of the individual results found a tag
872 // and, if so, to declare an ambiguity if the final result is not
873 // a tag.
874 bool FoundTag = false;
875 bool FoundNonTag = false;
876
John McCall5cebab12009-11-18 07:57:50 +0000877 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +0000878
879 bool Found = false;
880 while (!Queue.empty()) {
881 NamespaceDecl *ND = Queue.back();
882 Queue.pop_back();
883
884 // We go through some convolutions here to avoid copying results
885 // between LookupResults.
886 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +0000887 LookupResult &DirectR = UseLocal ? LocalR : R;
John McCall27b18f82009-11-17 02:14:36 +0000888 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +0000889
890 if (FoundDirect) {
891 // First do any local hiding.
892 DirectR.resolveKind();
893
894 // If the local result is a tag, remember that.
895 if (DirectR.isSingleTagDecl())
896 FoundTag = true;
897 else
898 FoundNonTag = true;
899
900 // Append the local results to the total results if necessary.
901 if (UseLocal) {
902 R.addAllDecls(LocalR);
903 LocalR.clear();
904 }
905 }
906
907 // If we find names in this namespace, ignore its using directives.
908 if (FoundDirect) {
909 Found = true;
910 continue;
911 }
912
913 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
914 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
915 if (Visited.insert(Nom).second)
916 Queue.push_back(Nom);
917 }
918 }
919
920 if (Found) {
921 if (FoundTag && FoundNonTag)
922 R.setAmbiguousQualifiedTagHiding();
923 else
924 R.resolveKind();
925 }
926
927 return Found;
928}
929
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000930/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +0000931///
932/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
933/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000934/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +0000935///
936/// Different lookup criteria can find different names. For example, a
937/// particular scope can have both a struct and a function of the same
938/// name, and each can be found by certain lookup criteria. For more
939/// information about lookup criteria, see the documentation for the
940/// class LookupCriteria.
941///
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000942/// \param R captures both the lookup criteria and any lookup results found.
943///
944/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +0000945/// search. If the lookup criteria permits, name lookup may also search
946/// in the parent contexts or (for C++ classes) base classes.
947///
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000948/// \param InUnqualifiedLookup true if this is qualified name lookup that
949/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +0000950///
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000951/// \returns true if lookup succeeded, false if it failed.
952bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
953 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +0000954 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +0000955
John McCall27b18f82009-11-17 02:14:36 +0000956 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +0000957 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000958
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000959 // Make sure that the declaration context is complete.
960 assert((!isa<TagDecl>(LookupCtx) ||
961 LookupCtx->isDependentContext() ||
962 cast<TagDecl>(LookupCtx)->isDefinition() ||
963 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
964 ->isBeingDefined()) &&
965 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +0000966
Douglas Gregor34074322009-01-14 22:20:51 +0000967 // Perform qualified name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000968 if (LookupDirect(R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +0000969 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +0000970 if (isa<CXXRecordDecl>(LookupCtx))
971 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +0000972 return true;
973 }
Douglas Gregor34074322009-01-14 22:20:51 +0000974
John McCall6538c932009-10-10 05:48:19 +0000975 // Don't descend into implied contexts for redeclarations.
976 // C++98 [namespace.qual]p6:
977 // In a declaration for a namespace member in which the
978 // declarator-id is a qualified-id, given that the qualified-id
979 // for the namespace member has the form
980 // nested-name-specifier unqualified-id
981 // the unqualified-id shall name a member of the namespace
982 // designated by the nested-name-specifier.
983 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +0000984 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +0000985 return false;
986
John McCall27b18f82009-11-17 02:14:36 +0000987 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +0000988 if (LookupCtx->isFileContext())
John McCall27b18f82009-11-17 02:14:36 +0000989 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +0000990
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000991 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +0000992 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000993 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
994 if (!LookupRec)
John McCall9f3059a2009-10-09 21:13:30 +0000995 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000996
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000997 // If we're performing qualified name lookup into a dependent class,
998 // then we are actually looking into a current instantiation. If we have any
999 // dependent base classes, then we either have to delay lookup until
1000 // template instantiation time (at which point all bases will be available)
1001 // or we have to fail.
1002 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1003 LookupRec->hasAnyDependentBases()) {
1004 R.setNotFoundInCurrentInstantiation();
1005 return false;
1006 }
1007
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001008 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001009 CXXBasePaths Paths;
1010 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001011
1012 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001013 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001014 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001015 case LookupOrdinaryName:
1016 case LookupMemberName:
1017 case LookupRedeclarationWithLinkage:
1018 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1019 break;
1020
1021 case LookupTagName:
1022 BaseCallback = &CXXRecordDecl::FindTagMember;
1023 break;
John McCall84d87672009-12-10 09:41:52 +00001024
1025 case LookupUsingDeclName:
1026 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001027
1028 case LookupOperatorName:
1029 case LookupNamespaceName:
1030 case LookupObjCProtocolName:
1031 case LookupObjCImplementationName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001032 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001033 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001034
1035 case LookupNestedNameSpecifierName:
1036 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1037 break;
1038 }
1039
John McCall27b18f82009-11-17 02:14:36 +00001040 if (!LookupRec->lookupInBases(BaseCallback,
1041 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001042 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001043
John McCall553c0792010-01-23 00:46:32 +00001044 R.setNamingClass(LookupRec);
1045
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001046 // C++ [class.member.lookup]p2:
1047 // [...] If the resulting set of declarations are not all from
1048 // sub-objects of the same type, or the set has a nonstatic member
1049 // and includes members from distinct sub-objects, there is an
1050 // ambiguity and the program is ill-formed. Otherwise that set is
1051 // the result of the lookup.
1052 // FIXME: support using declarations!
1053 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001054 int SubobjectNumber = 0;
John McCall401982f2010-01-20 21:53:11 +00001055 AccessSpecifier SubobjectAccess = AS_private;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001056 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001057 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001058 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001059
John McCall401982f2010-01-20 21:53:11 +00001060 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1061 // across all paths.
1062 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1063
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001064 // Determine whether we're looking at a distinct sub-object or not.
1065 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001066 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001067 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1068 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001069 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001070 != Context.getCanonicalType(PathElement.Base->getType())) {
1071 // We found members of the given name in two subobjects of
1072 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001073 R.setAmbiguousBaseSubobjectTypes(Paths);
1074 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001075 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1076 // We have a different subobject of the same type.
1077
1078 // C++ [class.member.lookup]p5:
1079 // A static member, a nested type or an enumerator defined in
1080 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001081 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001082 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001083 if (isa<VarDecl>(FirstDecl) ||
1084 isa<TypeDecl>(FirstDecl) ||
1085 isa<EnumConstantDecl>(FirstDecl))
1086 continue;
1087
1088 if (isa<CXXMethodDecl>(FirstDecl)) {
1089 // Determine whether all of the methods are static.
1090 bool AllMethodsAreStatic = true;
1091 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1092 Func != Path->Decls.second; ++Func) {
1093 if (!isa<CXXMethodDecl>(*Func)) {
1094 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1095 break;
1096 }
1097
1098 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1099 AllMethodsAreStatic = false;
1100 break;
1101 }
1102 }
1103
1104 if (AllMethodsAreStatic)
1105 continue;
1106 }
1107
1108 // We have found a nonstatic member name in multiple, distinct
1109 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001110 R.setAmbiguousBaseSubobjects(Paths);
1111 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001112 }
1113 }
1114
1115 // Lookup in a base class succeeded; return these results.
1116
John McCall9f3059a2009-10-09 21:13:30 +00001117 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001118 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1119 NamedDecl *D = *I;
1120 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1121 D->getAccess());
1122 R.addDecl(D, AS);
1123 }
John McCall9f3059a2009-10-09 21:13:30 +00001124 R.resolveKind();
1125 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001126}
1127
1128/// @brief Performs name lookup for a name that was parsed in the
1129/// source code, and may contain a C++ scope specifier.
1130///
1131/// This routine is a convenience routine meant to be called from
1132/// contexts that receive a name and an optional C++ scope specifier
1133/// (e.g., "N::M::x"). It will then perform either qualified or
1134/// unqualified name lookup (with LookupQualifiedName or LookupName,
1135/// respectively) on the given name and return those results.
1136///
1137/// @param S The scope from which unqualified name lookup will
1138/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001139///
Douglas Gregore861bac2009-08-25 22:51:20 +00001140/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001141///
1142/// @param Name The name of the entity that name lookup will
1143/// search for.
1144///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001145/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001146/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001147/// C library functions (like "malloc") are implicitly declared.
1148///
Douglas Gregore861bac2009-08-25 22:51:20 +00001149/// @param EnteringContext Indicates whether we are going to enter the
1150/// context of the scope-specifier SS (if present).
1151///
John McCall9f3059a2009-10-09 21:13:30 +00001152/// @returns True if any decls were found (but possibly ambiguous)
1153bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001154 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001155 if (SS && SS->isInvalid()) {
1156 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001157 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001158 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001159 }
Mike Stump11289f42009-09-09 15:08:12 +00001160
Douglas Gregore861bac2009-08-25 22:51:20 +00001161 if (SS && SS->isSet()) {
1162 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001163 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001164 // contex, and will perform name lookup in that context.
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001165 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCall9f3059a2009-10-09 21:13:30 +00001166 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001167
John McCall27b18f82009-11-17 02:14:36 +00001168 R.setContextRange(SS->getRange());
1169
1170 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001171 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001172
Douglas Gregore861bac2009-08-25 22:51:20 +00001173 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001174 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001175 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001176 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001177 }
1178
Mike Stump11289f42009-09-09 15:08:12 +00001179 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001180 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001181}
1182
Douglas Gregor889ceb72009-02-03 19:21:40 +00001183
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001184/// @brief Produce a diagnostic describing the ambiguity that resulted
1185/// from name lookup.
1186///
1187/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001188///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001189/// @param Name The name of the entity that name lookup was
1190/// searching for.
1191///
1192/// @param NameLoc The location of the name within the source code.
1193///
1194/// @param LookupRange A source range that provides more
1195/// source-location information concerning the lookup itself. For
1196/// example, this range might highlight a nested-name-specifier that
1197/// precedes the name.
1198///
1199/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001200bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001201 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1202
John McCall27b18f82009-11-17 02:14:36 +00001203 DeclarationName Name = Result.getLookupName();
1204 SourceLocation NameLoc = Result.getNameLoc();
1205 SourceRange LookupRange = Result.getContextRange();
1206
John McCall6538c932009-10-10 05:48:19 +00001207 switch (Result.getAmbiguityKind()) {
1208 case LookupResult::AmbiguousBaseSubobjects: {
1209 CXXBasePaths *Paths = Result.getBasePaths();
1210 QualType SubobjectType = Paths->front().back().Base->getType();
1211 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1212 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1213 << LookupRange;
1214
1215 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1216 while (isa<CXXMethodDecl>(*Found) &&
1217 cast<CXXMethodDecl>(*Found)->isStatic())
1218 ++Found;
1219
1220 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1221
1222 return true;
1223 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001224
John McCall6538c932009-10-10 05:48:19 +00001225 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001226 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1227 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001228
1229 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001230 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001231 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1232 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001233 Path != PathEnd; ++Path) {
1234 Decl *D = *Path->Decls.first;
1235 if (DeclsPrinted.insert(D).second)
1236 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1237 }
1238
Douglas Gregor1c846b02009-01-16 00:38:09 +00001239 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001240 }
1241
John McCall6538c932009-10-10 05:48:19 +00001242 case LookupResult::AmbiguousTagHiding: {
1243 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001244
John McCall6538c932009-10-10 05:48:19 +00001245 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1246
1247 LookupResult::iterator DI, DE = Result.end();
1248 for (DI = Result.begin(); DI != DE; ++DI)
1249 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1250 TagDecls.insert(TD);
1251 Diag(TD->getLocation(), diag::note_hidden_tag);
1252 }
1253
1254 for (DI = Result.begin(); DI != DE; ++DI)
1255 if (!isa<TagDecl>(*DI))
1256 Diag((*DI)->getLocation(), diag::note_hiding_object);
1257
1258 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001259 LookupResult::Filter F = Result.makeFilter();
1260 while (F.hasNext()) {
1261 if (TagDecls.count(F.next()))
1262 F.erase();
1263 }
1264 F.done();
John McCall6538c932009-10-10 05:48:19 +00001265
1266 return true;
1267 }
1268
1269 case LookupResult::AmbiguousReference: {
1270 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001271
John McCall6538c932009-10-10 05:48:19 +00001272 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1273 for (; DI != DE; ++DI)
1274 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001275
John McCall6538c932009-10-10 05:48:19 +00001276 return true;
1277 }
1278 }
1279
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001280 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001281 return true;
1282}
Douglas Gregore254f902009-02-04 00:32:51 +00001283
Mike Stump11289f42009-09-09 15:08:12 +00001284static void
1285addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001286 ASTContext &Context,
1287 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001288 Sema::AssociatedClassSet &AssociatedClasses);
1289
1290static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1291 DeclContext *Ctx) {
1292 if (Ctx->isFileContext())
1293 Namespaces.insert(Ctx);
1294}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001295
Mike Stump11289f42009-09-09 15:08:12 +00001296// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001297// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001298static void
1299addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001300 ASTContext &Context,
1301 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001302 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001303 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001304 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001305 switch (Arg.getKind()) {
1306 case TemplateArgument::Null:
1307 break;
Mike Stump11289f42009-09-09 15:08:12 +00001308
Douglas Gregor197e5f72009-07-08 07:51:57 +00001309 case TemplateArgument::Type:
1310 // [...] the namespaces and classes associated with the types of the
1311 // template arguments provided for template type parameters (excluding
1312 // template template parameters)
1313 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1314 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001315 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001316 break;
Mike Stump11289f42009-09-09 15:08:12 +00001317
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001318 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001319 // [...] the namespaces in which any template template arguments are
1320 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001321 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001322 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001323 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001324 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001325 DeclContext *Ctx = ClassTemplate->getDeclContext();
1326 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1327 AssociatedClasses.insert(EnclosingClass);
1328 // Add the associated namespace for this class.
1329 while (Ctx->isRecord())
1330 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001331 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001332 }
1333 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001334 }
1335
1336 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001337 case TemplateArgument::Integral:
1338 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001339 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001340 // associated namespaces. ]
1341 break;
Mike Stump11289f42009-09-09 15:08:12 +00001342
Douglas Gregor197e5f72009-07-08 07:51:57 +00001343 case TemplateArgument::Pack:
1344 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1345 PEnd = Arg.pack_end();
1346 P != PEnd; ++P)
1347 addAssociatedClassesAndNamespaces(*P, Context,
1348 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001349 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001350 break;
1351 }
1352}
1353
Douglas Gregore254f902009-02-04 00:32:51 +00001354// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001355// argument-dependent lookup with an argument of class type
1356// (C++ [basic.lookup.koenig]p2).
1357static void
1358addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregore254f902009-02-04 00:32:51 +00001359 ASTContext &Context,
1360 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001361 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001362 // C++ [basic.lookup.koenig]p2:
1363 // [...]
1364 // -- If T is a class type (including unions), its associated
1365 // classes are: the class itself; the class of which it is a
1366 // member, if any; and its direct and indirect base
1367 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001368 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001369
1370 // Add the class of which it is a member, if any.
1371 DeclContext *Ctx = Class->getDeclContext();
1372 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1373 AssociatedClasses.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001374 // Add the associated namespace for this class.
1375 while (Ctx->isRecord())
1376 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001377 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001378
Douglas Gregore254f902009-02-04 00:32:51 +00001379 // Add the class itself. If we've already seen this class, we don't
1380 // need to visit base classes.
1381 if (!AssociatedClasses.insert(Class))
1382 return;
1383
Mike Stump11289f42009-09-09 15:08:12 +00001384 // -- If T is a template-id, its associated namespaces and classes are
1385 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001386 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001387 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001388 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001389 // namespaces in which any template template arguments are defined; and
1390 // the classes in which any member templates used as template template
1391 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001392 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001393 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001394 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1395 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1396 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1397 AssociatedClasses.insert(EnclosingClass);
1398 // Add the associated namespace for this class.
1399 while (Ctx->isRecord())
1400 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001401 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001402
Douglas Gregor197e5f72009-07-08 07:51:57 +00001403 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1404 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1405 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1406 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001407 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001408 }
Mike Stump11289f42009-09-09 15:08:12 +00001409
Douglas Gregore254f902009-02-04 00:32:51 +00001410 // Add direct and indirect base classes along with their associated
1411 // namespaces.
1412 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1413 Bases.push_back(Class);
1414 while (!Bases.empty()) {
1415 // Pop this class off the stack.
1416 Class = Bases.back();
1417 Bases.pop_back();
1418
1419 // Visit the base classes.
1420 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1421 BaseEnd = Class->bases_end();
1422 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001423 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001424 // In dependent contexts, we do ADL twice, and the first time around,
1425 // the base type might be a dependent TemplateSpecializationType, or a
1426 // TemplateTypeParmType. If that happens, simply ignore it.
1427 // FIXME: If we want to support export, we probably need to add the
1428 // namespace of the template in a TemplateSpecializationType, or even
1429 // the classes and namespaces of known non-dependent arguments.
1430 if (!BaseType)
1431 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001432 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1433 if (AssociatedClasses.insert(BaseDecl)) {
1434 // Find the associated namespace for this base class.
1435 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1436 while (BaseCtx->isRecord())
1437 BaseCtx = BaseCtx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001438 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001439
1440 // Make sure we visit the bases of this base class.
1441 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1442 Bases.push_back(BaseDecl);
1443 }
1444 }
1445 }
1446}
1447
1448// \brief Add the associated classes and namespaces for
1449// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001450// (C++ [basic.lookup.koenig]p2).
1451static void
1452addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregore254f902009-02-04 00:32:51 +00001453 ASTContext &Context,
1454 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001455 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001456 // C++ [basic.lookup.koenig]p2:
1457 //
1458 // For each argument type T in the function call, there is a set
1459 // of zero or more associated namespaces and a set of zero or more
1460 // associated classes to be considered. The sets of namespaces and
1461 // classes is determined entirely by the types of the function
1462 // arguments (and the namespace of any template template
1463 // argument). Typedef names and using-declarations used to specify
1464 // the types do not contribute to this set. The sets of namespaces
1465 // and classes are determined in the following way:
1466 T = Context.getCanonicalType(T).getUnqualifiedType();
1467
1468 // -- If T is a pointer to U or an array of U, its associated
Mike Stump11289f42009-09-09 15:08:12 +00001469 // namespaces and classes are those associated with U.
Douglas Gregore254f902009-02-04 00:32:51 +00001470 //
1471 // We handle this by unwrapping pointer and array types immediately,
1472 // to avoid unnecessary recursion.
1473 while (true) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001474 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001475 T = Ptr->getPointeeType();
1476 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1477 T = Ptr->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001478 else
Douglas Gregore254f902009-02-04 00:32:51 +00001479 break;
1480 }
1481
1482 // -- If T is a fundamental type, its associated sets of
1483 // namespaces and classes are both empty.
John McCall9dd450b2009-09-21 23:43:11 +00001484 if (T->getAs<BuiltinType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001485 return;
1486
1487 // -- If T is a class type (including unions), its associated
1488 // classes are: the class itself; the class of which it is a
1489 // member, if any; and its direct and indirect base
1490 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001491 // which its associated classes are defined.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001492 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump11289f42009-09-09 15:08:12 +00001493 if (CXXRecordDecl *ClassDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001494 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001495 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1496 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001497 AssociatedClasses);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001498 return;
1499 }
Douglas Gregore254f902009-02-04 00:32:51 +00001500
1501 // -- If T is an enumeration type, its associated namespace is
1502 // the namespace in which it is defined. If it is class
1503 // member, its associated class is the member’s class; else
Mike Stump11289f42009-09-09 15:08:12 +00001504 // it has no associated class.
John McCall9dd450b2009-09-21 23:43:11 +00001505 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001506 EnumDecl *Enum = EnumT->getDecl();
1507
1508 DeclContext *Ctx = Enum->getDeclContext();
1509 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1510 AssociatedClasses.insert(EnclosingClass);
1511
1512 // Add the associated namespace for this class.
1513 while (Ctx->isRecord())
1514 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001515 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001516
1517 return;
1518 }
1519
1520 // -- If T is a function type, its associated namespaces and
1521 // classes are those associated with the function parameter
1522 // types and those associated with the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001523 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001524 // Return type
John McCall9dd450b2009-09-21 23:43:11 +00001525 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregore254f902009-02-04 00:32:51 +00001526 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001527 AssociatedNamespaces, AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001528
John McCall9dd450b2009-09-21 23:43:11 +00001529 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregore254f902009-02-04 00:32:51 +00001530 if (!Proto)
1531 return;
1532
1533 // Argument types
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001534 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001535 ArgEnd = Proto->arg_type_end();
Douglas Gregore254f902009-02-04 00:32:51 +00001536 Arg != ArgEnd; ++Arg)
1537 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallc7e8e792009-08-07 22:18:02 +00001538 AssociatedNamespaces, AssociatedClasses);
Mike Stump11289f42009-09-09 15:08:12 +00001539
Douglas Gregore254f902009-02-04 00:32:51 +00001540 return;
1541 }
1542
1543 // -- If T is a pointer to a member function of a class X, its
1544 // associated namespaces and classes are those associated
1545 // with the function parameter types and return type,
Mike Stump11289f42009-09-09 15:08:12 +00001546 // together with those associated with X.
Douglas Gregore254f902009-02-04 00:32:51 +00001547 //
1548 // -- If T is a pointer to a data member of class X, its
1549 // associated namespaces and classes are those associated
1550 // with the member type together with those associated with
Mike Stump11289f42009-09-09 15:08:12 +00001551 // X.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001552 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001553 // Handle the type that the pointer to member points to.
1554 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1555 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001556 AssociatedNamespaces,
1557 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001558
1559 // Handle the class type into which this points.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001560 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001561 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1562 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001563 AssociatedNamespaces,
1564 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001565
1566 return;
1567 }
1568
1569 // FIXME: What about block pointers?
1570 // FIXME: What about Objective-C message sends?
1571}
1572
1573/// \brief Find the associated classes and namespaces for
1574/// argument-dependent lookup for a call with the given set of
1575/// arguments.
1576///
1577/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001578/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001579/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001580void
Douglas Gregore254f902009-02-04 00:32:51 +00001581Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1582 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001583 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001584 AssociatedNamespaces.clear();
1585 AssociatedClasses.clear();
1586
1587 // C++ [basic.lookup.koenig]p2:
1588 // For each argument type T in the function call, there is a set
1589 // of zero or more associated namespaces and a set of zero or more
1590 // associated classes to be considered. The sets of namespaces and
1591 // classes is determined entirely by the types of the function
1592 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001593 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001594 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1595 Expr *Arg = Args[ArgIdx];
1596
1597 if (Arg->getType() != Context.OverloadTy) {
1598 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001599 AssociatedNamespaces,
1600 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001601 continue;
1602 }
1603
1604 // [...] In addition, if the argument is the name or address of a
1605 // set of overloaded functions and/or function templates, its
1606 // associated classes and namespaces are the union of those
1607 // associated with each of the members of the set: the namespace
1608 // in which the function or function template is defined and the
1609 // classes and namespaces associated with its (non-dependent)
1610 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001611 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001612 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1613 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1614 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001615
John McCalld14a8642009-11-21 08:51:07 +00001616 // TODO: avoid the copies. This should be easy when the cases
1617 // share a storage implementation.
1618 llvm::SmallVector<NamedDecl*, 8> Functions;
1619
1620 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1621 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00001622 else
Douglas Gregore254f902009-02-04 00:32:51 +00001623 continue;
1624
John McCalld14a8642009-11-21 08:51:07 +00001625 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1626 E = Functions.end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001627 // Look through any using declarations to find the underlying function.
1628 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001629
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001630 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1631 if (!FDecl)
1632 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001633
1634 // Add the classes and namespaces associated with the parameter
1635 // types and return type of this function.
1636 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001637 AssociatedNamespaces,
1638 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001639 }
1640 }
1641}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001642
1643/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1644/// an acceptable non-member overloaded operator for a call whose
1645/// arguments have types T1 (and, if non-empty, T2). This routine
1646/// implements the check in C++ [over.match.oper]p3b2 concerning
1647/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001648static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001649IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1650 QualType T1, QualType T2,
1651 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001652 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1653 return true;
1654
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001655 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1656 return true;
1657
John McCall9dd450b2009-09-21 23:43:11 +00001658 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001659 if (Proto->getNumArgs() < 1)
1660 return false;
1661
1662 if (T1->isEnumeralType()) {
1663 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001664 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001665 return true;
1666 }
1667
1668 if (Proto->getNumArgs() < 2)
1669 return false;
1670
1671 if (!T2.isNull() && T2->isEnumeralType()) {
1672 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001673 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001674 return true;
1675 }
1676
1677 return false;
1678}
1679
John McCall5cebab12009-11-18 07:57:50 +00001680NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1681 LookupNameKind NameKind,
1682 RedeclarationKind Redecl) {
1683 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1684 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00001685 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00001686}
1687
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001688/// \brief Find the protocol with the given name, if any.
1689ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001690 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001691 return cast_or_null<ObjCProtocolDecl>(D);
1692}
1693
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001694void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001695 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00001696 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001697 // C++ [over.match.oper]p3:
1698 // -- The set of non-member candidates is the result of the
1699 // unqualified lookup of operator@ in the context of the
1700 // expression according to the usual rules for name lookup in
1701 // unqualified function calls (3.4.2) except that all member
1702 // functions are ignored. However, if no operand has a class
1703 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001704 // that have a first parameter of type T1 or "reference to
1705 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001706 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001707 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001708 // when T2 is an enumeration type, are candidate functions.
1709 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00001710 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1711 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00001712
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001713 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1714
John McCall9f3059a2009-10-09 21:13:30 +00001715 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001716 return;
1717
1718 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1719 Op != OpEnd; ++Op) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001720 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001721 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
John McCall4c4c1df2010-01-26 03:27:55 +00001722 Functions.addDecl(FD, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001723 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor15448f82009-06-27 21:05:07 +00001724 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1725 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001726 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001727 // later?
1728 if (!FunTmpl->getDeclContext()->isRecord())
John McCall4c4c1df2010-01-26 03:27:55 +00001729 Functions.addDecl(FunTmpl, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00001730 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001731 }
1732}
1733
John McCall8fe68082010-01-26 07:16:45 +00001734void ADLResult::insert(NamedDecl *New) {
1735 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1736
1737 // If we haven't yet seen a decl for this key, or the last decl
1738 // was exactly this one, we're done.
1739 if (Old == 0 || Old == New) {
1740 Old = New;
1741 return;
1742 }
1743
1744 // Otherwise, decide which is a more recent redeclaration.
1745 FunctionDecl *OldFD, *NewFD;
1746 if (isa<FunctionTemplateDecl>(New)) {
1747 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1748 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1749 } else {
1750 OldFD = cast<FunctionDecl>(Old);
1751 NewFD = cast<FunctionDecl>(New);
1752 }
1753
1754 FunctionDecl *Cursor = NewFD;
1755 while (true) {
1756 Cursor = Cursor->getPreviousDeclaration();
1757
1758 // If we got to the end without finding OldFD, OldFD is the newer
1759 // declaration; leave things as they are.
1760 if (!Cursor) return;
1761
1762 // If we do find OldFD, then NewFD is newer.
1763 if (Cursor == OldFD) break;
1764
1765 // Otherwise, keep looking.
1766 }
1767
1768 Old = New;
1769}
1770
Sebastian Redlc057f422009-10-23 19:23:15 +00001771void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001772 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00001773 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001774 // Find all of the associated namespaces and classes based on the
1775 // arguments we have.
1776 AssociatedNamespaceSet AssociatedNamespaces;
1777 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00001778 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00001779 AssociatedNamespaces,
1780 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001781
Sebastian Redlc057f422009-10-23 19:23:15 +00001782 QualType T1, T2;
1783 if (Operator) {
1784 T1 = Args[0]->getType();
1785 if (NumArgs >= 2)
1786 T2 = Args[1]->getType();
1787 }
1788
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001789 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001790 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1791 // and let Y be the lookup set produced by argument dependent
1792 // lookup (defined as follows). If X contains [...] then Y is
1793 // empty. Otherwise Y is the set of declarations found in the
1794 // namespaces associated with the argument types as described
1795 // below. The set of declarations found by the lookup of the name
1796 // is the union of X and Y.
1797 //
1798 // Here, we compute Y and add its members to the overloaded
1799 // candidate set.
1800 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001801 NSEnd = AssociatedNamespaces.end();
1802 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001803 // When considering an associated namespace, the lookup is the
1804 // same as the lookup performed when the associated namespace is
1805 // used as a qualifier (3.4.3.2) except that:
1806 //
1807 // -- Any using-directives in the associated namespace are
1808 // ignored.
1809 //
John McCallc7e8e792009-08-07 22:18:02 +00001810 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001811 // associated classes are visible within their respective
1812 // namespaces even if they are not visible during an ordinary
1813 // lookup (11.4).
1814 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00001815 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00001816 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00001817 // If the only declaration here is an ordinary friend, consider
1818 // it only if it was declared in an associated classes.
1819 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00001820 DeclContext *LexDC = D->getLexicalDeclContext();
1821 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1822 continue;
1823 }
Mike Stump11289f42009-09-09 15:08:12 +00001824
John McCall91f61fc2010-01-26 06:04:06 +00001825 if (isa<UsingShadowDecl>(D))
1826 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00001827
John McCall91f61fc2010-01-26 06:04:06 +00001828 if (isa<FunctionDecl>(D)) {
1829 if (Operator &&
1830 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
1831 T1, T2, Context))
1832 continue;
John McCall8fe68082010-01-26 07:16:45 +00001833 } else if (!isa<FunctionTemplateDecl>(D))
1834 continue;
1835
1836 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00001837 }
1838 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001839}
Douglas Gregor2d435302009-12-30 17:04:44 +00001840
1841//----------------------------------------------------------------------------
1842// Search for all visible declarations.
1843//----------------------------------------------------------------------------
1844VisibleDeclConsumer::~VisibleDeclConsumer() { }
1845
1846namespace {
1847
1848class ShadowContextRAII;
1849
1850class VisibleDeclsRecord {
1851public:
1852 /// \brief An entry in the shadow map, which is optimized to store a
1853 /// single declaration (the common case) but can also store a list
1854 /// of declarations.
1855 class ShadowMapEntry {
1856 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1857
1858 /// \brief Contains either the solitary NamedDecl * or a vector
1859 /// of declarations.
1860 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1861
1862 public:
1863 ShadowMapEntry() : DeclOrVector() { }
1864
1865 void Add(NamedDecl *ND);
1866 void Destroy();
1867
1868 // Iteration.
1869 typedef NamedDecl **iterator;
1870 iterator begin();
1871 iterator end();
1872 };
1873
1874private:
1875 /// \brief A mapping from declaration names to the declarations that have
1876 /// this name within a particular scope.
1877 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
1878
1879 /// \brief A list of shadow maps, which is used to model name hiding.
1880 std::list<ShadowMap> ShadowMaps;
1881
1882 /// \brief The declaration contexts we have already visited.
1883 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
1884
1885 friend class ShadowContextRAII;
1886
1887public:
1888 /// \brief Determine whether we have already visited this context
1889 /// (and, if not, note that we are going to visit that context now).
1890 bool visitedContext(DeclContext *Ctx) {
1891 return !VisitedContexts.insert(Ctx);
1892 }
1893
1894 /// \brief Determine whether the given declaration is hidden in the
1895 /// current scope.
1896 ///
1897 /// \returns the declaration that hides the given declaration, or
1898 /// NULL if no such declaration exists.
1899 NamedDecl *checkHidden(NamedDecl *ND);
1900
1901 /// \brief Add a declaration to the current shadow map.
1902 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
1903};
1904
1905/// \brief RAII object that records when we've entered a shadow context.
1906class ShadowContextRAII {
1907 VisibleDeclsRecord &Visible;
1908
1909 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
1910
1911public:
1912 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
1913 Visible.ShadowMaps.push_back(ShadowMap());
1914 }
1915
1916 ~ShadowContextRAII() {
1917 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
1918 EEnd = Visible.ShadowMaps.back().end();
1919 E != EEnd;
1920 ++E)
1921 E->second.Destroy();
1922
1923 Visible.ShadowMaps.pop_back();
1924 }
1925};
1926
1927} // end anonymous namespace
1928
1929void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
1930 if (DeclOrVector.isNull()) {
1931 // 0 - > 1 elements: just set the single element information.
1932 DeclOrVector = ND;
1933 return;
1934 }
1935
1936 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
1937 // 1 -> 2 elements: create the vector of results and push in the
1938 // existing declaration.
1939 DeclVector *Vec = new DeclVector;
1940 Vec->push_back(PrevND);
1941 DeclOrVector = Vec;
1942 }
1943
1944 // Add the new element to the end of the vector.
1945 DeclOrVector.get<DeclVector*>()->push_back(ND);
1946}
1947
1948void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
1949 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
1950 delete Vec;
1951 DeclOrVector = ((NamedDecl *)0);
1952 }
1953}
1954
1955VisibleDeclsRecord::ShadowMapEntry::iterator
1956VisibleDeclsRecord::ShadowMapEntry::begin() {
1957 if (DeclOrVector.isNull())
1958 return 0;
1959
1960 if (DeclOrVector.dyn_cast<NamedDecl *>())
1961 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
1962
1963 return DeclOrVector.get<DeclVector *>()->begin();
1964}
1965
1966VisibleDeclsRecord::ShadowMapEntry::iterator
1967VisibleDeclsRecord::ShadowMapEntry::end() {
1968 if (DeclOrVector.isNull())
1969 return 0;
1970
1971 if (DeclOrVector.dyn_cast<NamedDecl *>())
1972 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
1973
1974 return DeclOrVector.get<DeclVector *>()->end();
1975}
1976
1977NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00001978 // Look through using declarations.
1979 ND = ND->getUnderlyingDecl();
1980
Douglas Gregor2d435302009-12-30 17:04:44 +00001981 unsigned IDNS = ND->getIdentifierNamespace();
1982 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
1983 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
1984 SM != SMEnd; ++SM) {
1985 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
1986 if (Pos == SM->end())
1987 continue;
1988
1989 for (ShadowMapEntry::iterator I = Pos->second.begin(),
1990 IEnd = Pos->second.end();
1991 I != IEnd; ++I) {
1992 // A tag declaration does not hide a non-tag declaration.
1993 if ((*I)->getIdentifierNamespace() == Decl::IDNS_Tag &&
1994 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
1995 Decl::IDNS_ObjCProtocol)))
1996 continue;
1997
1998 // Protocols are in distinct namespaces from everything else.
1999 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2000 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2001 (*I)->getIdentifierNamespace() != IDNS)
2002 continue;
2003
Douglas Gregor09bbc652010-01-14 15:47:35 +00002004 // Functions and function templates in the same scope overload
2005 // rather than hide. FIXME: Look for hiding based on function
2006 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002007 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002008 ND->isFunctionOrFunctionTemplate() &&
2009 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002010 continue;
2011
Douglas Gregor2d435302009-12-30 17:04:44 +00002012 // We've found a declaration that hides this one.
2013 return *I;
2014 }
2015 }
2016
2017 return 0;
2018}
2019
2020static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2021 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002022 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002023 VisibleDeclConsumer &Consumer,
2024 VisibleDeclsRecord &Visited) {
2025 // Make sure we don't visit the same context twice.
2026 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2027 return;
2028
2029 // Enumerate all of the results in this context.
2030 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2031 CurCtx = CurCtx->getNextContext()) {
2032 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2033 DEnd = CurCtx->decls_end();
2034 D != DEnd; ++D) {
2035 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2036 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002037 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002038 Visited.add(ND);
2039 }
2040
2041 // Visit transparent contexts inside this context.
2042 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2043 if (InnerCtx->isTransparentContext())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002044 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002045 Consumer, Visited);
2046 }
2047 }
2048 }
2049
2050 // Traverse using directives for qualified name lookup.
2051 if (QualifiedNameLookup) {
2052 ShadowContextRAII Shadow(Visited);
2053 DeclContext::udir_iterator I, E;
2054 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2055 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002056 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002057 }
2058 }
2059
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002060 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002061 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
2062 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2063 BEnd = Record->bases_end();
2064 B != BEnd; ++B) {
2065 QualType BaseType = B->getType();
2066
2067 // Don't look into dependent bases, because name lookup can't look
2068 // there anyway.
2069 if (BaseType->isDependentType())
2070 continue;
2071
2072 const RecordType *Record = BaseType->getAs<RecordType>();
2073 if (!Record)
2074 continue;
2075
2076 // FIXME: It would be nice to be able to determine whether referencing
2077 // a particular member would be ambiguous. For example, given
2078 //
2079 // struct A { int member; };
2080 // struct B { int member; };
2081 // struct C : A, B { };
2082 //
2083 // void f(C *c) { c->### }
2084 //
2085 // accessing 'member' would result in an ambiguity. However, we
2086 // could be smart enough to qualify the member with the base
2087 // class, e.g.,
2088 //
2089 // c->B::member
2090 //
2091 // or
2092 //
2093 // c->A::member
2094
2095 // Find results in this base class (and its bases).
2096 ShadowContextRAII Shadow(Visited);
2097 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002098 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002099 }
2100 }
2101
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002102 // Traverse the contexts of Objective-C classes.
2103 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2104 // Traverse categories.
2105 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2106 Category; Category = Category->getNextClassCategory()) {
2107 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002108 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2109 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002110 }
2111
2112 // Traverse protocols.
2113 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2114 E = IFace->protocol_end(); I != E; ++I) {
2115 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002116 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2117 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002118 }
2119
2120 // Traverse the superclass.
2121 if (IFace->getSuperClass()) {
2122 ShadowContextRAII Shadow(Visited);
2123 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002124 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002125 }
2126 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2127 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2128 E = Protocol->protocol_end(); I != E; ++I) {
2129 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002130 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2131 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002132 }
2133 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2134 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2135 E = Category->protocol_end(); I != E; ++I) {
2136 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002137 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2138 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002139 }
2140 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002141}
2142
2143static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2144 UnqualUsingDirectiveSet &UDirs,
2145 VisibleDeclConsumer &Consumer,
2146 VisibleDeclsRecord &Visited) {
2147 if (!S)
2148 return;
2149
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002150 if (!S->getEntity() || !S->getParent() ||
2151 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2152 // Walk through the declarations in this Scope.
2153 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2154 D != DEnd; ++D) {
2155 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2156 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002157 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002158 Visited.add(ND);
2159 }
2160 }
2161 }
2162
Douglas Gregor2d435302009-12-30 17:04:44 +00002163 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002164 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002165 // Look into this scope's declaration context, along with any of its
2166 // parent lookup contexts (e.g., enclosing classes), up to the point
2167 // where we hit the context stored in the next outer scope.
2168 Entity = (DeclContext *)S->getEntity();
2169 DeclContext *OuterCtx = findOuterContext(S);
2170
2171 for (DeclContext *Ctx = Entity; Ctx && Ctx->getPrimaryContext() != OuterCtx;
2172 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002173 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2174 if (Method->isInstanceMethod()) {
2175 // For instance methods, look for ivars in the method's interface.
2176 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2177 Result.getNameLoc(), Sema::LookupMemberName);
2178 ObjCInterfaceDecl *IFace = Method->getClassInterface();
2179 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002180 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002181 }
2182
2183 // We've already performed all of the name lookup that we need
2184 // to for Objective-C methods; the next context will be the
2185 // outer scope.
2186 break;
2187 }
2188
Douglas Gregor2d435302009-12-30 17:04:44 +00002189 if (Ctx->isFunctionOrMethod())
2190 continue;
2191
2192 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002193 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002194 }
2195 } else if (!S->getParent()) {
2196 // Look into the translation unit scope. We walk through the translation
2197 // unit's declaration context, because the Scope itself won't have all of
2198 // the declarations if we loaded a precompiled header.
2199 // FIXME: We would like the translation unit's Scope object to point to the
2200 // translation unit, so we don't need this special "if" branch. However,
2201 // doing so would force the normal C++ name-lookup code to look into the
2202 // translation unit decl when the IdentifierInfo chains would suffice.
2203 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002204 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002205 Entity = Result.getSema().Context.getTranslationUnitDecl();
2206 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002207 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002208 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002209
2210 if (Entity) {
2211 // Lookup visible declarations in any namespaces found by using
2212 // directives.
2213 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2214 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2215 for (; UI != UEnd; ++UI)
2216 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002217 Result, /*QualifiedNameLookup=*/false,
2218 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002219 }
2220
2221 // Lookup names in the parent scope.
2222 ShadowContextRAII Shadow(Visited);
2223 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2224}
2225
2226void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2227 VisibleDeclConsumer &Consumer) {
2228 // Determine the set of using directives available during
2229 // unqualified name lookup.
2230 Scope *Initial = S;
2231 UnqualUsingDirectiveSet UDirs;
2232 if (getLangOptions().CPlusPlus) {
2233 // Find the first namespace or translation-unit scope.
2234 while (S && !isNamespaceOrTranslationUnitScope(S))
2235 S = S->getParent();
2236
2237 UDirs.visitScopeChain(Initial, S);
2238 }
2239 UDirs.done();
2240
2241 // Look for visible declarations.
2242 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2243 VisibleDeclsRecord Visited;
2244 ShadowContextRAII Shadow(Visited);
2245 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2246}
2247
2248void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2249 VisibleDeclConsumer &Consumer) {
2250 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2251 VisibleDeclsRecord Visited;
2252 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002253 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2254 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002255}
2256
2257//----------------------------------------------------------------------------
2258// Typo correction
2259//----------------------------------------------------------------------------
2260
2261namespace {
2262class TypoCorrectionConsumer : public VisibleDeclConsumer {
2263 /// \brief The name written that is a typo in the source.
2264 llvm::StringRef Typo;
2265
2266 /// \brief The results found that have the smallest edit distance
2267 /// found (so far) with the typo name.
2268 llvm::SmallVector<NamedDecl *, 4> BestResults;
2269
2270 /// \brief The best edit distance found so far.
2271 unsigned BestEditDistance;
2272
2273public:
2274 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2275 : Typo(Typo->getName()) { }
2276
Douglas Gregor09bbc652010-01-14 15:47:35 +00002277 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002278
2279 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2280 iterator begin() const { return BestResults.begin(); }
2281 iterator end() const { return BestResults.end(); }
2282 bool empty() const { return BestResults.empty(); }
2283
2284 unsigned getBestEditDistance() const { return BestEditDistance; }
2285};
2286
2287}
2288
Douglas Gregor09bbc652010-01-14 15:47:35 +00002289void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2290 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002291 // Don't consider hidden names for typo correction.
2292 if (Hiding)
2293 return;
2294
2295 // Only consider entities with identifiers for names, ignoring
2296 // special names (constructors, overloaded operators, selectors,
2297 // etc.).
2298 IdentifierInfo *Name = ND->getIdentifier();
2299 if (!Name)
2300 return;
2301
2302 // Compute the edit distance between the typo and the name of this
2303 // entity. If this edit distance is not worse than the best edit
2304 // distance we've seen so far, add it to the list of results.
2305 unsigned ED = Typo.edit_distance(Name->getName());
2306 if (!BestResults.empty()) {
2307 if (ED < BestEditDistance) {
2308 // This result is better than any we've seen before; clear out
2309 // the previous results.
2310 BestResults.clear();
2311 BestEditDistance = ED;
2312 } else if (ED > BestEditDistance) {
2313 // This result is worse than the best results we've seen so far;
2314 // ignore it.
2315 return;
2316 }
2317 } else
2318 BestEditDistance = ED;
2319
2320 BestResults.push_back(ND);
2321}
2322
2323/// \brief Try to "correct" a typo in the source code by finding
2324/// visible declarations whose names are similar to the name that was
2325/// present in the source code.
2326///
2327/// \param Res the \c LookupResult structure that contains the name
2328/// that was present in the source code along with the name-lookup
2329/// criteria used to search for the name. On success, this structure
2330/// will contain the results of name lookup.
2331///
2332/// \param S the scope in which name lookup occurs.
2333///
2334/// \param SS the nested-name-specifier that precedes the name we're
2335/// looking for, if present.
2336///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002337/// \param MemberContext if non-NULL, the context in which to look for
2338/// a member access expression.
2339///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002340/// \param EnteringContext whether we're entering the context described by
2341/// the nested-name-specifier SS.
2342///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002343/// \param OPT when non-NULL, the search for visible declarations will
2344/// also walk the protocols in the qualified interfaces of \p OPT.
2345///
Douglas Gregor2d435302009-12-30 17:04:44 +00002346/// \returns true if the typo was corrected, in which case the \p Res
2347/// structure will contain the results of name lookup for the
2348/// corrected name. Otherwise, returns false.
2349bool Sema::CorrectTypo(LookupResult &Res, Scope *S, const CXXScopeSpec *SS,
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002350 DeclContext *MemberContext, bool EnteringContext,
2351 const ObjCObjectPointerType *OPT) {
Ted Kremeneke51136e2010-01-06 00:23:04 +00002352
2353 if (Diags.hasFatalErrorOccurred())
2354 return false;
2355
Douglas Gregor2d435302009-12-30 17:04:44 +00002356 // We only attempt to correct typos for identifiers.
2357 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2358 if (!Typo)
2359 return false;
2360
2361 // If the scope specifier itself was invalid, don't try to correct
2362 // typos.
2363 if (SS && SS->isInvalid())
2364 return false;
2365
2366 // Never try to correct typos during template deduction or
2367 // instantiation.
2368 if (!ActiveTemplateInstantiations.empty())
2369 return false;
2370
2371 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002372 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002373 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002374
2375 // Look in qualified interfaces.
2376 if (OPT) {
2377 for (ObjCObjectPointerType::qual_iterator
2378 I = OPT->qual_begin(), E = OPT->qual_end();
2379 I != E; ++I)
2380 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2381 }
2382 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002383 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2384 if (!DC)
2385 return false;
2386
2387 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2388 } else {
2389 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2390 }
2391
2392 if (Consumer.empty())
2393 return false;
2394
2395 // Only allow a single, closest name in the result set (it's okay to
2396 // have overloads of that name, though).
2397 TypoCorrectionConsumer::iterator I = Consumer.begin();
2398 DeclarationName BestName = (*I)->getDeclName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002399
2400 // If we've found an Objective-C ivar or property, don't perform
2401 // name lookup again; we'll just return the result directly.
2402 NamedDecl *FoundBest = 0;
2403 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I))
2404 FoundBest = *I;
Douglas Gregor2d435302009-12-30 17:04:44 +00002405 ++I;
2406 for(TypoCorrectionConsumer::iterator IEnd = Consumer.end(); I != IEnd; ++I) {
2407 if (BestName != (*I)->getDeclName())
2408 return false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002409
2410 // FIXME: If there are both ivars and properties of the same name,
2411 // don't return both because the callee can't handle two
2412 // results. We really need to separate ivar lookup from property
2413 // lookup to avoid this problem.
2414 FoundBest = 0;
Douglas Gregor2d435302009-12-30 17:04:44 +00002415 }
2416
2417 // BestName is the closest viable name to what the user
2418 // typed. However, to make sure that we don't pick something that's
2419 // way off, make sure that the user typed at least 3 characters for
2420 // each correction.
2421 unsigned ED = Consumer.getBestEditDistance();
2422 if (ED == 0 || (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
2423 return false;
2424
2425 // Perform name lookup again with the name we chose, and declare
2426 // success if we found something that was not ambiguous.
2427 Res.clear();
2428 Res.setLookupName(BestName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002429
2430 // If we found an ivar or property, add that result; no further
2431 // lookup is required.
2432 if (FoundBest)
2433 Res.addDecl(FoundBest);
2434 // If we're looking into the context of a member, perform qualified
2435 // name lookup on the best name.
2436 else if (MemberContext)
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002437 LookupQualifiedName(Res, MemberContext);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002438 // Perform lookup as if we had just parsed the best name.
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002439 else
2440 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2441 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00002442
2443 if (Res.isAmbiguous()) {
2444 Res.suppressDiagnostics();
2445 return false;
2446 }
2447
2448 return Res.getResultKind() != LookupResult::NotFound;
Douglas Gregor2d435302009-12-30 17:04:44 +00002449}