blob: 0d95c713b01ca5c0b9f14e4453dcc3e796d2b5bc [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 McCall5b0829a2010-02-10 09:31:12 +0000407 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000408 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()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000456 != DeclarationName::CXXConversionFunctionName ||
457 R.getLookupName().getCXXNameType()->isDependentType() ||
458 !isa<CXXRecordDecl>(DC))
459 return Found;
460
461 // C++ [temp.mem]p6:
462 // A specialization of a conversion function template is not found by
463 // name lookup. Instead, any conversion function templates visible in the
464 // context of the use are considered. [...]
465 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
466 if (!Record->isDefinition())
467 return Found;
468
469 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
470 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
471 UEnd = Unresolved->end(); U != UEnd; ++U) {
472 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
473 if (!ConvTemplate)
474 continue;
475
476 // When we're performing lookup for the purposes of redeclaration, just
477 // add the conversion function template. When we deduce template
478 // arguments for specializations, we'll end up unifying the return
479 // type of the new declaration with the type of the function template.
480 if (R.isForRedeclaration()) {
481 R.addDecl(ConvTemplate);
482 Found = true;
483 continue;
484 }
485
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000486 // C++ [temp.mem]p6:
Chandler Carruth3a693b72010-01-31 11:44:02 +0000487 // [...] For each such operator, if argument deduction succeeds
488 // (14.9.2.3), the resulting specialization is used as if found by
489 // name lookup.
490 //
491 // When referencing a conversion function for any purpose other than
492 // a redeclaration (such that we'll be building an expression with the
493 // result), perform template argument deduction and place the
494 // specialization into the result set. We do this to avoid forcing all
495 // callers to perform special deduction for conversion functions.
John McCallbc077cf2010-02-08 23:07:23 +0000496 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000497 FunctionDecl *Specialization = 0;
498
499 const FunctionProtoType *ConvProto
500 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
501 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000502
Chandler Carruth3a693b72010-01-31 11:44:02 +0000503 // Compute the type of the function that we would expect the conversion
504 // function to have, if it were to match the name given.
505 // FIXME: Calling convention!
506 QualType ExpectedType
507 = R.getSema().Context.getFunctionType(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;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000520 }
521 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000522
John McCall9f3059a2009-10-09 21:13:30 +0000523 return Found;
524}
525
John McCallf6c8a4e2009-11-10 07:01:13 +0000526// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000527static bool
John McCall5cebab12009-11-18 07:57:50 +0000528CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCall27b18f82009-11-17 02:14:36 +0000529 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000530
531 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
532
John McCallf6c8a4e2009-11-10 07:01:13 +0000533 // Perform direct name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000534 bool Found = LookupDirect(R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000535
John McCallf6c8a4e2009-11-10 07:01:13 +0000536 // Perform direct name lookup into the namespaces nominated by the
537 // using directives whose common ancestor is this namespace.
538 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
539 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000540
John McCallf6c8a4e2009-11-10 07:01:13 +0000541 for (; UI != UEnd; ++UI)
John McCall27b18f82009-11-17 02:14:36 +0000542 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000543 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000544
545 R.resolveKind();
546
547 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000548}
549
550static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000551 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000552 return Ctx->isFileContext();
553 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000554}
Douglas Gregored8f2882009-01-30 01:04:22 +0000555
Douglas Gregor7f737c02009-09-10 16:57:35 +0000556// Find the next outer declaration context corresponding to this scope.
557static DeclContext *findOuterContext(Scope *S) {
558 for (S = S->getParent(); S; S = S->getParent())
559 if (S->getEntity())
560 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
561
562 return 0;
563}
564
John McCall27b18f82009-11-17 02:14:36 +0000565bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000566 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000567
568 DeclarationName Name = R.getLookupName();
569
Douglas Gregor889ceb72009-02-03 19:21:40 +0000570 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000571 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000572 I = IdResolver.begin(Name),
573 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000574
Douglas Gregor889ceb72009-02-03 19:21:40 +0000575 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000576 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000577 // ...During unqualified name lookup (3.4.1), the names appear as if
578 // they were declared in the nearest enclosing namespace which contains
579 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000580 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000581 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000582 //
583 // For example:
584 // namespace A { int i; }
585 // void foo() {
586 // int i;
587 // {
588 // using namespace A;
589 // ++i; // finds local 'i', A::i appears at global scope
590 // }
591 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000592 //
Douglas Gregor700792c2009-02-05 19:25:20 +0000593 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000594 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000595 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000596 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000597 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000598 Found = true;
599 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000600 }
601 }
John McCall9f3059a2009-10-09 21:13:30 +0000602 if (Found) {
603 R.resolveKind();
604 return true;
605 }
606
Douglas Gregor700792c2009-02-05 19:25:20 +0000607 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregor7f737c02009-09-10 16:57:35 +0000608 DeclContext *OuterCtx = findOuterContext(S);
609 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
610 Ctx = Ctx->getLookupParent()) {
Douglas Gregora64c1e52009-12-08 15:38:36 +0000611 // We do not directly look into function or method contexts
612 // (since all local variables are found via the identifier
613 // changes) or in transparent contexts (since those entities
614 // will be found in the nearest enclosing non-transparent
615 // context).
616 if (Ctx->isFunctionOrMethod() || Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000617 continue;
618
619 // Perform qualified name lookup into this context.
620 // FIXME: In some cases, we know that every name that could be found by
621 // this qualified name lookup will also be on the identifier chain. For
622 // example, inside a class without any base classes, we never need to
623 // perform qualified lookup because all of the members are on top of the
624 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000625 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000626 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000627 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000628 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000629 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000630
John McCallf6c8a4e2009-11-10 07:01:13 +0000631 // Stop if we ran out of scopes.
632 // FIXME: This really, really shouldn't be happening.
633 if (!S) return false;
634
Douglas Gregor700792c2009-02-05 19:25:20 +0000635 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000636 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000637 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000638 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
639 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000640
John McCallf6c8a4e2009-11-10 07:01:13 +0000641 UnqualUsingDirectiveSet UDirs;
642 UDirs.visitScopeChain(Initial, S);
643 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000644
Douglas Gregor700792c2009-02-05 19:25:20 +0000645 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000646 // Unqualified name lookup in C++ requires looking into scopes
647 // that aren't strictly lexical, and therefore we walk through the
648 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000649
Douglas Gregor889ceb72009-02-03 19:21:40 +0000650 for (; S; S = S->getParent()) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000651 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregor3ce74932010-02-05 07:07:10 +0000652 if (Ctx && Ctx->isTransparentContext())
Douglas Gregorf2270432009-08-24 18:55:03 +0000653 continue;
654
Douglas Gregor889ceb72009-02-03 19:21:40 +0000655 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000656 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000657 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000658 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000659 // We found something. Look for anything else in our scope
660 // with this same name and in an acceptable identifier
661 // namespace, so that we can construct an overload set if we
662 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000663 Found = true;
664 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000665 }
666 }
667
Douglas Gregor3ce74932010-02-05 07:07:10 +0000668 if (Ctx) {
669 assert(Ctx->isFileContext() &&
670 "We should have been looking only at file context here already.");
671
672 // Look into context considering using-directives.
673 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
674 Found = true;
675 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000676
John McCall9f3059a2009-10-09 21:13:30 +0000677 if (Found) {
678 R.resolveKind();
679 return true;
680 }
681
Douglas Gregor3ce74932010-02-05 07:07:10 +0000682 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000683 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000684 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000685
John McCall9f3059a2009-10-09 21:13:30 +0000686 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000687}
688
Douglas Gregor34074322009-01-14 22:20:51 +0000689/// @brief Perform unqualified name lookup starting from a given
690/// scope.
691///
692/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
693/// used to find names within the current scope. For example, 'x' in
694/// @code
695/// int x;
696/// int f() {
697/// return x; // unqualified name look finds 'x' in the global scope
698/// }
699/// @endcode
700///
701/// Different lookup criteria can find different names. For example, a
702/// particular scope can have both a struct and a function of the same
703/// name, and each can be found by certain lookup criteria. For more
704/// information about lookup criteria, see the documentation for the
705/// class LookupCriteria.
706///
707/// @param S The scope from which unqualified name lookup will
708/// begin. If the lookup criteria permits, name lookup may also search
709/// in the parent scopes.
710///
711/// @param Name The name of the entity that we are searching for.
712///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000713/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000714/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000715/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000716///
717/// @returns The result of name lookup, which includes zero or more
718/// declarations and possibly additional information used to diagnose
719/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000720bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
721 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +0000722 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000723
John McCall27b18f82009-11-17 02:14:36 +0000724 LookupNameKind NameKind = R.getLookupKind();
725
Douglas Gregor34074322009-01-14 22:20:51 +0000726 if (!getLangOptions().CPlusPlus) {
727 // Unqualified name lookup in C/Objective-C is purely lexical, so
728 // search in the declarations attached to the name.
729
John McCallea305ed2009-12-18 10:40:03 +0000730 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000731 // Find the nearest non-transparent declaration scope.
732 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000733 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000734 static_cast<DeclContext *>(S->getEntity())
735 ->isTransparentContext()))
736 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +0000737 }
738
John McCallea305ed2009-12-18 10:40:03 +0000739 unsigned IDNS = R.getIdentifierNamespace();
740
Douglas Gregor34074322009-01-14 22:20:51 +0000741 // Scan up the scope chain looking for a decl that matches this
742 // identifier that is in the appropriate namespace. This search
743 // should not take long, as shadowing of names is uncommon, and
744 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000745 bool LeftStartingScope = false;
746
Douglas Gregored8f2882009-01-30 01:04:22 +0000747 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000748 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000749 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000750 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000751 if (NameKind == LookupRedeclarationWithLinkage) {
752 // Determine whether this (or a previous) declaration is
753 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000754 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000755 LeftStartingScope = true;
756
757 // If we found something outside of our starting scope that
758 // does not have linkage, skip it.
759 if (LeftStartingScope && !((*I)->hasLinkage()))
760 continue;
761 }
762
John McCall9f3059a2009-10-09 21:13:30 +0000763 R.addDecl(*I);
764
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000765 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000766 // If this declaration has the "overloadable" attribute, we
767 // might have a set of overloaded functions.
768
769 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000770 while (!(S->getFlags() & Scope::DeclScope) ||
771 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000772 S = S->getParent();
773
774 // Find the last declaration in this scope (with the same
775 // name, naturally).
776 IdentifierResolver::iterator LastI = I;
777 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000778 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000779 break;
John McCall9f3059a2009-10-09 21:13:30 +0000780 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000781 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000782 }
783
John McCall9f3059a2009-10-09 21:13:30 +0000784 R.resolveKind();
785
786 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000787 }
Douglas Gregor34074322009-01-14 22:20:51 +0000788 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000789 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000790 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +0000791 return true;
Douglas Gregor34074322009-01-14 22:20:51 +0000792 }
793
794 // If we didn't find a use of this identifier, and if the identifier
795 // corresponds to a compiler builtin, create the decl object for the builtin
796 // now, injecting it into translation unit scope, and return it.
Mike Stump11289f42009-09-09 15:08:12 +0000797 if (NameKind == LookupOrdinaryName ||
Douglas Gregoreddf4332009-02-24 20:03:32 +0000798 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor34074322009-01-14 22:20:51 +0000799 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000800 if (II && AllowBuiltinCreation) {
Douglas Gregor34074322009-01-14 22:20:51 +0000801 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000802 if (unsigned BuiltinID = II->getBuiltinID()) {
803 // In C++, we don't have any predefined library functions like
804 // 'malloc'. Instead, we'll just error.
Mike Stump11289f42009-09-09 15:08:12 +0000805 if (getLangOptions().CPlusPlus &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000806 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCall9f3059a2009-10-09 21:13:30 +0000807 return false;
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000808
John McCall9f3059a2009-10-09 21:13:30 +0000809 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCall27b18f82009-11-17 02:14:36 +0000810 S, R.isForRedeclaration(),
811 R.getNameLoc());
John McCall9f3059a2009-10-09 21:13:30 +0000812 if (D) R.addDecl(D);
813 return (D != NULL);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000814 }
Douglas Gregor34074322009-01-14 22:20:51 +0000815 }
Douglas Gregor34074322009-01-14 22:20:51 +0000816 }
John McCall9f3059a2009-10-09 21:13:30 +0000817 return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000818}
819
John McCall6538c932009-10-10 05:48:19 +0000820/// @brief Perform qualified name lookup in the namespaces nominated by
821/// using directives by the given context.
822///
823/// C++98 [namespace.qual]p2:
824/// Given X::m (where X is a user-declared namespace), or given ::m
825/// (where X is the global namespace), let S be the set of all
826/// declarations of m in X and in the transitive closure of all
827/// namespaces nominated by using-directives in X and its used
828/// namespaces, except that using-directives are ignored in any
829/// namespace, including X, directly containing one or more
830/// declarations of m. No namespace is searched more than once in
831/// the lookup of a name. If S is the empty set, the program is
832/// ill-formed. Otherwise, if S has exactly one member, or if the
833/// context of the reference is a using-declaration
834/// (namespace.udecl), S is the required set of declarations of
835/// m. Otherwise if the use of m is not one that allows a unique
836/// declaration to be chosen from S, the program is ill-formed.
837/// C++98 [namespace.qual]p5:
838/// During the lookup of a qualified namespace member name, if the
839/// lookup finds more than one declaration of the member, and if one
840/// declaration introduces a class name or enumeration name and the
841/// other declarations either introduce the same object, the same
842/// enumerator or a set of functions, the non-type name hides the
843/// class or enumeration name if and only if the declarations are
844/// from the same namespace; otherwise (the declarations are from
845/// different namespaces), the program is ill-formed.
John McCall5cebab12009-11-18 07:57:50 +0000846static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +0000847 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +0000848 assert(StartDC->isFileContext() && "start context is not a file context");
849
850 DeclContext::udir_iterator I = StartDC->using_directives_begin();
851 DeclContext::udir_iterator E = StartDC->using_directives_end();
852
853 if (I == E) return false;
854
855 // We have at least added all these contexts to the queue.
856 llvm::DenseSet<DeclContext*> Visited;
857 Visited.insert(StartDC);
858
859 // We have not yet looked into these namespaces, much less added
860 // their "using-children" to the queue.
861 llvm::SmallVector<NamespaceDecl*, 8> Queue;
862
863 // We have already looked into the initial namespace; seed the queue
864 // with its using-children.
865 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +0000866 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +0000867 if (Visited.insert(ND).second)
868 Queue.push_back(ND);
869 }
870
871 // The easiest way to implement the restriction in [namespace.qual]p5
872 // is to check whether any of the individual results found a tag
873 // and, if so, to declare an ambiguity if the final result is not
874 // a tag.
875 bool FoundTag = false;
876 bool FoundNonTag = false;
877
John McCall5cebab12009-11-18 07:57:50 +0000878 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +0000879
880 bool Found = false;
881 while (!Queue.empty()) {
882 NamespaceDecl *ND = Queue.back();
883 Queue.pop_back();
884
885 // We go through some convolutions here to avoid copying results
886 // between LookupResults.
887 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +0000888 LookupResult &DirectR = UseLocal ? LocalR : R;
John McCall27b18f82009-11-17 02:14:36 +0000889 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +0000890
891 if (FoundDirect) {
892 // First do any local hiding.
893 DirectR.resolveKind();
894
895 // If the local result is a tag, remember that.
896 if (DirectR.isSingleTagDecl())
897 FoundTag = true;
898 else
899 FoundNonTag = true;
900
901 // Append the local results to the total results if necessary.
902 if (UseLocal) {
903 R.addAllDecls(LocalR);
904 LocalR.clear();
905 }
906 }
907
908 // If we find names in this namespace, ignore its using directives.
909 if (FoundDirect) {
910 Found = true;
911 continue;
912 }
913
914 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
915 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
916 if (Visited.insert(Nom).second)
917 Queue.push_back(Nom);
918 }
919 }
920
921 if (Found) {
922 if (FoundTag && FoundNonTag)
923 R.setAmbiguousQualifiedTagHiding();
924 else
925 R.resolveKind();
926 }
927
928 return Found;
929}
930
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000931/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +0000932///
933/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
934/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000935/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +0000936///
937/// Different lookup criteria can find different names. For example, a
938/// particular scope can have both a struct and a function of the same
939/// name, and each can be found by certain lookup criteria. For more
940/// information about lookup criteria, see the documentation for the
941/// class LookupCriteria.
942///
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000943/// \param R captures both the lookup criteria and any lookup results found.
944///
945/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +0000946/// search. If the lookup criteria permits, name lookup may also search
947/// in the parent contexts or (for C++ classes) base classes.
948///
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000949/// \param InUnqualifiedLookup true if this is qualified name lookup that
950/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +0000951///
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000952/// \returns true if lookup succeeded, false if it failed.
953bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
954 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +0000955 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +0000956
John McCall27b18f82009-11-17 02:14:36 +0000957 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +0000958 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000959
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000960 // Make sure that the declaration context is complete.
961 assert((!isa<TagDecl>(LookupCtx) ||
962 LookupCtx->isDependentContext() ||
963 cast<TagDecl>(LookupCtx)->isDefinition() ||
964 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
965 ->isBeingDefined()) &&
966 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +0000967
Douglas Gregor34074322009-01-14 22:20:51 +0000968 // Perform qualified name lookup into the LookupCtx.
John McCall27b18f82009-11-17 02:14:36 +0000969 if (LookupDirect(R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +0000970 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +0000971 if (isa<CXXRecordDecl>(LookupCtx))
972 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +0000973 return true;
974 }
Douglas Gregor34074322009-01-14 22:20:51 +0000975
John McCall6538c932009-10-10 05:48:19 +0000976 // Don't descend into implied contexts for redeclarations.
977 // C++98 [namespace.qual]p6:
978 // In a declaration for a namespace member in which the
979 // declarator-id is a qualified-id, given that the qualified-id
980 // for the namespace member has the form
981 // nested-name-specifier unqualified-id
982 // the unqualified-id shall name a member of the namespace
983 // designated by the nested-name-specifier.
984 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +0000985 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +0000986 return false;
987
John McCall27b18f82009-11-17 02:14:36 +0000988 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +0000989 if (LookupCtx->isFileContext())
John McCall27b18f82009-11-17 02:14:36 +0000990 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +0000991
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000992 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +0000993 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000994 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
995 if (!LookupRec)
John McCall9f3059a2009-10-09 21:13:30 +0000996 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000997
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000998 // If we're performing qualified name lookup into a dependent class,
999 // then we are actually looking into a current instantiation. If we have any
1000 // dependent base classes, then we either have to delay lookup until
1001 // template instantiation time (at which point all bases will be available)
1002 // or we have to fail.
1003 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1004 LookupRec->hasAnyDependentBases()) {
1005 R.setNotFoundInCurrentInstantiation();
1006 return false;
1007 }
1008
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001009 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001010 CXXBasePaths Paths;
1011 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001012
1013 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001014 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001015 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001016 case LookupOrdinaryName:
1017 case LookupMemberName:
1018 case LookupRedeclarationWithLinkage:
1019 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1020 break;
1021
1022 case LookupTagName:
1023 BaseCallback = &CXXRecordDecl::FindTagMember;
1024 break;
John McCall84d87672009-12-10 09:41:52 +00001025
1026 case LookupUsingDeclName:
1027 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001028
1029 case LookupOperatorName:
1030 case LookupNamespaceName:
1031 case LookupObjCProtocolName:
1032 case LookupObjCImplementationName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001033 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001034 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001035
1036 case LookupNestedNameSpecifierName:
1037 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1038 break;
1039 }
1040
John McCall27b18f82009-11-17 02:14:36 +00001041 if (!LookupRec->lookupInBases(BaseCallback,
1042 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001043 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001044
John McCall553c0792010-01-23 00:46:32 +00001045 R.setNamingClass(LookupRec);
1046
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001047 // C++ [class.member.lookup]p2:
1048 // [...] If the resulting set of declarations are not all from
1049 // sub-objects of the same type, or the set has a nonstatic member
1050 // and includes members from distinct sub-objects, there is an
1051 // ambiguity and the program is ill-formed. Otherwise that set is
1052 // the result of the lookup.
1053 // FIXME: support using declarations!
1054 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001055 int SubobjectNumber = 0;
John McCall401982f2010-01-20 21:53:11 +00001056 AccessSpecifier SubobjectAccess = AS_private;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001057 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001058 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001059 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001060
John McCall401982f2010-01-20 21:53:11 +00001061 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1062 // across all paths.
1063 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1064
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001065 // Determine whether we're looking at a distinct sub-object or not.
1066 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001067 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001068 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1069 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001070 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001071 != Context.getCanonicalType(PathElement.Base->getType())) {
1072 // We found members of the given name in two subobjects of
1073 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001074 R.setAmbiguousBaseSubobjectTypes(Paths);
1075 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001076 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1077 // We have a different subobject of the same type.
1078
1079 // C++ [class.member.lookup]p5:
1080 // A static member, a nested type or an enumerator defined in
1081 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001082 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001083 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001084 if (isa<VarDecl>(FirstDecl) ||
1085 isa<TypeDecl>(FirstDecl) ||
1086 isa<EnumConstantDecl>(FirstDecl))
1087 continue;
1088
1089 if (isa<CXXMethodDecl>(FirstDecl)) {
1090 // Determine whether all of the methods are static.
1091 bool AllMethodsAreStatic = true;
1092 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1093 Func != Path->Decls.second; ++Func) {
1094 if (!isa<CXXMethodDecl>(*Func)) {
1095 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1096 break;
1097 }
1098
1099 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1100 AllMethodsAreStatic = false;
1101 break;
1102 }
1103 }
1104
1105 if (AllMethodsAreStatic)
1106 continue;
1107 }
1108
1109 // We have found a nonstatic member name in multiple, distinct
1110 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001111 R.setAmbiguousBaseSubobjects(Paths);
1112 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001113 }
1114 }
1115
1116 // Lookup in a base class succeeded; return these results.
1117
John McCall9f3059a2009-10-09 21:13:30 +00001118 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001119 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1120 NamedDecl *D = *I;
1121 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1122 D->getAccess());
1123 R.addDecl(D, AS);
1124 }
John McCall9f3059a2009-10-09 21:13:30 +00001125 R.resolveKind();
1126 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001127}
1128
1129/// @brief Performs name lookup for a name that was parsed in the
1130/// source code, and may contain a C++ scope specifier.
1131///
1132/// This routine is a convenience routine meant to be called from
1133/// contexts that receive a name and an optional C++ scope specifier
1134/// (e.g., "N::M::x"). It will then perform either qualified or
1135/// unqualified name lookup (with LookupQualifiedName or LookupName,
1136/// respectively) on the given name and return those results.
1137///
1138/// @param S The scope from which unqualified name lookup will
1139/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001140///
Douglas Gregore861bac2009-08-25 22:51:20 +00001141/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001142///
1143/// @param Name The name of the entity that name lookup will
1144/// search for.
1145///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001146/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001147/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001148/// C library functions (like "malloc") are implicitly declared.
1149///
Douglas Gregore861bac2009-08-25 22:51:20 +00001150/// @param EnteringContext Indicates whether we are going to enter the
1151/// context of the scope-specifier SS (if present).
1152///
John McCall9f3059a2009-10-09 21:13:30 +00001153/// @returns True if any decls were found (but possibly ambiguous)
1154bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001155 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001156 if (SS && SS->isInvalid()) {
1157 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001158 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001159 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001160 }
Mike Stump11289f42009-09-09 15:08:12 +00001161
Douglas Gregore861bac2009-08-25 22:51:20 +00001162 if (SS && SS->isSet()) {
1163 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001164 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001165 // contex, and will perform name lookup in that context.
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001166 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCall9f3059a2009-10-09 21:13:30 +00001167 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001168
John McCall27b18f82009-11-17 02:14:36 +00001169 R.setContextRange(SS->getRange());
1170
1171 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001172 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001173
Douglas Gregore861bac2009-08-25 22:51:20 +00001174 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001175 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001176 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001177 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001178 }
1179
Mike Stump11289f42009-09-09 15:08:12 +00001180 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001181 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001182}
1183
Douglas Gregor889ceb72009-02-03 19:21:40 +00001184
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001185/// @brief Produce a diagnostic describing the ambiguity that resulted
1186/// from name lookup.
1187///
1188/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001189///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001190/// @param Name The name of the entity that name lookup was
1191/// searching for.
1192///
1193/// @param NameLoc The location of the name within the source code.
1194///
1195/// @param LookupRange A source range that provides more
1196/// source-location information concerning the lookup itself. For
1197/// example, this range might highlight a nested-name-specifier that
1198/// precedes the name.
1199///
1200/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001201bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001202 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1203
John McCall27b18f82009-11-17 02:14:36 +00001204 DeclarationName Name = Result.getLookupName();
1205 SourceLocation NameLoc = Result.getNameLoc();
1206 SourceRange LookupRange = Result.getContextRange();
1207
John McCall6538c932009-10-10 05:48:19 +00001208 switch (Result.getAmbiguityKind()) {
1209 case LookupResult::AmbiguousBaseSubobjects: {
1210 CXXBasePaths *Paths = Result.getBasePaths();
1211 QualType SubobjectType = Paths->front().back().Base->getType();
1212 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1213 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1214 << LookupRange;
1215
1216 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1217 while (isa<CXXMethodDecl>(*Found) &&
1218 cast<CXXMethodDecl>(*Found)->isStatic())
1219 ++Found;
1220
1221 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1222
1223 return true;
1224 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001225
John McCall6538c932009-10-10 05:48:19 +00001226 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001227 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1228 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001229
1230 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001231 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001232 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1233 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001234 Path != PathEnd; ++Path) {
1235 Decl *D = *Path->Decls.first;
1236 if (DeclsPrinted.insert(D).second)
1237 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1238 }
1239
Douglas Gregor1c846b02009-01-16 00:38:09 +00001240 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001241 }
1242
John McCall6538c932009-10-10 05:48:19 +00001243 case LookupResult::AmbiguousTagHiding: {
1244 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001245
John McCall6538c932009-10-10 05:48:19 +00001246 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1247
1248 LookupResult::iterator DI, DE = Result.end();
1249 for (DI = Result.begin(); DI != DE; ++DI)
1250 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1251 TagDecls.insert(TD);
1252 Diag(TD->getLocation(), diag::note_hidden_tag);
1253 }
1254
1255 for (DI = Result.begin(); DI != DE; ++DI)
1256 if (!isa<TagDecl>(*DI))
1257 Diag((*DI)->getLocation(), diag::note_hiding_object);
1258
1259 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001260 LookupResult::Filter F = Result.makeFilter();
1261 while (F.hasNext()) {
1262 if (TagDecls.count(F.next()))
1263 F.erase();
1264 }
1265 F.done();
John McCall6538c932009-10-10 05:48:19 +00001266
1267 return true;
1268 }
1269
1270 case LookupResult::AmbiguousReference: {
1271 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001272
John McCall6538c932009-10-10 05:48:19 +00001273 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1274 for (; DI != DE; ++DI)
1275 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001276
John McCall6538c932009-10-10 05:48:19 +00001277 return true;
1278 }
1279 }
1280
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001281 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001282 return true;
1283}
Douglas Gregore254f902009-02-04 00:32:51 +00001284
Mike Stump11289f42009-09-09 15:08:12 +00001285static void
1286addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001287 ASTContext &Context,
1288 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001289 Sema::AssociatedClassSet &AssociatedClasses);
1290
1291static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1292 DeclContext *Ctx) {
1293 if (Ctx->isFileContext())
1294 Namespaces.insert(Ctx);
1295}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001296
Mike Stump11289f42009-09-09 15:08:12 +00001297// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001298// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001299static void
1300addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001301 ASTContext &Context,
1302 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001303 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001304 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001305 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001306 switch (Arg.getKind()) {
1307 case TemplateArgument::Null:
1308 break;
Mike Stump11289f42009-09-09 15:08:12 +00001309
Douglas Gregor197e5f72009-07-08 07:51:57 +00001310 case TemplateArgument::Type:
1311 // [...] the namespaces and classes associated with the types of the
1312 // template arguments provided for template type parameters (excluding
1313 // template template parameters)
1314 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1315 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001316 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001317 break;
Mike Stump11289f42009-09-09 15:08:12 +00001318
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001319 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001320 // [...] the namespaces in which any template template arguments are
1321 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001322 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001323 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001324 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001325 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001326 DeclContext *Ctx = ClassTemplate->getDeclContext();
1327 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1328 AssociatedClasses.insert(EnclosingClass);
1329 // Add the associated namespace for this class.
1330 while (Ctx->isRecord())
1331 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001332 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001333 }
1334 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001335 }
1336
1337 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001338 case TemplateArgument::Integral:
1339 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001340 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001341 // associated namespaces. ]
1342 break;
Mike Stump11289f42009-09-09 15:08:12 +00001343
Douglas Gregor197e5f72009-07-08 07:51:57 +00001344 case TemplateArgument::Pack:
1345 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1346 PEnd = Arg.pack_end();
1347 P != PEnd; ++P)
1348 addAssociatedClassesAndNamespaces(*P, Context,
1349 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001350 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001351 break;
1352 }
1353}
1354
Douglas Gregore254f902009-02-04 00:32:51 +00001355// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001356// argument-dependent lookup with an argument of class type
1357// (C++ [basic.lookup.koenig]p2).
1358static void
1359addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregore254f902009-02-04 00:32:51 +00001360 ASTContext &Context,
1361 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001362 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001363 // C++ [basic.lookup.koenig]p2:
1364 // [...]
1365 // -- If T is a class type (including unions), its associated
1366 // classes are: the class itself; the class of which it is a
1367 // member, if any; and its direct and indirect base
1368 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001369 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001370
1371 // Add the class of which it is a member, if any.
1372 DeclContext *Ctx = Class->getDeclContext();
1373 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1374 AssociatedClasses.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001375 // Add the associated namespace for this class.
1376 while (Ctx->isRecord())
1377 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001378 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001379
Douglas Gregore254f902009-02-04 00:32:51 +00001380 // Add the class itself. If we've already seen this class, we don't
1381 // need to visit base classes.
1382 if (!AssociatedClasses.insert(Class))
1383 return;
1384
Mike Stump11289f42009-09-09 15:08:12 +00001385 // -- If T is a template-id, its associated namespaces and classes are
1386 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001387 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001388 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001389 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001390 // namespaces in which any template template arguments are defined; and
1391 // the classes in which any member templates used as template template
1392 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001393 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001394 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001395 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1396 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1397 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1398 AssociatedClasses.insert(EnclosingClass);
1399 // Add the associated namespace for this class.
1400 while (Ctx->isRecord())
1401 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001402 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001403
Douglas Gregor197e5f72009-07-08 07:51:57 +00001404 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1405 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1406 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1407 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001408 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001409 }
Mike Stump11289f42009-09-09 15:08:12 +00001410
John McCall67da35c2010-02-04 22:26:26 +00001411 // Only recurse into base classes for complete types.
1412 if (!Class->hasDefinition()) {
1413 // FIXME: we might need to instantiate templates here
1414 return;
1415 }
1416
Douglas Gregore254f902009-02-04 00:32:51 +00001417 // Add direct and indirect base classes along with their associated
1418 // namespaces.
1419 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1420 Bases.push_back(Class);
1421 while (!Bases.empty()) {
1422 // Pop this class off the stack.
1423 Class = Bases.back();
1424 Bases.pop_back();
1425
1426 // Visit the base classes.
1427 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1428 BaseEnd = Class->bases_end();
1429 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001430 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001431 // In dependent contexts, we do ADL twice, and the first time around,
1432 // the base type might be a dependent TemplateSpecializationType, or a
1433 // TemplateTypeParmType. If that happens, simply ignore it.
1434 // FIXME: If we want to support export, we probably need to add the
1435 // namespace of the template in a TemplateSpecializationType, or even
1436 // the classes and namespaces of known non-dependent arguments.
1437 if (!BaseType)
1438 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001439 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1440 if (AssociatedClasses.insert(BaseDecl)) {
1441 // Find the associated namespace for this base class.
1442 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1443 while (BaseCtx->isRecord())
1444 BaseCtx = BaseCtx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001445 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001446
1447 // Make sure we visit the bases of this base class.
1448 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1449 Bases.push_back(BaseDecl);
1450 }
1451 }
1452 }
1453}
1454
1455// \brief Add the associated classes and namespaces for
1456// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001457// (C++ [basic.lookup.koenig]p2).
1458static void
1459addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregore254f902009-02-04 00:32:51 +00001460 ASTContext &Context,
1461 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001462 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001463 // C++ [basic.lookup.koenig]p2:
1464 //
1465 // For each argument type T in the function call, there is a set
1466 // of zero or more associated namespaces and a set of zero or more
1467 // associated classes to be considered. The sets of namespaces and
1468 // classes is determined entirely by the types of the function
1469 // arguments (and the namespace of any template template
1470 // argument). Typedef names and using-declarations used to specify
1471 // the types do not contribute to this set. The sets of namespaces
1472 // and classes are determined in the following way:
1473 T = Context.getCanonicalType(T).getUnqualifiedType();
1474
1475 // -- If T is a pointer to U or an array of U, its associated
Mike Stump11289f42009-09-09 15:08:12 +00001476 // namespaces and classes are those associated with U.
Douglas Gregore254f902009-02-04 00:32:51 +00001477 //
1478 // We handle this by unwrapping pointer and array types immediately,
1479 // to avoid unnecessary recursion.
1480 while (true) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001481 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001482 T = Ptr->getPointeeType();
1483 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1484 T = Ptr->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001485 else
Douglas Gregore254f902009-02-04 00:32:51 +00001486 break;
1487 }
1488
1489 // -- If T is a fundamental type, its associated sets of
1490 // namespaces and classes are both empty.
John McCall9dd450b2009-09-21 23:43:11 +00001491 if (T->getAs<BuiltinType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001492 return;
1493
1494 // -- If T is a class type (including unions), its associated
1495 // classes are: the class itself; the class of which it is a
1496 // member, if any; and its direct and indirect base
1497 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001498 // which its associated classes are defined.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001499 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump11289f42009-09-09 15:08:12 +00001500 if (CXXRecordDecl *ClassDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001501 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001502 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1503 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001504 AssociatedClasses);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001505 return;
1506 }
Douglas Gregore254f902009-02-04 00:32:51 +00001507
1508 // -- If T is an enumeration type, its associated namespace is
1509 // the namespace in which it is defined. If it is class
1510 // member, its associated class is the member’s class; else
Mike Stump11289f42009-09-09 15:08:12 +00001511 // it has no associated class.
John McCall9dd450b2009-09-21 23:43:11 +00001512 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001513 EnumDecl *Enum = EnumT->getDecl();
1514
1515 DeclContext *Ctx = Enum->getDeclContext();
1516 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1517 AssociatedClasses.insert(EnclosingClass);
1518
1519 // Add the associated namespace for this class.
1520 while (Ctx->isRecord())
1521 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001522 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001523
1524 return;
1525 }
1526
1527 // -- If T is a function type, its associated namespaces and
1528 // classes are those associated with the function parameter
1529 // types and those associated with the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001530 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001531 // Return type
John McCall9dd450b2009-09-21 23:43:11 +00001532 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregore254f902009-02-04 00:32:51 +00001533 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001534 AssociatedNamespaces, AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001535
John McCall9dd450b2009-09-21 23:43:11 +00001536 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregore254f902009-02-04 00:32:51 +00001537 if (!Proto)
1538 return;
1539
1540 // Argument types
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001541 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001542 ArgEnd = Proto->arg_type_end();
Douglas Gregore254f902009-02-04 00:32:51 +00001543 Arg != ArgEnd; ++Arg)
1544 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallc7e8e792009-08-07 22:18:02 +00001545 AssociatedNamespaces, AssociatedClasses);
Mike Stump11289f42009-09-09 15:08:12 +00001546
Douglas Gregore254f902009-02-04 00:32:51 +00001547 return;
1548 }
1549
1550 // -- If T is a pointer to a member function of a class X, its
1551 // associated namespaces and classes are those associated
1552 // with the function parameter types and return type,
Mike Stump11289f42009-09-09 15:08:12 +00001553 // together with those associated with X.
Douglas Gregore254f902009-02-04 00:32:51 +00001554 //
1555 // -- If T is a pointer to a data member of class X, its
1556 // associated namespaces and classes are those associated
1557 // with the member type together with those associated with
Mike Stump11289f42009-09-09 15:08:12 +00001558 // X.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001559 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001560 // Handle the type that the pointer to member points to.
1561 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1562 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001563 AssociatedNamespaces,
1564 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001565
1566 // Handle the class type into which this points.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001567 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001568 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1569 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001570 AssociatedNamespaces,
1571 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001572
1573 return;
1574 }
1575
1576 // FIXME: What about block pointers?
1577 // FIXME: What about Objective-C message sends?
1578}
1579
1580/// \brief Find the associated classes and namespaces for
1581/// argument-dependent lookup for a call with the given set of
1582/// arguments.
1583///
1584/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001585/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001586/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001587void
Douglas Gregore254f902009-02-04 00:32:51 +00001588Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1589 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001590 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001591 AssociatedNamespaces.clear();
1592 AssociatedClasses.clear();
1593
1594 // C++ [basic.lookup.koenig]p2:
1595 // For each argument type T in the function call, there is a set
1596 // of zero or more associated namespaces and a set of zero or more
1597 // associated classes to be considered. The sets of namespaces and
1598 // classes is determined entirely by the types of the function
1599 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001600 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001601 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1602 Expr *Arg = Args[ArgIdx];
1603
1604 if (Arg->getType() != Context.OverloadTy) {
1605 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001606 AssociatedNamespaces,
1607 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001608 continue;
1609 }
1610
1611 // [...] In addition, if the argument is the name or address of a
1612 // set of overloaded functions and/or function templates, its
1613 // associated classes and namespaces are the union of those
1614 // associated with each of the members of the set: the namespace
1615 // in which the function or function template is defined and the
1616 // classes and namespaces associated with its (non-dependent)
1617 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001618 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001619 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1620 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1621 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001622
John McCalld14a8642009-11-21 08:51:07 +00001623 // TODO: avoid the copies. This should be easy when the cases
1624 // share a storage implementation.
1625 llvm::SmallVector<NamedDecl*, 8> Functions;
1626
1627 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1628 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00001629 else
Douglas Gregore254f902009-02-04 00:32:51 +00001630 continue;
1631
John McCalld14a8642009-11-21 08:51:07 +00001632 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1633 E = Functions.end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001634 // Look through any using declarations to find the underlying function.
1635 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001636
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001637 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1638 if (!FDecl)
1639 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001640
1641 // Add the classes and namespaces associated with the parameter
1642 // types and return type of this function.
1643 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001644 AssociatedNamespaces,
1645 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001646 }
1647 }
1648}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001649
1650/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1651/// an acceptable non-member overloaded operator for a call whose
1652/// arguments have types T1 (and, if non-empty, T2). This routine
1653/// implements the check in C++ [over.match.oper]p3b2 concerning
1654/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001655static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001656IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1657 QualType T1, QualType T2,
1658 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001659 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1660 return true;
1661
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001662 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1663 return true;
1664
John McCall9dd450b2009-09-21 23:43:11 +00001665 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001666 if (Proto->getNumArgs() < 1)
1667 return false;
1668
1669 if (T1->isEnumeralType()) {
1670 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001671 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001672 return true;
1673 }
1674
1675 if (Proto->getNumArgs() < 2)
1676 return false;
1677
1678 if (!T2.isNull() && T2->isEnumeralType()) {
1679 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001680 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001681 return true;
1682 }
1683
1684 return false;
1685}
1686
John McCall5cebab12009-11-18 07:57:50 +00001687NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1688 LookupNameKind NameKind,
1689 RedeclarationKind Redecl) {
1690 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1691 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00001692 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00001693}
1694
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001695/// \brief Find the protocol with the given name, if any.
1696ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCall9f3059a2009-10-09 21:13:30 +00001697 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001698 return cast_or_null<ObjCProtocolDecl>(D);
1699}
1700
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001701void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001702 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00001703 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001704 // C++ [over.match.oper]p3:
1705 // -- The set of non-member candidates is the result of the
1706 // unqualified lookup of operator@ in the context of the
1707 // expression according to the usual rules for name lookup in
1708 // unqualified function calls (3.4.2) except that all member
1709 // functions are ignored. However, if no operand has a class
1710 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001711 // that have a first parameter of type T1 or "reference to
1712 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001713 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001714 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001715 // when T2 is an enumeration type, are candidate functions.
1716 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00001717 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1718 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00001719
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001720 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1721
John McCall9f3059a2009-10-09 21:13:30 +00001722 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001723 return;
1724
1725 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1726 Op != OpEnd; ++Op) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001727 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001728 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
John McCall4c4c1df2010-01-26 03:27:55 +00001729 Functions.addDecl(FD, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001730 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor15448f82009-06-27 21:05:07 +00001731 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1732 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001733 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001734 // later?
1735 if (!FunTmpl->getDeclContext()->isRecord())
John McCall4c4c1df2010-01-26 03:27:55 +00001736 Functions.addDecl(FunTmpl, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00001737 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001738 }
1739}
1740
John McCall8fe68082010-01-26 07:16:45 +00001741void ADLResult::insert(NamedDecl *New) {
1742 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1743
1744 // If we haven't yet seen a decl for this key, or the last decl
1745 // was exactly this one, we're done.
1746 if (Old == 0 || Old == New) {
1747 Old = New;
1748 return;
1749 }
1750
1751 // Otherwise, decide which is a more recent redeclaration.
1752 FunctionDecl *OldFD, *NewFD;
1753 if (isa<FunctionTemplateDecl>(New)) {
1754 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1755 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1756 } else {
1757 OldFD = cast<FunctionDecl>(Old);
1758 NewFD = cast<FunctionDecl>(New);
1759 }
1760
1761 FunctionDecl *Cursor = NewFD;
1762 while (true) {
1763 Cursor = Cursor->getPreviousDeclaration();
1764
1765 // If we got to the end without finding OldFD, OldFD is the newer
1766 // declaration; leave things as they are.
1767 if (!Cursor) return;
1768
1769 // If we do find OldFD, then NewFD is newer.
1770 if (Cursor == OldFD) break;
1771
1772 // Otherwise, keep looking.
1773 }
1774
1775 Old = New;
1776}
1777
Sebastian Redlc057f422009-10-23 19:23:15 +00001778void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001779 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00001780 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001781 // Find all of the associated namespaces and classes based on the
1782 // arguments we have.
1783 AssociatedNamespaceSet AssociatedNamespaces;
1784 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00001785 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00001786 AssociatedNamespaces,
1787 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001788
Sebastian Redlc057f422009-10-23 19:23:15 +00001789 QualType T1, T2;
1790 if (Operator) {
1791 T1 = Args[0]->getType();
1792 if (NumArgs >= 2)
1793 T2 = Args[1]->getType();
1794 }
1795
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001796 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001797 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1798 // and let Y be the lookup set produced by argument dependent
1799 // lookup (defined as follows). If X contains [...] then Y is
1800 // empty. Otherwise Y is the set of declarations found in the
1801 // namespaces associated with the argument types as described
1802 // below. The set of declarations found by the lookup of the name
1803 // is the union of X and Y.
1804 //
1805 // Here, we compute Y and add its members to the overloaded
1806 // candidate set.
1807 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001808 NSEnd = AssociatedNamespaces.end();
1809 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001810 // When considering an associated namespace, the lookup is the
1811 // same as the lookup performed when the associated namespace is
1812 // used as a qualifier (3.4.3.2) except that:
1813 //
1814 // -- Any using-directives in the associated namespace are
1815 // ignored.
1816 //
John McCallc7e8e792009-08-07 22:18:02 +00001817 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001818 // associated classes are visible within their respective
1819 // namespaces even if they are not visible during an ordinary
1820 // lookup (11.4).
1821 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00001822 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00001823 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00001824 // If the only declaration here is an ordinary friend, consider
1825 // it only if it was declared in an associated classes.
1826 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00001827 DeclContext *LexDC = D->getLexicalDeclContext();
1828 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1829 continue;
1830 }
Mike Stump11289f42009-09-09 15:08:12 +00001831
John McCall91f61fc2010-01-26 06:04:06 +00001832 if (isa<UsingShadowDecl>(D))
1833 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00001834
John McCall91f61fc2010-01-26 06:04:06 +00001835 if (isa<FunctionDecl>(D)) {
1836 if (Operator &&
1837 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
1838 T1, T2, Context))
1839 continue;
John McCall8fe68082010-01-26 07:16:45 +00001840 } else if (!isa<FunctionTemplateDecl>(D))
1841 continue;
1842
1843 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00001844 }
1845 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001846}
Douglas Gregor2d435302009-12-30 17:04:44 +00001847
1848//----------------------------------------------------------------------------
1849// Search for all visible declarations.
1850//----------------------------------------------------------------------------
1851VisibleDeclConsumer::~VisibleDeclConsumer() { }
1852
1853namespace {
1854
1855class ShadowContextRAII;
1856
1857class VisibleDeclsRecord {
1858public:
1859 /// \brief An entry in the shadow map, which is optimized to store a
1860 /// single declaration (the common case) but can also store a list
1861 /// of declarations.
1862 class ShadowMapEntry {
1863 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1864
1865 /// \brief Contains either the solitary NamedDecl * or a vector
1866 /// of declarations.
1867 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1868
1869 public:
1870 ShadowMapEntry() : DeclOrVector() { }
1871
1872 void Add(NamedDecl *ND);
1873 void Destroy();
1874
1875 // Iteration.
1876 typedef NamedDecl **iterator;
1877 iterator begin();
1878 iterator end();
1879 };
1880
1881private:
1882 /// \brief A mapping from declaration names to the declarations that have
1883 /// this name within a particular scope.
1884 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
1885
1886 /// \brief A list of shadow maps, which is used to model name hiding.
1887 std::list<ShadowMap> ShadowMaps;
1888
1889 /// \brief The declaration contexts we have already visited.
1890 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
1891
1892 friend class ShadowContextRAII;
1893
1894public:
1895 /// \brief Determine whether we have already visited this context
1896 /// (and, if not, note that we are going to visit that context now).
1897 bool visitedContext(DeclContext *Ctx) {
1898 return !VisitedContexts.insert(Ctx);
1899 }
1900
1901 /// \brief Determine whether the given declaration is hidden in the
1902 /// current scope.
1903 ///
1904 /// \returns the declaration that hides the given declaration, or
1905 /// NULL if no such declaration exists.
1906 NamedDecl *checkHidden(NamedDecl *ND);
1907
1908 /// \brief Add a declaration to the current shadow map.
1909 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
1910};
1911
1912/// \brief RAII object that records when we've entered a shadow context.
1913class ShadowContextRAII {
1914 VisibleDeclsRecord &Visible;
1915
1916 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
1917
1918public:
1919 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
1920 Visible.ShadowMaps.push_back(ShadowMap());
1921 }
1922
1923 ~ShadowContextRAII() {
1924 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
1925 EEnd = Visible.ShadowMaps.back().end();
1926 E != EEnd;
1927 ++E)
1928 E->second.Destroy();
1929
1930 Visible.ShadowMaps.pop_back();
1931 }
1932};
1933
1934} // end anonymous namespace
1935
1936void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
1937 if (DeclOrVector.isNull()) {
1938 // 0 - > 1 elements: just set the single element information.
1939 DeclOrVector = ND;
1940 return;
1941 }
1942
1943 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
1944 // 1 -> 2 elements: create the vector of results and push in the
1945 // existing declaration.
1946 DeclVector *Vec = new DeclVector;
1947 Vec->push_back(PrevND);
1948 DeclOrVector = Vec;
1949 }
1950
1951 // Add the new element to the end of the vector.
1952 DeclOrVector.get<DeclVector*>()->push_back(ND);
1953}
1954
1955void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
1956 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
1957 delete Vec;
1958 DeclOrVector = ((NamedDecl *)0);
1959 }
1960}
1961
1962VisibleDeclsRecord::ShadowMapEntry::iterator
1963VisibleDeclsRecord::ShadowMapEntry::begin() {
1964 if (DeclOrVector.isNull())
1965 return 0;
1966
1967 if (DeclOrVector.dyn_cast<NamedDecl *>())
1968 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
1969
1970 return DeclOrVector.get<DeclVector *>()->begin();
1971}
1972
1973VisibleDeclsRecord::ShadowMapEntry::iterator
1974VisibleDeclsRecord::ShadowMapEntry::end() {
1975 if (DeclOrVector.isNull())
1976 return 0;
1977
1978 if (DeclOrVector.dyn_cast<NamedDecl *>())
1979 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
1980
1981 return DeclOrVector.get<DeclVector *>()->end();
1982}
1983
1984NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00001985 // Look through using declarations.
1986 ND = ND->getUnderlyingDecl();
1987
Douglas Gregor2d435302009-12-30 17:04:44 +00001988 unsigned IDNS = ND->getIdentifierNamespace();
1989 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
1990 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
1991 SM != SMEnd; ++SM) {
1992 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
1993 if (Pos == SM->end())
1994 continue;
1995
1996 for (ShadowMapEntry::iterator I = Pos->second.begin(),
1997 IEnd = Pos->second.end();
1998 I != IEnd; ++I) {
1999 // A tag declaration does not hide a non-tag declaration.
2000 if ((*I)->getIdentifierNamespace() == Decl::IDNS_Tag &&
2001 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2002 Decl::IDNS_ObjCProtocol)))
2003 continue;
2004
2005 // Protocols are in distinct namespaces from everything else.
2006 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2007 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2008 (*I)->getIdentifierNamespace() != IDNS)
2009 continue;
2010
Douglas Gregor09bbc652010-01-14 15:47:35 +00002011 // Functions and function templates in the same scope overload
2012 // rather than hide. FIXME: Look for hiding based on function
2013 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002014 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002015 ND->isFunctionOrFunctionTemplate() &&
2016 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002017 continue;
2018
Douglas Gregor2d435302009-12-30 17:04:44 +00002019 // We've found a declaration that hides this one.
2020 return *I;
2021 }
2022 }
2023
2024 return 0;
2025}
2026
2027static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2028 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002029 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002030 VisibleDeclConsumer &Consumer,
2031 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002032 if (!Ctx)
2033 return;
2034
Douglas Gregor2d435302009-12-30 17:04:44 +00002035 // Make sure we don't visit the same context twice.
2036 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2037 return;
2038
2039 // Enumerate all of the results in this context.
2040 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2041 CurCtx = CurCtx->getNextContext()) {
2042 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2043 DEnd = CurCtx->decls_end();
2044 D != DEnd; ++D) {
2045 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2046 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002047 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002048 Visited.add(ND);
2049 }
2050
2051 // Visit transparent contexts inside this context.
2052 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2053 if (InnerCtx->isTransparentContext())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002054 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002055 Consumer, Visited);
2056 }
2057 }
2058 }
2059
2060 // Traverse using directives for qualified name lookup.
2061 if (QualifiedNameLookup) {
2062 ShadowContextRAII Shadow(Visited);
2063 DeclContext::udir_iterator I, E;
2064 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2065 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002066 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002067 }
2068 }
2069
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002070 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002071 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002072 if (!Record->hasDefinition())
2073 return;
2074
Douglas Gregor2d435302009-12-30 17:04:44 +00002075 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2076 BEnd = Record->bases_end();
2077 B != BEnd; ++B) {
2078 QualType BaseType = B->getType();
2079
2080 // Don't look into dependent bases, because name lookup can't look
2081 // there anyway.
2082 if (BaseType->isDependentType())
2083 continue;
2084
2085 const RecordType *Record = BaseType->getAs<RecordType>();
2086 if (!Record)
2087 continue;
2088
2089 // FIXME: It would be nice to be able to determine whether referencing
2090 // a particular member would be ambiguous. For example, given
2091 //
2092 // struct A { int member; };
2093 // struct B { int member; };
2094 // struct C : A, B { };
2095 //
2096 // void f(C *c) { c->### }
2097 //
2098 // accessing 'member' would result in an ambiguity. However, we
2099 // could be smart enough to qualify the member with the base
2100 // class, e.g.,
2101 //
2102 // c->B::member
2103 //
2104 // or
2105 //
2106 // c->A::member
2107
2108 // Find results in this base class (and its bases).
2109 ShadowContextRAII Shadow(Visited);
2110 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002111 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002112 }
2113 }
2114
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002115 // Traverse the contexts of Objective-C classes.
2116 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2117 // Traverse categories.
2118 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2119 Category; Category = Category->getNextClassCategory()) {
2120 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002121 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2122 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002123 }
2124
2125 // Traverse protocols.
2126 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2127 E = IFace->protocol_end(); I != E; ++I) {
2128 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002129 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2130 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002131 }
2132
2133 // Traverse the superclass.
2134 if (IFace->getSuperClass()) {
2135 ShadowContextRAII Shadow(Visited);
2136 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002137 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002138 }
2139 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2140 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2141 E = Protocol->protocol_end(); I != E; ++I) {
2142 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002143 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2144 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002145 }
2146 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2147 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2148 E = Category->protocol_end(); I != E; ++I) {
2149 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002150 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2151 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002152 }
2153 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002154}
2155
2156static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2157 UnqualUsingDirectiveSet &UDirs,
2158 VisibleDeclConsumer &Consumer,
2159 VisibleDeclsRecord &Visited) {
2160 if (!S)
2161 return;
2162
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002163 if (!S->getEntity() || !S->getParent() ||
2164 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2165 // Walk through the declarations in this Scope.
2166 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2167 D != DEnd; ++D) {
2168 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2169 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002170 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002171 Visited.add(ND);
2172 }
2173 }
2174 }
2175
Douglas Gregor2d435302009-12-30 17:04:44 +00002176 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002177 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002178 // Look into this scope's declaration context, along with any of its
2179 // parent lookup contexts (e.g., enclosing classes), up to the point
2180 // where we hit the context stored in the next outer scope.
2181 Entity = (DeclContext *)S->getEntity();
2182 DeclContext *OuterCtx = findOuterContext(S);
2183
2184 for (DeclContext *Ctx = Entity; Ctx && Ctx->getPrimaryContext() != OuterCtx;
2185 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002186 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2187 if (Method->isInstanceMethod()) {
2188 // For instance methods, look for ivars in the method's interface.
2189 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2190 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002191 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2192 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2193 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002194 }
2195
2196 // We've already performed all of the name lookup that we need
2197 // to for Objective-C methods; the next context will be the
2198 // outer scope.
2199 break;
2200 }
2201
Douglas Gregor2d435302009-12-30 17:04:44 +00002202 if (Ctx->isFunctionOrMethod())
2203 continue;
2204
2205 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002206 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002207 }
2208 } else if (!S->getParent()) {
2209 // Look into the translation unit scope. We walk through the translation
2210 // unit's declaration context, because the Scope itself won't have all of
2211 // the declarations if we loaded a precompiled header.
2212 // FIXME: We would like the translation unit's Scope object to point to the
2213 // translation unit, so we don't need this special "if" branch. However,
2214 // doing so would force the normal C++ name-lookup code to look into the
2215 // translation unit decl when the IdentifierInfo chains would suffice.
2216 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002217 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002218 Entity = Result.getSema().Context.getTranslationUnitDecl();
2219 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002220 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002221 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002222
2223 if (Entity) {
2224 // Lookup visible declarations in any namespaces found by using
2225 // directives.
2226 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2227 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2228 for (; UI != UEnd; ++UI)
2229 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002230 Result, /*QualifiedNameLookup=*/false,
2231 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002232 }
2233
2234 // Lookup names in the parent scope.
2235 ShadowContextRAII Shadow(Visited);
2236 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2237}
2238
2239void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2240 VisibleDeclConsumer &Consumer) {
2241 // Determine the set of using directives available during
2242 // unqualified name lookup.
2243 Scope *Initial = S;
2244 UnqualUsingDirectiveSet UDirs;
2245 if (getLangOptions().CPlusPlus) {
2246 // Find the first namespace or translation-unit scope.
2247 while (S && !isNamespaceOrTranslationUnitScope(S))
2248 S = S->getParent();
2249
2250 UDirs.visitScopeChain(Initial, S);
2251 }
2252 UDirs.done();
2253
2254 // Look for visible declarations.
2255 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2256 VisibleDeclsRecord Visited;
2257 ShadowContextRAII Shadow(Visited);
2258 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2259}
2260
2261void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2262 VisibleDeclConsumer &Consumer) {
2263 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2264 VisibleDeclsRecord Visited;
2265 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002266 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2267 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002268}
2269
2270//----------------------------------------------------------------------------
2271// Typo correction
2272//----------------------------------------------------------------------------
2273
2274namespace {
2275class TypoCorrectionConsumer : public VisibleDeclConsumer {
2276 /// \brief The name written that is a typo in the source.
2277 llvm::StringRef Typo;
2278
2279 /// \brief The results found that have the smallest edit distance
2280 /// found (so far) with the typo name.
2281 llvm::SmallVector<NamedDecl *, 4> BestResults;
2282
2283 /// \brief The best edit distance found so far.
2284 unsigned BestEditDistance;
2285
2286public:
2287 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2288 : Typo(Typo->getName()) { }
2289
Douglas Gregor09bbc652010-01-14 15:47:35 +00002290 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002291
2292 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2293 iterator begin() const { return BestResults.begin(); }
2294 iterator end() const { return BestResults.end(); }
2295 bool empty() const { return BestResults.empty(); }
2296
2297 unsigned getBestEditDistance() const { return BestEditDistance; }
2298};
2299
2300}
2301
Douglas Gregor09bbc652010-01-14 15:47:35 +00002302void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2303 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002304 // Don't consider hidden names for typo correction.
2305 if (Hiding)
2306 return;
2307
2308 // Only consider entities with identifiers for names, ignoring
2309 // special names (constructors, overloaded operators, selectors,
2310 // etc.).
2311 IdentifierInfo *Name = ND->getIdentifier();
2312 if (!Name)
2313 return;
2314
2315 // Compute the edit distance between the typo and the name of this
2316 // entity. If this edit distance is not worse than the best edit
2317 // distance we've seen so far, add it to the list of results.
2318 unsigned ED = Typo.edit_distance(Name->getName());
2319 if (!BestResults.empty()) {
2320 if (ED < BestEditDistance) {
2321 // This result is better than any we've seen before; clear out
2322 // the previous results.
2323 BestResults.clear();
2324 BestEditDistance = ED;
2325 } else if (ED > BestEditDistance) {
2326 // This result is worse than the best results we've seen so far;
2327 // ignore it.
2328 return;
2329 }
2330 } else
2331 BestEditDistance = ED;
2332
2333 BestResults.push_back(ND);
2334}
2335
2336/// \brief Try to "correct" a typo in the source code by finding
2337/// visible declarations whose names are similar to the name that was
2338/// present in the source code.
2339///
2340/// \param Res the \c LookupResult structure that contains the name
2341/// that was present in the source code along with the name-lookup
2342/// criteria used to search for the name. On success, this structure
2343/// will contain the results of name lookup.
2344///
2345/// \param S the scope in which name lookup occurs.
2346///
2347/// \param SS the nested-name-specifier that precedes the name we're
2348/// looking for, if present.
2349///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002350/// \param MemberContext if non-NULL, the context in which to look for
2351/// a member access expression.
2352///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002353/// \param EnteringContext whether we're entering the context described by
2354/// the nested-name-specifier SS.
2355///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002356/// \param OPT when non-NULL, the search for visible declarations will
2357/// also walk the protocols in the qualified interfaces of \p OPT.
2358///
Douglas Gregor2d435302009-12-30 17:04:44 +00002359/// \returns true if the typo was corrected, in which case the \p Res
2360/// structure will contain the results of name lookup for the
2361/// corrected name. Otherwise, returns false.
2362bool Sema::CorrectTypo(LookupResult &Res, Scope *S, const CXXScopeSpec *SS,
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002363 DeclContext *MemberContext, bool EnteringContext,
2364 const ObjCObjectPointerType *OPT) {
Ted Kremeneke51136e2010-01-06 00:23:04 +00002365 if (Diags.hasFatalErrorOccurred())
2366 return false;
Ted Kremenek54516822010-02-02 02:07:01 +00002367
2368 // Provide a stop gap for files that are just seriously broken. Trying
2369 // to correct all typos can turn into a HUGE performance penalty, causing
2370 // some files to take minutes to get rejected by the parser.
2371 // FIXME: Is this the right solution?
2372 if (TyposCorrected == 20)
2373 return false;
2374 ++TyposCorrected;
Ted Kremeneke51136e2010-01-06 00:23:04 +00002375
Douglas Gregor2d435302009-12-30 17:04:44 +00002376 // We only attempt to correct typos for identifiers.
2377 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2378 if (!Typo)
2379 return false;
2380
2381 // If the scope specifier itself was invalid, don't try to correct
2382 // typos.
2383 if (SS && SS->isInvalid())
2384 return false;
2385
2386 // Never try to correct typos during template deduction or
2387 // instantiation.
2388 if (!ActiveTemplateInstantiations.empty())
2389 return false;
2390
2391 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002392 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002393 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002394
2395 // Look in qualified interfaces.
2396 if (OPT) {
2397 for (ObjCObjectPointerType::qual_iterator
2398 I = OPT->qual_begin(), E = OPT->qual_end();
2399 I != E; ++I)
2400 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2401 }
2402 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002403 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2404 if (!DC)
2405 return false;
2406
2407 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2408 } else {
2409 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2410 }
2411
2412 if (Consumer.empty())
2413 return false;
2414
2415 // Only allow a single, closest name in the result set (it's okay to
2416 // have overloads of that name, though).
2417 TypoCorrectionConsumer::iterator I = Consumer.begin();
2418 DeclarationName BestName = (*I)->getDeclName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002419
2420 // If we've found an Objective-C ivar or property, don't perform
2421 // name lookup again; we'll just return the result directly.
2422 NamedDecl *FoundBest = 0;
2423 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I))
2424 FoundBest = *I;
Douglas Gregor2d435302009-12-30 17:04:44 +00002425 ++I;
2426 for(TypoCorrectionConsumer::iterator IEnd = Consumer.end(); I != IEnd; ++I) {
2427 if (BestName != (*I)->getDeclName())
2428 return false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002429
2430 // FIXME: If there are both ivars and properties of the same name,
2431 // don't return both because the callee can't handle two
2432 // results. We really need to separate ivar lookup from property
2433 // lookup to avoid this problem.
2434 FoundBest = 0;
Douglas Gregor2d435302009-12-30 17:04:44 +00002435 }
2436
2437 // BestName is the closest viable name to what the user
2438 // typed. However, to make sure that we don't pick something that's
2439 // way off, make sure that the user typed at least 3 characters for
2440 // each correction.
2441 unsigned ED = Consumer.getBestEditDistance();
2442 if (ED == 0 || (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
2443 return false;
2444
2445 // Perform name lookup again with the name we chose, and declare
2446 // success if we found something that was not ambiguous.
2447 Res.clear();
2448 Res.setLookupName(BestName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002449
2450 // If we found an ivar or property, add that result; no further
2451 // lookup is required.
2452 if (FoundBest)
2453 Res.addDecl(FoundBest);
2454 // If we're looking into the context of a member, perform qualified
2455 // name lookup on the best name.
2456 else if (MemberContext)
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002457 LookupQualifiedName(Res, MemberContext);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002458 // Perform lookup as if we had just parsed the best name.
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002459 else
2460 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2461 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00002462
2463 if (Res.isAmbiguous()) {
2464 Res.suppressDiagnostics();
2465 return false;
2466 }
2467
2468 return Res.getResultKind() != LookupResult::NotFound;
Douglas Gregor2d435302009-12-30 17:04:44 +00002469}