blob: da7626780caafeefc64f29bcaacff1d5c8582e6d [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6e247262009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor546be3c2009-12-30 17:04:44 +000030#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000031#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000032#include <vector>
33#include <iterator>
34#include <utility>
35#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000036
37using namespace clang;
38
John McCalld7be78a2009-11-10 07:01:13 +000039namespace {
40 class UnqualUsingEntry {
41 const DeclContext *Nominated;
42 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000043
John McCalld7be78a2009-11-10 07:01:13 +000044 public:
45 UnqualUsingEntry(const DeclContext *Nominated,
46 const DeclContext *CommonAncestor)
47 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
48 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000049
John McCalld7be78a2009-11-10 07:01:13 +000050 const DeclContext *getCommonAncestor() const {
51 return CommonAncestor;
52 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000053
John McCalld7be78a2009-11-10 07:01:13 +000054 const DeclContext *getNominatedNamespace() const {
55 return Nominated;
56 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000057
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +000063
John McCalld7be78a2009-11-10 07:01:13 +000064 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
65 return E.getCommonAncestor() < DC;
66 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000067
John McCalld7be78a2009-11-10 07:01:13 +000068 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
69 return DC < E.getCommonAncestor();
70 }
71 };
72 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000073
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +000078
John McCalld7be78a2009-11-10 07:01:13 +000079 ListTy list;
80 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000081
John McCalld7be78a2009-11-10 07:01:13 +000082 public:
83 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000084
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +000093
John McCalld7be78a2009-11-10 07:01:13 +000094 for (; S; S = S->getParent()) {
John McCalld7be78a2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000105 }
106 }
John McCalld7be78a2009-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 McCall12ea5782009-11-10 09:20:04 +0000171 Common = Common->getPrimaryContext();
John McCalld7be78a2009-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 McCall12ea5782009-11-10 09:20:04 +0000190 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000191 UnqualUsingEntry::Comparator());
192 }
193 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000194}
195
John McCall1d7c5282009-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 McCall4e0d81f2009-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 McCall1d7c5282009-12-18 10:40:03 +0000216}
217
218static bool IsAcceptableNamespaceName(NamedDecl *D, unsigned IDNS) {
John McCall4e0d81f2009-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 McCall1d7c5282009-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 Gregor2a3009a2009-02-03 19:21:40 +0000252// Retrieve the set of identifier namespaces that correspond to a
253// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000254static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
255 bool CPlusPlus,
256 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000257 unsigned IDNS = 0;
258 switch (NameKind) {
259 case Sema::LookupOrdinaryName:
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000260 case Sema::LookupOperatorName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000261 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000262 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000263 if (CPlusPlus) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000264 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
John McCall1d7c5282009-12-18 10:40:03 +0000265 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
266 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000267 break;
268
269 case Sema::LookupTagName:
270 IDNS = Decl::IDNS_Tag;
John McCall1d7c5282009-12-18 10:40:03 +0000271 if (CPlusPlus && Redeclaration)
272 IDNS |= Decl::IDNS_TagFriend;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000273 break;
274
275 case Sema::LookupMemberName:
276 IDNS = Decl::IDNS_Member;
277 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000278 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-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 Gregor6e378de2009-04-23 23:18:26 +0000285
John McCall9f54ad42009-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 Gregor8fc463a2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000298 }
299 return IDNS;
300}
301
John McCall1d7c5282009-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 McCallf36e02d2009-10-09 21:13:30 +0000309// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000310void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000311 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000312}
313
John McCall7453ed42009-11-22 00:44:51 +0000314/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000315void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000316 unsigned N = Decls.size();
John McCall9f54ad42009-12-10 09:41:52 +0000317
John McCallf36e02d2009-10-09 21:13:30 +0000318 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000319 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000320 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000321 return;
322 }
323
John McCall7453ed42009-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 McCall7ba107a2009-11-18 02:36:19 +0000326 if (N == 1) {
John McCalleec51cf2010-01-20 00:46:10 +0000327 if (isa<FunctionTemplateDecl>(*Decls.begin()))
John McCall7453ed42009-11-22 00:44:51 +0000328 ResultKind = FoundOverloaded;
John McCalleec51cf2010-01-20 00:46:10 +0000329 else if (isa<UnresolvedUsingValueDecl>(*Decls.begin()))
John McCall7ba107a2009-11-18 02:36:19 +0000330 ResultKind = FoundUnresolvedValue;
331 return;
332 }
John McCallf36e02d2009-10-09 21:13:30 +0000333
John McCall6e247262009-10-10 05:48:19 +0000334 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000335 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000336
John McCallf36e02d2009-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 McCall7453ed42009-11-22 00:44:51 +0000341 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000342
343 unsigned UniqueTagIndex = 0;
344
345 unsigned I = 0;
346 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000347 NamedDecl *D = Decls[I]->getUnderlyingDecl();
348 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000349
John McCall314be4e2009-11-17 07:50:12 +0000350 if (!Unique.insert(D)) {
John McCallf36e02d2009-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 McCallf36e02d2009-10-09 21:13:30 +0000354 } else {
355 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000356
357 if (isa<UnresolvedUsingValueDecl>(D)) {
358 HasUnresolved = true;
359 } else if (isa<TagDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000360 if (HasTag)
361 Ambiguous = true;
362 UniqueTagIndex = I;
363 HasTag = true;
John McCall7453ed42009-11-22 00:44:51 +0000364 } else if (isa<FunctionTemplateDecl>(D)) {
365 HasFunction = true;
366 HasFunctionTemplate = true;
367 } else if (isa<FunctionDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000368 HasFunction = true;
369 } else {
370 if (HasNonFunction)
371 Ambiguous = true;
372 HasNonFunction = true;
373 }
374 I++;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000375 }
Mike Stump1eb44332009-09-09 15:08:12 +0000376 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000377
John McCallf36e02d2009-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 McCallfda8e122009-12-03 00:58:24 +0000387 if (HideTags && HasTag && !Ambiguous &&
388 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000389 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000390
John McCallf36e02d2009-10-09 21:13:30 +0000391 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000392
John McCallfda8e122009-12-03 00:58:24 +0000393 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000394 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000395
John McCallf36e02d2009-10-09 21:13:30 +0000396 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000397 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000398 else if (HasUnresolved)
399 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000400 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000401 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000402 else
John McCalla24dc2e2009-11-17 02:14:36 +0000403 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000404}
405
John McCall7d384dd2009-11-18 07:57:50 +0000406void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000407 CXXBasePaths::paths_iterator I, E;
408 DeclContext::lookup_iterator DI, DE;
409 for (I = P.begin(), E = P.end(); I != E; ++I)
410 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
411 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000412}
413
John McCall7d384dd2009-11-18 07:57:50 +0000414void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000415 Paths = new CXXBasePaths;
416 Paths->swap(P);
417 addDeclsFromBasePaths(*Paths);
418 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000419 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000420}
421
John McCall7d384dd2009-11-18 07:57:50 +0000422void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000423 Paths = new CXXBasePaths;
424 Paths->swap(P);
425 addDeclsFromBasePaths(*Paths);
426 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000427 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000428}
429
John McCall7d384dd2009-11-18 07:57:50 +0000430void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-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 McCall7d384dd2009-11-18 07:57:50 +0000443static bool LookupDirect(LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000444 bool Found = false;
445
John McCalld7be78a2009-11-10 07:01:13 +0000446 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000447 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
448 if (R.isAcceptableDecl(*I)) {
449 R.addDecl(*I);
450 Found = true;
451 }
452 }
John McCallf36e02d2009-10-09 21:13:30 +0000453
Douglas Gregor48026d22010-01-11 18:40:55 +0000454 if (R.getLookupName().getNameKind()
455 == DeclarationName::CXXConversionFunctionName &&
456 !R.getLookupName().getCXXNameType()->isDependentType() &&
457 isa<CXXRecordDecl>(DC)) {
458 // C++ [temp.mem]p6:
459 // A specialization of a conversion function template is not found by
460 // name lookup. Instead, any conversion function templates visible in the
461 // context of the use are considered. [...]
462 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregor3f477a12010-01-12 01:17:50 +0000463 if (!Record->isDefinition())
464 return Found;
465
John McCalleec51cf2010-01-20 00:46:10 +0000466 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
467 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
468 UEnd = Unresolved->end(); U != UEnd; ++U) {
Douglas Gregor48026d22010-01-11 18:40:55 +0000469 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
470 if (!ConvTemplate)
471 continue;
472
473 // When we're performing lookup for the purposes of redeclaration, just
474 // add the conversion function template. When we deduce template
475 // arguments for specializations, we'll end up unifying the return
476 // type of the new declaration with the type of the function template.
477 if (R.isForRedeclaration()) {
478 R.addDecl(ConvTemplate);
479 Found = true;
480 continue;
481 }
482
483 // C++ [temp.mem]p6:
484 // [...] For each such operator, if argument deduction succeeds
485 // (14.9.2.3), the resulting specialization is used as if found by
486 // name lookup.
487 //
488 // When referencing a conversion function for any purpose other than
489 // a redeclaration (such that we'll be building an expression with the
490 // result), perform template argument deduction and place the
491 // specialization into the result set. We do this to avoid forcing all
492 // callers to perform special deduction for conversion functions.
493 Sema::TemplateDeductionInfo Info(R.getSema().Context);
494 FunctionDecl *Specialization = 0;
495
496 const FunctionProtoType *ConvProto
497 = ConvTemplate->getTemplatedDecl()->getType()
498 ->getAs<FunctionProtoType>();
499 assert(ConvProto && "Nonsensical conversion function template type");
500
501 // Compute the type of the function that we would expect the conversion
502 // function to have, if it were to match the name given.
503 // FIXME: Calling convention!
504 QualType ExpectedType
505 = R.getSema().Context.getFunctionType(
506 R.getLookupName().getCXXNameType(),
507 0, 0, ConvProto->isVariadic(),
508 ConvProto->getTypeQuals(),
509 false, false, 0, 0,
510 ConvProto->getNoReturnAttr());
511
512 // Perform template argument deduction against the type that we would
513 // expect the function to have.
514 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
515 Specialization, Info)
516 == Sema::TDK_Success) {
517 R.addDecl(Specialization);
518 Found = true;
519 }
520 }
521 }
522
John McCallf36e02d2009-10-09 21:13:30 +0000523 return Found;
524}
525
John McCalld7be78a2009-11-10 07:01:13 +0000526// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000527static bool
John McCall7d384dd2009-11-18 07:57:50 +0000528CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCalla24dc2e2009-11-17 02:14:36 +0000529 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000530
531 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
532
John McCalld7be78a2009-11-10 07:01:13 +0000533 // Perform direct name lookup into the LookupCtx.
John McCalla24dc2e2009-11-17 02:14:36 +0000534 bool Found = LookupDirect(R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000535
John McCalld7be78a2009-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 Stump1eb44332009-09-09 15:08:12 +0000540
John McCalld7be78a2009-11-10 07:01:13 +0000541 for (; UI != UEnd; ++UI)
John McCalla24dc2e2009-11-17 02:14:36 +0000542 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000543 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000544
545 R.resolveKind();
546
547 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000548}
549
550static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000551 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000552 return Ctx->isFileContext();
553 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000554}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000555
Douglas Gregore942bbe2009-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 McCalla24dc2e2009-11-17 02:14:36 +0000565bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000566 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000567
568 DeclarationName Name = R.getLookupName();
569
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000570 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000571 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000572 I = IdResolver.begin(Name),
573 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000574
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000575 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000576 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-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 Friedman33a31382009-08-05 19:21:58 +0000580 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000581 // indirectly".
Douglas Gregor2a3009a2009-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 Gregor47b9a1c2009-02-04 17:27:36 +0000592 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000593 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000594 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000595 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000596 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000597 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000598 Found = true;
599 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000600 }
601 }
John McCallf36e02d2009-10-09 21:13:30 +0000602 if (Found) {
603 R.resolveKind();
604 return true;
605 }
606
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000607 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregore942bbe2009-09-10 16:57:35 +0000608 DeclContext *OuterCtx = findOuterContext(S);
609 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
610 Ctx = Ctx->getLookupParent()) {
Douglas Gregor12372592009-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 Gregore942bbe2009-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 Gregor7d3f5762010-01-15 01:44:47 +0000625 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000626 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000627 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000628 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000629 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000630
John McCalld7be78a2009-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 Gregor7dda67d2009-02-05 19:25:20 +0000635 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000636 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000637 //
Mike Stump390b4cc2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000640
John McCalld7be78a2009-11-10 07:01:13 +0000641 UnqualUsingDirectiveSet UDirs;
642 UDirs.visitScopeChain(Initial, S);
643 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000644
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000645 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-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 Gregor7dda67d2009-02-05 19:25:20 +0000649
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000650 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000651 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregor277d2802010-01-11 22:40:45 +0000652 if (!Ctx || Ctx->isTransparentContext())
Douglas Gregora24eb4e2009-08-24 18:55:03 +0000653 continue;
654
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000655 assert(Ctx && Ctx->isFileContext() &&
656 "We should have been looking only at file context here already.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000657
658 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000659 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000660 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000661 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000662 // We found something. Look for anything else in our scope
663 // with this same name and in an acceptable identifier
664 // namespace, so that we can construct an overload set if we
665 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000666 Found = true;
667 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000668 }
669 }
670
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000671 // Look into context considering using-directives.
John McCalla24dc2e2009-11-17 02:14:36 +0000672 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
John McCallf36e02d2009-10-09 21:13:30 +0000673 Found = true;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000674
John McCallf36e02d2009-10-09 21:13:30 +0000675 if (Found) {
676 R.resolveKind();
677 return true;
678 }
679
John McCalla24dc2e2009-11-17 02:14:36 +0000680 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000681 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000682 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000683
John McCallf36e02d2009-10-09 21:13:30 +0000684 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000685}
686
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000687/// @brief Perform unqualified name lookup starting from a given
688/// scope.
689///
690/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
691/// used to find names within the current scope. For example, 'x' in
692/// @code
693/// int x;
694/// int f() {
695/// return x; // unqualified name look finds 'x' in the global scope
696/// }
697/// @endcode
698///
699/// Different lookup criteria can find different names. For example, a
700/// particular scope can have both a struct and a function of the same
701/// name, and each can be found by certain lookup criteria. For more
702/// information about lookup criteria, see the documentation for the
703/// class LookupCriteria.
704///
705/// @param S The scope from which unqualified name lookup will
706/// begin. If the lookup criteria permits, name lookup may also search
707/// in the parent scopes.
708///
709/// @param Name The name of the entity that we are searching for.
710///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000711/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +0000712/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +0000713/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000714///
715/// @returns The result of name lookup, which includes zero or more
716/// declarations and possibly additional information used to diagnose
717/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000718bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
719 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +0000720 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000721
John McCalla24dc2e2009-11-17 02:14:36 +0000722 LookupNameKind NameKind = R.getLookupKind();
723
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000724 if (!getLangOptions().CPlusPlus) {
725 // Unqualified name lookup in C/Objective-C is purely lexical, so
726 // search in the declarations attached to the name.
727
John McCall1d7c5282009-12-18 10:40:03 +0000728 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000729 // Find the nearest non-transparent declaration scope.
730 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000731 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000732 static_cast<DeclContext *>(S->getEntity())
733 ->isTransparentContext()))
734 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000735 }
736
John McCall1d7c5282009-12-18 10:40:03 +0000737 unsigned IDNS = R.getIdentifierNamespace();
738
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000739 // Scan up the scope chain looking for a decl that matches this
740 // identifier that is in the appropriate namespace. This search
741 // should not take long, as shadowing of names is uncommon, and
742 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000743 bool LeftStartingScope = false;
744
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000745 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +0000746 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000747 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000748 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000749 if (NameKind == LookupRedeclarationWithLinkage) {
750 // Determine whether this (or a previous) declaration is
751 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000752 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000753 LeftStartingScope = true;
754
755 // If we found something outside of our starting scope that
756 // does not have linkage, skip it.
757 if (LeftStartingScope && !((*I)->hasLinkage()))
758 continue;
759 }
760
John McCallf36e02d2009-10-09 21:13:30 +0000761 R.addDecl(*I);
762
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000763 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000764 // If this declaration has the "overloadable" attribute, we
765 // might have a set of overloaded functions.
766
767 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000768 while (!(S->getFlags() & Scope::DeclScope) ||
769 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000770 S = S->getParent();
771
772 // Find the last declaration in this scope (with the same
773 // name, naturally).
774 IdentifierResolver::iterator LastI = I;
775 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000776 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000777 break;
John McCallf36e02d2009-10-09 21:13:30 +0000778 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000779 }
Douglas Gregorf9201e02009-02-11 23:02:49 +0000780 }
781
John McCallf36e02d2009-10-09 21:13:30 +0000782 R.resolveKind();
783
784 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000785 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000786 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000787 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000788 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +0000789 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000790 }
791
792 // If we didn't find a use of this identifier, and if the identifier
793 // corresponds to a compiler builtin, create the decl object for the builtin
794 // now, injecting it into translation unit scope, and return it.
Mike Stump1eb44332009-09-09 15:08:12 +0000795 if (NameKind == LookupOrdinaryName ||
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000796 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000797 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000798 if (II && AllowBuiltinCreation) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000799 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor3e41d602009-02-13 23:20:09 +0000800 if (unsigned BuiltinID = II->getBuiltinID()) {
801 // In C++, we don't have any predefined library functions like
802 // 'malloc'. Instead, we'll just error.
Mike Stump1eb44332009-09-09 15:08:12 +0000803 if (getLangOptions().CPlusPlus &&
Douglas Gregor3e41d602009-02-13 23:20:09 +0000804 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCallf36e02d2009-10-09 21:13:30 +0000805 return false;
Douglas Gregor3e41d602009-02-13 23:20:09 +0000806
John McCallf36e02d2009-10-09 21:13:30 +0000807 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCalla24dc2e2009-11-17 02:14:36 +0000808 S, R.isForRedeclaration(),
809 R.getNameLoc());
John McCallf36e02d2009-10-09 21:13:30 +0000810 if (D) R.addDecl(D);
811 return (D != NULL);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000812 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000813 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000814 }
John McCallf36e02d2009-10-09 21:13:30 +0000815 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000816}
817
John McCall6e247262009-10-10 05:48:19 +0000818/// @brief Perform qualified name lookup in the namespaces nominated by
819/// using directives by the given context.
820///
821/// C++98 [namespace.qual]p2:
822/// Given X::m (where X is a user-declared namespace), or given ::m
823/// (where X is the global namespace), let S be the set of all
824/// declarations of m in X and in the transitive closure of all
825/// namespaces nominated by using-directives in X and its used
826/// namespaces, except that using-directives are ignored in any
827/// namespace, including X, directly containing one or more
828/// declarations of m. No namespace is searched more than once in
829/// the lookup of a name. If S is the empty set, the program is
830/// ill-formed. Otherwise, if S has exactly one member, or if the
831/// context of the reference is a using-declaration
832/// (namespace.udecl), S is the required set of declarations of
833/// m. Otherwise if the use of m is not one that allows a unique
834/// declaration to be chosen from S, the program is ill-formed.
835/// C++98 [namespace.qual]p5:
836/// During the lookup of a qualified namespace member name, if the
837/// lookup finds more than one declaration of the member, and if one
838/// declaration introduces a class name or enumeration name and the
839/// other declarations either introduce the same object, the same
840/// enumerator or a set of functions, the non-type name hides the
841/// class or enumeration name if and only if the declarations are
842/// from the same namespace; otherwise (the declarations are from
843/// different namespaces), the program is ill-formed.
John McCall7d384dd2009-11-18 07:57:50 +0000844static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +0000845 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +0000846 assert(StartDC->isFileContext() && "start context is not a file context");
847
848 DeclContext::udir_iterator I = StartDC->using_directives_begin();
849 DeclContext::udir_iterator E = StartDC->using_directives_end();
850
851 if (I == E) return false;
852
853 // We have at least added all these contexts to the queue.
854 llvm::DenseSet<DeclContext*> Visited;
855 Visited.insert(StartDC);
856
857 // We have not yet looked into these namespaces, much less added
858 // their "using-children" to the queue.
859 llvm::SmallVector<NamespaceDecl*, 8> Queue;
860
861 // We have already looked into the initial namespace; seed the queue
862 // with its using-children.
863 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +0000864 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +0000865 if (Visited.insert(ND).second)
866 Queue.push_back(ND);
867 }
868
869 // The easiest way to implement the restriction in [namespace.qual]p5
870 // is to check whether any of the individual results found a tag
871 // and, if so, to declare an ambiguity if the final result is not
872 // a tag.
873 bool FoundTag = false;
874 bool FoundNonTag = false;
875
John McCall7d384dd2009-11-18 07:57:50 +0000876 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +0000877
878 bool Found = false;
879 while (!Queue.empty()) {
880 NamespaceDecl *ND = Queue.back();
881 Queue.pop_back();
882
883 // We go through some convolutions here to avoid copying results
884 // between LookupResults.
885 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +0000886 LookupResult &DirectR = UseLocal ? LocalR : R;
John McCalla24dc2e2009-11-17 02:14:36 +0000887 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +0000888
889 if (FoundDirect) {
890 // First do any local hiding.
891 DirectR.resolveKind();
892
893 // If the local result is a tag, remember that.
894 if (DirectR.isSingleTagDecl())
895 FoundTag = true;
896 else
897 FoundNonTag = true;
898
899 // Append the local results to the total results if necessary.
900 if (UseLocal) {
901 R.addAllDecls(LocalR);
902 LocalR.clear();
903 }
904 }
905
906 // If we find names in this namespace, ignore its using directives.
907 if (FoundDirect) {
908 Found = true;
909 continue;
910 }
911
912 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
913 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
914 if (Visited.insert(Nom).second)
915 Queue.push_back(Nom);
916 }
917 }
918
919 if (Found) {
920 if (FoundTag && FoundNonTag)
921 R.setAmbiguousQualifiedTagHiding();
922 else
923 R.resolveKind();
924 }
925
926 return Found;
927}
928
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000929/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000930///
931/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
932/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000933/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000934///
935/// Different lookup criteria can find different names. For example, a
936/// particular scope can have both a struct and a function of the same
937/// name, and each can be found by certain lookup criteria. For more
938/// information about lookup criteria, see the documentation for the
939/// class LookupCriteria.
940///
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000941/// \param R captures both the lookup criteria and any lookup results found.
942///
943/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000944/// search. If the lookup criteria permits, name lookup may also search
945/// in the parent contexts or (for C++ classes) base classes.
946///
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000947/// \param InUnqualifiedLookup true if this is qualified name lookup that
948/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000949///
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000950/// \returns true if lookup succeeded, false if it failed.
951bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
952 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000953 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +0000954
John McCalla24dc2e2009-11-17 02:14:36 +0000955 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +0000956 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000958 // Make sure that the declaration context is complete.
959 assert((!isa<TagDecl>(LookupCtx) ||
960 LookupCtx->isDependentContext() ||
961 cast<TagDecl>(LookupCtx)->isDefinition() ||
962 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
963 ->isBeingDefined()) &&
964 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000966 // Perform qualified name lookup into the LookupCtx.
John McCalla24dc2e2009-11-17 02:14:36 +0000967 if (LookupDirect(R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +0000968 R.resolveKind();
969 return true;
970 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000971
John McCall6e247262009-10-10 05:48:19 +0000972 // Don't descend into implied contexts for redeclarations.
973 // C++98 [namespace.qual]p6:
974 // In a declaration for a namespace member in which the
975 // declarator-id is a qualified-id, given that the qualified-id
976 // for the namespace member has the form
977 // nested-name-specifier unqualified-id
978 // the unqualified-id shall name a member of the namespace
979 // designated by the nested-name-specifier.
980 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +0000981 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +0000982 return false;
983
John McCalla24dc2e2009-11-17 02:14:36 +0000984 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +0000985 if (LookupCtx->isFileContext())
John McCalla24dc2e2009-11-17 02:14:36 +0000986 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +0000987
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000988 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +0000989 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000990 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
991 if (!LookupRec)
John McCallf36e02d2009-10-09 21:13:30 +0000992 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000993
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000994 // If we're performing qualified name lookup into a dependent class,
995 // then we are actually looking into a current instantiation. If we have any
996 // dependent base classes, then we either have to delay lookup until
997 // template instantiation time (at which point all bases will be available)
998 // or we have to fail.
999 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1000 LookupRec->hasAnyDependentBases()) {
1001 R.setNotFoundInCurrentInstantiation();
1002 return false;
1003 }
1004
Douglas Gregor7176fff2009-01-15 00:26:24 +00001005 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001006 CXXBasePaths Paths;
1007 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001008
1009 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001010 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001011 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001012 case LookupOrdinaryName:
1013 case LookupMemberName:
1014 case LookupRedeclarationWithLinkage:
1015 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1016 break;
1017
1018 case LookupTagName:
1019 BaseCallback = &CXXRecordDecl::FindTagMember;
1020 break;
John McCall9f54ad42009-12-10 09:41:52 +00001021
1022 case LookupUsingDeclName:
1023 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001024
1025 case LookupOperatorName:
1026 case LookupNamespaceName:
1027 case LookupObjCProtocolName:
1028 case LookupObjCImplementationName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001029 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001030 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001031
1032 case LookupNestedNameSpecifierName:
1033 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1034 break;
1035 }
1036
John McCalla24dc2e2009-11-17 02:14:36 +00001037 if (!LookupRec->lookupInBases(BaseCallback,
1038 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001039 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001040
1041 // C++ [class.member.lookup]p2:
1042 // [...] If the resulting set of declarations are not all from
1043 // sub-objects of the same type, or the set has a nonstatic member
1044 // and includes members from distinct sub-objects, there is an
1045 // ambiguity and the program is ill-formed. Otherwise that set is
1046 // the result of the lookup.
1047 // FIXME: support using declarations!
1048 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001049 int SubobjectNumber = 0;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001050 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001051 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001052 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001053
1054 // Determine whether we're looking at a distinct sub-object or not.
1055 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001056 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001057 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1058 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00001059 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001060 != Context.getCanonicalType(PathElement.Base->getType())) {
1061 // We found members of the given name in two subobjects of
1062 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001063 R.setAmbiguousBaseSubobjectTypes(Paths);
1064 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001065 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1066 // We have a different subobject of the same type.
1067
1068 // C++ [class.member.lookup]p5:
1069 // A static member, a nested type or an enumerator defined in
1070 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001071 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001072 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001073 if (isa<VarDecl>(FirstDecl) ||
1074 isa<TypeDecl>(FirstDecl) ||
1075 isa<EnumConstantDecl>(FirstDecl))
1076 continue;
1077
1078 if (isa<CXXMethodDecl>(FirstDecl)) {
1079 // Determine whether all of the methods are static.
1080 bool AllMethodsAreStatic = true;
1081 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1082 Func != Path->Decls.second; ++Func) {
1083 if (!isa<CXXMethodDecl>(*Func)) {
1084 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1085 break;
1086 }
1087
1088 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1089 AllMethodsAreStatic = false;
1090 break;
1091 }
1092 }
1093
1094 if (AllMethodsAreStatic)
1095 continue;
1096 }
1097
1098 // We have found a nonstatic member name in multiple, distinct
1099 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001100 R.setAmbiguousBaseSubobjects(Paths);
1101 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001102 }
1103 }
1104
1105 // Lookup in a base class succeeded; return these results.
1106
John McCallf36e02d2009-10-09 21:13:30 +00001107 DeclContext::lookup_iterator I, E;
1108 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I)
1109 R.addDecl(*I);
1110 R.resolveKind();
1111 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001112}
1113
1114/// @brief Performs name lookup for a name that was parsed in the
1115/// source code, and may contain a C++ scope specifier.
1116///
1117/// This routine is a convenience routine meant to be called from
1118/// contexts that receive a name and an optional C++ scope specifier
1119/// (e.g., "N::M::x"). It will then perform either qualified or
1120/// unqualified name lookup (with LookupQualifiedName or LookupName,
1121/// respectively) on the given name and return those results.
1122///
1123/// @param S The scope from which unqualified name lookup will
1124/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001125///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001126/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001127///
1128/// @param Name The name of the entity that name lookup will
1129/// search for.
1130///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001131/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001132/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001133/// C library functions (like "malloc") are implicitly declared.
1134///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001135/// @param EnteringContext Indicates whether we are going to enter the
1136/// context of the scope-specifier SS (if present).
1137///
John McCallf36e02d2009-10-09 21:13:30 +00001138/// @returns True if any decls were found (but possibly ambiguous)
1139bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001140 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001141 if (SS && SS->isInvalid()) {
1142 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001143 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001144 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001145 }
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Douglas Gregor495c35d2009-08-25 22:51:20 +00001147 if (SS && SS->isSet()) {
1148 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001149 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001150 // contex, and will perform name lookup in that context.
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001151 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCallf36e02d2009-10-09 21:13:30 +00001152 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001153
John McCalla24dc2e2009-11-17 02:14:36 +00001154 R.setContextRange(SS->getRange());
1155
1156 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001157 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001158
Douglas Gregor495c35d2009-08-25 22:51:20 +00001159 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001160 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001161 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001162 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001163 }
1164
Mike Stump1eb44332009-09-09 15:08:12 +00001165 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001166 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001167}
1168
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001169
Douglas Gregor7176fff2009-01-15 00:26:24 +00001170/// @brief Produce a diagnostic describing the ambiguity that resulted
1171/// from name lookup.
1172///
1173/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001174///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001175/// @param Name The name of the entity that name lookup was
1176/// searching for.
1177///
1178/// @param NameLoc The location of the name within the source code.
1179///
1180/// @param LookupRange A source range that provides more
1181/// source-location information concerning the lookup itself. For
1182/// example, this range might highlight a nested-name-specifier that
1183/// precedes the name.
1184///
1185/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001186bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001187 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1188
John McCalla24dc2e2009-11-17 02:14:36 +00001189 DeclarationName Name = Result.getLookupName();
1190 SourceLocation NameLoc = Result.getNameLoc();
1191 SourceRange LookupRange = Result.getContextRange();
1192
John McCall6e247262009-10-10 05:48:19 +00001193 switch (Result.getAmbiguityKind()) {
1194 case LookupResult::AmbiguousBaseSubobjects: {
1195 CXXBasePaths *Paths = Result.getBasePaths();
1196 QualType SubobjectType = Paths->front().back().Base->getType();
1197 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1198 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1199 << LookupRange;
1200
1201 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1202 while (isa<CXXMethodDecl>(*Found) &&
1203 cast<CXXMethodDecl>(*Found)->isStatic())
1204 ++Found;
1205
1206 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1207
1208 return true;
1209 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001210
John McCall6e247262009-10-10 05:48:19 +00001211 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001212 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1213 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001214
1215 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001216 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001217 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1218 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001219 Path != PathEnd; ++Path) {
1220 Decl *D = *Path->Decls.first;
1221 if (DeclsPrinted.insert(D).second)
1222 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1223 }
1224
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001225 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001226 }
1227
John McCall6e247262009-10-10 05:48:19 +00001228 case LookupResult::AmbiguousTagHiding: {
1229 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001230
John McCall6e247262009-10-10 05:48:19 +00001231 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1232
1233 LookupResult::iterator DI, DE = Result.end();
1234 for (DI = Result.begin(); DI != DE; ++DI)
1235 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1236 TagDecls.insert(TD);
1237 Diag(TD->getLocation(), diag::note_hidden_tag);
1238 }
1239
1240 for (DI = Result.begin(); DI != DE; ++DI)
1241 if (!isa<TagDecl>(*DI))
1242 Diag((*DI)->getLocation(), diag::note_hiding_object);
1243
1244 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001245 LookupResult::Filter F = Result.makeFilter();
1246 while (F.hasNext()) {
1247 if (TagDecls.count(F.next()))
1248 F.erase();
1249 }
1250 F.done();
John McCall6e247262009-10-10 05:48:19 +00001251
1252 return true;
1253 }
1254
1255 case LookupResult::AmbiguousReference: {
1256 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001257
John McCall6e247262009-10-10 05:48:19 +00001258 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1259 for (; DI != DE; ++DI)
1260 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001261
John McCall6e247262009-10-10 05:48:19 +00001262 return true;
1263 }
1264 }
1265
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001266 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001267 return true;
1268}
Douglas Gregorfa047642009-02-04 00:32:51 +00001269
Mike Stump1eb44332009-09-09 15:08:12 +00001270static void
1271addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001272 ASTContext &Context,
1273 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001274 Sema::AssociatedClassSet &AssociatedClasses);
1275
1276static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1277 DeclContext *Ctx) {
1278 if (Ctx->isFileContext())
1279 Namespaces.insert(Ctx);
1280}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001281
Mike Stump1eb44332009-09-09 15:08:12 +00001282// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001283// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001284static void
1285addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001286 ASTContext &Context,
1287 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001288 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001289 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001290 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001291 switch (Arg.getKind()) {
1292 case TemplateArgument::Null:
1293 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Douglas Gregor69be8d62009-07-08 07:51:57 +00001295 case TemplateArgument::Type:
1296 // [...] the namespaces and classes associated with the types of the
1297 // template arguments provided for template type parameters (excluding
1298 // template template parameters)
1299 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1300 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001301 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001302 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Douglas Gregor788cd062009-11-11 01:00:40 +00001304 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001305 // [...] the namespaces in which any template template arguments are
1306 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001307 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001308 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001309 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001310 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001311 DeclContext *Ctx = ClassTemplate->getDeclContext();
1312 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1313 AssociatedClasses.insert(EnclosingClass);
1314 // Add the associated namespace for this class.
1315 while (Ctx->isRecord())
1316 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001317 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001318 }
1319 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001320 }
1321
1322 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001323 case TemplateArgument::Integral:
1324 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001325 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001326 // associated namespaces. ]
1327 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Douglas Gregor69be8d62009-07-08 07:51:57 +00001329 case TemplateArgument::Pack:
1330 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1331 PEnd = Arg.pack_end();
1332 P != PEnd; ++P)
1333 addAssociatedClassesAndNamespaces(*P, Context,
1334 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001335 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001336 break;
1337 }
1338}
1339
Douglas Gregorfa047642009-02-04 00:32:51 +00001340// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001341// argument-dependent lookup with an argument of class type
1342// (C++ [basic.lookup.koenig]p2).
1343static void
1344addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregorfa047642009-02-04 00:32:51 +00001345 ASTContext &Context,
1346 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001347 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001348 // C++ [basic.lookup.koenig]p2:
1349 // [...]
1350 // -- If T is a class type (including unions), its associated
1351 // classes are: the class itself; the class of which it is a
1352 // member, if any; and its direct and indirect base
1353 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001354 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001355
1356 // Add the class of which it is a member, if any.
1357 DeclContext *Ctx = Class->getDeclContext();
1358 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1359 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001360 // Add the associated namespace for this class.
1361 while (Ctx->isRecord())
1362 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001363 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Douglas Gregorfa047642009-02-04 00:32:51 +00001365 // Add the class itself. If we've already seen this class, we don't
1366 // need to visit base classes.
1367 if (!AssociatedClasses.insert(Class))
1368 return;
1369
Mike Stump1eb44332009-09-09 15:08:12 +00001370 // -- If T is a template-id, its associated namespaces and classes are
1371 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001372 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001373 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001374 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001375 // namespaces in which any template template arguments are defined; and
1376 // the classes in which any member templates used as template template
1377 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001378 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001379 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001380 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1381 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1382 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1383 AssociatedClasses.insert(EnclosingClass);
1384 // Add the associated namespace for this class.
1385 while (Ctx->isRecord())
1386 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001387 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Douglas Gregor69be8d62009-07-08 07:51:57 +00001389 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1390 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1391 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1392 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001393 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001394 }
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Douglas Gregorfa047642009-02-04 00:32:51 +00001396 // Add direct and indirect base classes along with their associated
1397 // namespaces.
1398 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1399 Bases.push_back(Class);
1400 while (!Bases.empty()) {
1401 // Pop this class off the stack.
1402 Class = Bases.back();
1403 Bases.pop_back();
1404
1405 // Visit the base classes.
1406 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1407 BaseEnd = Class->bases_end();
1408 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001409 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001410 // In dependent contexts, we do ADL twice, and the first time around,
1411 // the base type might be a dependent TemplateSpecializationType, or a
1412 // TemplateTypeParmType. If that happens, simply ignore it.
1413 // FIXME: If we want to support export, we probably need to add the
1414 // namespace of the template in a TemplateSpecializationType, or even
1415 // the classes and namespaces of known non-dependent arguments.
1416 if (!BaseType)
1417 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001418 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1419 if (AssociatedClasses.insert(BaseDecl)) {
1420 // Find the associated namespace for this base class.
1421 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1422 while (BaseCtx->isRecord())
1423 BaseCtx = BaseCtx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001424 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001425
1426 // Make sure we visit the bases of this base class.
1427 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1428 Bases.push_back(BaseDecl);
1429 }
1430 }
1431 }
1432}
1433
1434// \brief Add the associated classes and namespaces for
1435// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001436// (C++ [basic.lookup.koenig]p2).
1437static void
1438addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregorfa047642009-02-04 00:32:51 +00001439 ASTContext &Context,
1440 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001441 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001442 // C++ [basic.lookup.koenig]p2:
1443 //
1444 // For each argument type T in the function call, there is a set
1445 // of zero or more associated namespaces and a set of zero or more
1446 // associated classes to be considered. The sets of namespaces and
1447 // classes is determined entirely by the types of the function
1448 // arguments (and the namespace of any template template
1449 // argument). Typedef names and using-declarations used to specify
1450 // the types do not contribute to this set. The sets of namespaces
1451 // and classes are determined in the following way:
1452 T = Context.getCanonicalType(T).getUnqualifiedType();
1453
1454 // -- If T is a pointer to U or an array of U, its associated
Mike Stump1eb44332009-09-09 15:08:12 +00001455 // namespaces and classes are those associated with U.
Douglas Gregorfa047642009-02-04 00:32:51 +00001456 //
1457 // We handle this by unwrapping pointer and array types immediately,
1458 // to avoid unnecessary recursion.
1459 while (true) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001460 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001461 T = Ptr->getPointeeType();
1462 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1463 T = Ptr->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001464 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001465 break;
1466 }
1467
1468 // -- If T is a fundamental type, its associated sets of
1469 // namespaces and classes are both empty.
John McCall183700f2009-09-21 23:43:11 +00001470 if (T->getAs<BuiltinType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001471 return;
1472
1473 // -- If T is a class type (including unions), its associated
1474 // classes are: the class itself; the class of which it is a
1475 // member, if any; and its direct and indirect base
1476 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001477 // which its associated classes are defined.
Ted Kremenek6217b802009-07-29 21:53:49 +00001478 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001479 if (CXXRecordDecl *ClassDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001480 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001481 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1482 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001483 AssociatedClasses);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001484 return;
1485 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001486
1487 // -- If T is an enumeration type, its associated namespace is
1488 // the namespace in which it is defined. If it is class
1489 // member, its associated class is the member’s class; else
Mike Stump1eb44332009-09-09 15:08:12 +00001490 // it has no associated class.
John McCall183700f2009-09-21 23:43:11 +00001491 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001492 EnumDecl *Enum = EnumT->getDecl();
1493
1494 DeclContext *Ctx = Enum->getDeclContext();
1495 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1496 AssociatedClasses.insert(EnclosingClass);
1497
1498 // Add the associated namespace for this class.
1499 while (Ctx->isRecord())
1500 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001501 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001502
1503 return;
1504 }
1505
1506 // -- If T is a function type, its associated namespaces and
1507 // classes are those associated with the function parameter
1508 // types and those associated with the return type.
John McCall183700f2009-09-21 23:43:11 +00001509 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001510 // Return type
John McCall183700f2009-09-21 23:43:11 +00001511 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001512 Context,
John McCall6ff07852009-08-07 22:18:02 +00001513 AssociatedNamespaces, AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001514
John McCall183700f2009-09-21 23:43:11 +00001515 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001516 if (!Proto)
1517 return;
1518
1519 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001520 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001521 ArgEnd = Proto->arg_type_end();
Douglas Gregorfa047642009-02-04 00:32:51 +00001522 Arg != ArgEnd; ++Arg)
1523 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCall6ff07852009-08-07 22:18:02 +00001524 AssociatedNamespaces, AssociatedClasses);
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Douglas Gregorfa047642009-02-04 00:32:51 +00001526 return;
1527 }
1528
1529 // -- If T is a pointer to a member function of a class X, its
1530 // associated namespaces and classes are those associated
1531 // with the function parameter types and return type,
Mike Stump1eb44332009-09-09 15:08:12 +00001532 // together with those associated with X.
Douglas Gregorfa047642009-02-04 00:32:51 +00001533 //
1534 // -- If T is a pointer to a data member of class X, its
1535 // associated namespaces and classes are those associated
1536 // with the member type together with those associated with
Mike Stump1eb44332009-09-09 15:08:12 +00001537 // X.
Ted Kremenek6217b802009-07-29 21:53:49 +00001538 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001539 // Handle the type that the pointer to member points to.
1540 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1541 Context,
John McCall6ff07852009-08-07 22:18:02 +00001542 AssociatedNamespaces,
1543 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001544
1545 // Handle the class type into which this points.
Ted Kremenek6217b802009-07-29 21:53:49 +00001546 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001547 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1548 Context,
John McCall6ff07852009-08-07 22:18:02 +00001549 AssociatedNamespaces,
1550 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001551
1552 return;
1553 }
1554
1555 // FIXME: What about block pointers?
1556 // FIXME: What about Objective-C message sends?
1557}
1558
1559/// \brief Find the associated classes and namespaces for
1560/// argument-dependent lookup for a call with the given set of
1561/// arguments.
1562///
1563/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001564/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001565/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001566void
Douglas Gregorfa047642009-02-04 00:32:51 +00001567Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1568 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001569 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001570 AssociatedNamespaces.clear();
1571 AssociatedClasses.clear();
1572
1573 // C++ [basic.lookup.koenig]p2:
1574 // For each argument type T in the function call, there is a set
1575 // of zero or more associated namespaces and a set of zero or more
1576 // associated classes to be considered. The sets of namespaces and
1577 // classes is determined entirely by the types of the function
1578 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001579 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001580 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1581 Expr *Arg = Args[ArgIdx];
1582
1583 if (Arg->getType() != Context.OverloadTy) {
1584 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001585 AssociatedNamespaces,
1586 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001587 continue;
1588 }
1589
1590 // [...] In addition, if the argument is the name or address of a
1591 // set of overloaded functions and/or function templates, its
1592 // associated classes and namespaces are the union of those
1593 // associated with each of the members of the set: the namespace
1594 // in which the function or function template is defined and the
1595 // classes and namespaces associated with its (non-dependent)
1596 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001597 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001598 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1599 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1600 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001601
John McCallba135432009-11-21 08:51:07 +00001602 // TODO: avoid the copies. This should be easy when the cases
1603 // share a storage implementation.
1604 llvm::SmallVector<NamedDecl*, 8> Functions;
1605
1606 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1607 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00001608 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001609 continue;
1610
John McCallba135432009-11-21 08:51:07 +00001611 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1612 E = Functions.end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001613 // Look through any using declarations to find the underlying function.
1614 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001615
Chandler Carruthbd647292009-12-29 06:17:27 +00001616 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1617 if (!FDecl)
1618 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001619
1620 // Add the classes and namespaces associated with the parameter
1621 // types and return type of this function.
1622 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001623 AssociatedNamespaces,
1624 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001625 }
1626 }
1627}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001628
1629/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1630/// an acceptable non-member overloaded operator for a call whose
1631/// arguments have types T1 (and, if non-empty, T2). This routine
1632/// implements the check in C++ [over.match.oper]p3b2 concerning
1633/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001634static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001635IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1636 QualType T1, QualType T2,
1637 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001638 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1639 return true;
1640
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001641 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1642 return true;
1643
John McCall183700f2009-09-21 23:43:11 +00001644 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001645 if (Proto->getNumArgs() < 1)
1646 return false;
1647
1648 if (T1->isEnumeralType()) {
1649 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001650 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001651 return true;
1652 }
1653
1654 if (Proto->getNumArgs() < 2)
1655 return false;
1656
1657 if (!T2.isNull() && T2->isEnumeralType()) {
1658 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001659 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001660 return true;
1661 }
1662
1663 return false;
1664}
1665
John McCall7d384dd2009-11-18 07:57:50 +00001666NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1667 LookupNameKind NameKind,
1668 RedeclarationKind Redecl) {
1669 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1670 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00001671 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00001672}
1673
Douglas Gregor6e378de2009-04-23 23:18:26 +00001674/// \brief Find the protocol with the given name, if any.
1675ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCallf36e02d2009-10-09 21:13:30 +00001676 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001677 return cast_or_null<ObjCProtocolDecl>(D);
1678}
1679
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001680void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001681 QualType T1, QualType T2,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001682 FunctionSet &Functions) {
1683 // C++ [over.match.oper]p3:
1684 // -- The set of non-member candidates is the result of the
1685 // unqualified lookup of operator@ in the context of the
1686 // expression according to the usual rules for name lookup in
1687 // unqualified function calls (3.4.2) except that all member
1688 // functions are ignored. However, if no operand has a class
1689 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00001690 // that have a first parameter of type T1 or "reference to
1691 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001692 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00001693 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001694 // when T2 is an enumeration type, are candidate functions.
1695 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00001696 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1697 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001699 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1700
John McCallf36e02d2009-10-09 21:13:30 +00001701 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001702 return;
1703
1704 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1705 Op != OpEnd; ++Op) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001706 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001707 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1708 Functions.insert(FD); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00001709 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor364e0212009-06-27 21:05:07 +00001710 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1711 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00001712 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00001713 // later?
1714 if (!FunTmpl->getDeclContext()->isRecord())
1715 Functions.insert(FunTmpl);
1716 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001717 }
1718}
1719
John McCall6ff07852009-08-07 22:18:02 +00001720static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1721 Decl *D) {
1722 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1723 Functions.insert(Func);
1724 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1725 Functions.insert(FunTmpl);
1726}
1727
Sebastian Redl644be852009-10-23 19:23:15 +00001728void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001729 Expr **Args, unsigned NumArgs,
1730 FunctionSet &Functions) {
1731 // Find all of the associated namespaces and classes based on the
1732 // arguments we have.
1733 AssociatedNamespaceSet AssociatedNamespaces;
1734 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00001735 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00001736 AssociatedNamespaces,
1737 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001738
Sebastian Redl644be852009-10-23 19:23:15 +00001739 QualType T1, T2;
1740 if (Operator) {
1741 T1 = Args[0]->getType();
1742 if (NumArgs >= 2)
1743 T2 = Args[1]->getType();
1744 }
1745
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001746 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001747 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1748 // and let Y be the lookup set produced by argument dependent
1749 // lookup (defined as follows). If X contains [...] then Y is
1750 // empty. Otherwise Y is the set of declarations found in the
1751 // namespaces associated with the argument types as described
1752 // below. The set of declarations found by the lookup of the name
1753 // is the union of X and Y.
1754 //
1755 // Here, we compute Y and add its members to the overloaded
1756 // candidate set.
1757 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001758 NSEnd = AssociatedNamespaces.end();
1759 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001760 // When considering an associated namespace, the lookup is the
1761 // same as the lookup performed when the associated namespace is
1762 // used as a qualifier (3.4.3.2) except that:
1763 //
1764 // -- Any using-directives in the associated namespace are
1765 // ignored.
1766 //
John McCall6ff07852009-08-07 22:18:02 +00001767 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001768 // associated classes are visible within their respective
1769 // namespaces even if they are not visible during an ordinary
1770 // lookup (11.4).
1771 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00001772 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6ff07852009-08-07 22:18:02 +00001773 Decl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00001774 // If the only declaration here is an ordinary friend, consider
1775 // it only if it was declared in an associated classes.
1776 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00001777 DeclContext *LexDC = D->getLexicalDeclContext();
1778 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1779 continue;
1780 }
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Sebastian Redl644be852009-10-23 19:23:15 +00001782 FunctionDecl *Fn;
1783 if (!Operator || !(Fn = dyn_cast<FunctionDecl>(D)) ||
1784 IsAcceptableNonMemberOperatorCandidate(Fn, T1, T2, Context))
1785 CollectFunctionDecl(Functions, D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001786 }
1787 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001788}
Douglas Gregor546be3c2009-12-30 17:04:44 +00001789
1790//----------------------------------------------------------------------------
1791// Search for all visible declarations.
1792//----------------------------------------------------------------------------
1793VisibleDeclConsumer::~VisibleDeclConsumer() { }
1794
1795namespace {
1796
1797class ShadowContextRAII;
1798
1799class VisibleDeclsRecord {
1800public:
1801 /// \brief An entry in the shadow map, which is optimized to store a
1802 /// single declaration (the common case) but can also store a list
1803 /// of declarations.
1804 class ShadowMapEntry {
1805 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1806
1807 /// \brief Contains either the solitary NamedDecl * or a vector
1808 /// of declarations.
1809 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1810
1811 public:
1812 ShadowMapEntry() : DeclOrVector() { }
1813
1814 void Add(NamedDecl *ND);
1815 void Destroy();
1816
1817 // Iteration.
1818 typedef NamedDecl **iterator;
1819 iterator begin();
1820 iterator end();
1821 };
1822
1823private:
1824 /// \brief A mapping from declaration names to the declarations that have
1825 /// this name within a particular scope.
1826 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
1827
1828 /// \brief A list of shadow maps, which is used to model name hiding.
1829 std::list<ShadowMap> ShadowMaps;
1830
1831 /// \brief The declaration contexts we have already visited.
1832 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
1833
1834 friend class ShadowContextRAII;
1835
1836public:
1837 /// \brief Determine whether we have already visited this context
1838 /// (and, if not, note that we are going to visit that context now).
1839 bool visitedContext(DeclContext *Ctx) {
1840 return !VisitedContexts.insert(Ctx);
1841 }
1842
1843 /// \brief Determine whether the given declaration is hidden in the
1844 /// current scope.
1845 ///
1846 /// \returns the declaration that hides the given declaration, or
1847 /// NULL if no such declaration exists.
1848 NamedDecl *checkHidden(NamedDecl *ND);
1849
1850 /// \brief Add a declaration to the current shadow map.
1851 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
1852};
1853
1854/// \brief RAII object that records when we've entered a shadow context.
1855class ShadowContextRAII {
1856 VisibleDeclsRecord &Visible;
1857
1858 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
1859
1860public:
1861 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
1862 Visible.ShadowMaps.push_back(ShadowMap());
1863 }
1864
1865 ~ShadowContextRAII() {
1866 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
1867 EEnd = Visible.ShadowMaps.back().end();
1868 E != EEnd;
1869 ++E)
1870 E->second.Destroy();
1871
1872 Visible.ShadowMaps.pop_back();
1873 }
1874};
1875
1876} // end anonymous namespace
1877
1878void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
1879 if (DeclOrVector.isNull()) {
1880 // 0 - > 1 elements: just set the single element information.
1881 DeclOrVector = ND;
1882 return;
1883 }
1884
1885 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
1886 // 1 -> 2 elements: create the vector of results and push in the
1887 // existing declaration.
1888 DeclVector *Vec = new DeclVector;
1889 Vec->push_back(PrevND);
1890 DeclOrVector = Vec;
1891 }
1892
1893 // Add the new element to the end of the vector.
1894 DeclOrVector.get<DeclVector*>()->push_back(ND);
1895}
1896
1897void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
1898 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
1899 delete Vec;
1900 DeclOrVector = ((NamedDecl *)0);
1901 }
1902}
1903
1904VisibleDeclsRecord::ShadowMapEntry::iterator
1905VisibleDeclsRecord::ShadowMapEntry::begin() {
1906 if (DeclOrVector.isNull())
1907 return 0;
1908
1909 if (DeclOrVector.dyn_cast<NamedDecl *>())
1910 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
1911
1912 return DeclOrVector.get<DeclVector *>()->begin();
1913}
1914
1915VisibleDeclsRecord::ShadowMapEntry::iterator
1916VisibleDeclsRecord::ShadowMapEntry::end() {
1917 if (DeclOrVector.isNull())
1918 return 0;
1919
1920 if (DeclOrVector.dyn_cast<NamedDecl *>())
1921 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
1922
1923 return DeclOrVector.get<DeclVector *>()->end();
1924}
1925
1926NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00001927 // Look through using declarations.
1928 ND = ND->getUnderlyingDecl();
1929
Douglas Gregor546be3c2009-12-30 17:04:44 +00001930 unsigned IDNS = ND->getIdentifierNamespace();
1931 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
1932 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
1933 SM != SMEnd; ++SM) {
1934 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
1935 if (Pos == SM->end())
1936 continue;
1937
1938 for (ShadowMapEntry::iterator I = Pos->second.begin(),
1939 IEnd = Pos->second.end();
1940 I != IEnd; ++I) {
1941 // A tag declaration does not hide a non-tag declaration.
1942 if ((*I)->getIdentifierNamespace() == Decl::IDNS_Tag &&
1943 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
1944 Decl::IDNS_ObjCProtocol)))
1945 continue;
1946
1947 // Protocols are in distinct namespaces from everything else.
1948 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
1949 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
1950 (*I)->getIdentifierNamespace() != IDNS)
1951 continue;
1952
Douglas Gregor0cc84042010-01-14 15:47:35 +00001953 // Functions and function templates in the same scope overload
1954 // rather than hide. FIXME: Look for hiding based on function
1955 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00001956 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00001957 ND->isFunctionOrFunctionTemplate() &&
1958 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00001959 continue;
1960
Douglas Gregor546be3c2009-12-30 17:04:44 +00001961 // We've found a declaration that hides this one.
1962 return *I;
1963 }
1964 }
1965
1966 return 0;
1967}
1968
1969static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
1970 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00001971 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00001972 VisibleDeclConsumer &Consumer,
1973 VisibleDeclsRecord &Visited) {
1974 // Make sure we don't visit the same context twice.
1975 if (Visited.visitedContext(Ctx->getPrimaryContext()))
1976 return;
1977
1978 // Enumerate all of the results in this context.
1979 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
1980 CurCtx = CurCtx->getNextContext()) {
1981 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
1982 DEnd = CurCtx->decls_end();
1983 D != DEnd; ++D) {
1984 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
1985 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00001986 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00001987 Visited.add(ND);
1988 }
1989
1990 // Visit transparent contexts inside this context.
1991 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
1992 if (InnerCtx->isTransparentContext())
Douglas Gregor0cc84042010-01-14 15:47:35 +00001993 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00001994 Consumer, Visited);
1995 }
1996 }
1997 }
1998
1999 // Traverse using directives for qualified name lookup.
2000 if (QualifiedNameLookup) {
2001 ShadowContextRAII Shadow(Visited);
2002 DeclContext::udir_iterator I, E;
2003 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2004 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002005 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002006 }
2007 }
2008
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002009 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002010 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
2011 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2012 BEnd = Record->bases_end();
2013 B != BEnd; ++B) {
2014 QualType BaseType = B->getType();
2015
2016 // Don't look into dependent bases, because name lookup can't look
2017 // there anyway.
2018 if (BaseType->isDependentType())
2019 continue;
2020
2021 const RecordType *Record = BaseType->getAs<RecordType>();
2022 if (!Record)
2023 continue;
2024
2025 // FIXME: It would be nice to be able to determine whether referencing
2026 // a particular member would be ambiguous. For example, given
2027 //
2028 // struct A { int member; };
2029 // struct B { int member; };
2030 // struct C : A, B { };
2031 //
2032 // void f(C *c) { c->### }
2033 //
2034 // accessing 'member' would result in an ambiguity. However, we
2035 // could be smart enough to qualify the member with the base
2036 // class, e.g.,
2037 //
2038 // c->B::member
2039 //
2040 // or
2041 //
2042 // c->A::member
2043
2044 // Find results in this base class (and its bases).
2045 ShadowContextRAII Shadow(Visited);
2046 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002047 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002048 }
2049 }
2050
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002051 // Traverse the contexts of Objective-C classes.
2052 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2053 // Traverse categories.
2054 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2055 Category; Category = Category->getNextClassCategory()) {
2056 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002057 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2058 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002059 }
2060
2061 // Traverse protocols.
2062 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2063 E = IFace->protocol_end(); I != E; ++I) {
2064 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002065 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2066 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002067 }
2068
2069 // Traverse the superclass.
2070 if (IFace->getSuperClass()) {
2071 ShadowContextRAII Shadow(Visited);
2072 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002073 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002074 }
2075 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2076 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2077 E = Protocol->protocol_end(); I != E; ++I) {
2078 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002079 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2080 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002081 }
2082 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2083 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2084 E = Category->protocol_end(); I != E; ++I) {
2085 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002086 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2087 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002088 }
2089 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002090}
2091
2092static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2093 UnqualUsingDirectiveSet &UDirs,
2094 VisibleDeclConsumer &Consumer,
2095 VisibleDeclsRecord &Visited) {
2096 if (!S)
2097 return;
2098
Douglas Gregor539c5c32010-01-07 00:31:29 +00002099 if (!S->getEntity() || !S->getParent() ||
2100 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2101 // Walk through the declarations in this Scope.
2102 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2103 D != DEnd; ++D) {
2104 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2105 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002106 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002107 Visited.add(ND);
2108 }
2109 }
2110 }
2111
Douglas Gregor546be3c2009-12-30 17:04:44 +00002112 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002113 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002114 // Look into this scope's declaration context, along with any of its
2115 // parent lookup contexts (e.g., enclosing classes), up to the point
2116 // where we hit the context stored in the next outer scope.
2117 Entity = (DeclContext *)S->getEntity();
2118 DeclContext *OuterCtx = findOuterContext(S);
2119
2120 for (DeclContext *Ctx = Entity; Ctx && Ctx->getPrimaryContext() != OuterCtx;
2121 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002122 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2123 if (Method->isInstanceMethod()) {
2124 // For instance methods, look for ivars in the method's interface.
2125 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2126 Result.getNameLoc(), Sema::LookupMemberName);
2127 ObjCInterfaceDecl *IFace = Method->getClassInterface();
2128 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002129 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002130 }
2131
2132 // We've already performed all of the name lookup that we need
2133 // to for Objective-C methods; the next context will be the
2134 // outer scope.
2135 break;
2136 }
2137
Douglas Gregor546be3c2009-12-30 17:04:44 +00002138 if (Ctx->isFunctionOrMethod())
2139 continue;
2140
2141 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002142 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002143 }
2144 } else if (!S->getParent()) {
2145 // Look into the translation unit scope. We walk through the translation
2146 // unit's declaration context, because the Scope itself won't have all of
2147 // the declarations if we loaded a precompiled header.
2148 // FIXME: We would like the translation unit's Scope object to point to the
2149 // translation unit, so we don't need this special "if" branch. However,
2150 // doing so would force the normal C++ name-lookup code to look into the
2151 // translation unit decl when the IdentifierInfo chains would suffice.
2152 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002153 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002154 Entity = Result.getSema().Context.getTranslationUnitDecl();
2155 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002156 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002157 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002158
2159 if (Entity) {
2160 // Lookup visible declarations in any namespaces found by using
2161 // directives.
2162 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2163 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2164 for (; UI != UEnd; ++UI)
2165 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002166 Result, /*QualifiedNameLookup=*/false,
2167 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002168 }
2169
2170 // Lookup names in the parent scope.
2171 ShadowContextRAII Shadow(Visited);
2172 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2173}
2174
2175void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2176 VisibleDeclConsumer &Consumer) {
2177 // Determine the set of using directives available during
2178 // unqualified name lookup.
2179 Scope *Initial = S;
2180 UnqualUsingDirectiveSet UDirs;
2181 if (getLangOptions().CPlusPlus) {
2182 // Find the first namespace or translation-unit scope.
2183 while (S && !isNamespaceOrTranslationUnitScope(S))
2184 S = S->getParent();
2185
2186 UDirs.visitScopeChain(Initial, S);
2187 }
2188 UDirs.done();
2189
2190 // Look for visible declarations.
2191 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2192 VisibleDeclsRecord Visited;
2193 ShadowContextRAII Shadow(Visited);
2194 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2195}
2196
2197void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2198 VisibleDeclConsumer &Consumer) {
2199 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2200 VisibleDeclsRecord Visited;
2201 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002202 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2203 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002204}
2205
2206//----------------------------------------------------------------------------
2207// Typo correction
2208//----------------------------------------------------------------------------
2209
2210namespace {
2211class TypoCorrectionConsumer : public VisibleDeclConsumer {
2212 /// \brief The name written that is a typo in the source.
2213 llvm::StringRef Typo;
2214
2215 /// \brief The results found that have the smallest edit distance
2216 /// found (so far) with the typo name.
2217 llvm::SmallVector<NamedDecl *, 4> BestResults;
2218
2219 /// \brief The best edit distance found so far.
2220 unsigned BestEditDistance;
2221
2222public:
2223 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2224 : Typo(Typo->getName()) { }
2225
Douglas Gregor0cc84042010-01-14 15:47:35 +00002226 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002227
2228 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2229 iterator begin() const { return BestResults.begin(); }
2230 iterator end() const { return BestResults.end(); }
2231 bool empty() const { return BestResults.empty(); }
2232
2233 unsigned getBestEditDistance() const { return BestEditDistance; }
2234};
2235
2236}
2237
Douglas Gregor0cc84042010-01-14 15:47:35 +00002238void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2239 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002240 // Don't consider hidden names for typo correction.
2241 if (Hiding)
2242 return;
2243
2244 // Only consider entities with identifiers for names, ignoring
2245 // special names (constructors, overloaded operators, selectors,
2246 // etc.).
2247 IdentifierInfo *Name = ND->getIdentifier();
2248 if (!Name)
2249 return;
2250
2251 // Compute the edit distance between the typo and the name of this
2252 // entity. If this edit distance is not worse than the best edit
2253 // distance we've seen so far, add it to the list of results.
2254 unsigned ED = Typo.edit_distance(Name->getName());
2255 if (!BestResults.empty()) {
2256 if (ED < BestEditDistance) {
2257 // This result is better than any we've seen before; clear out
2258 // the previous results.
2259 BestResults.clear();
2260 BestEditDistance = ED;
2261 } else if (ED > BestEditDistance) {
2262 // This result is worse than the best results we've seen so far;
2263 // ignore it.
2264 return;
2265 }
2266 } else
2267 BestEditDistance = ED;
2268
2269 BestResults.push_back(ND);
2270}
2271
2272/// \brief Try to "correct" a typo in the source code by finding
2273/// visible declarations whose names are similar to the name that was
2274/// present in the source code.
2275///
2276/// \param Res the \c LookupResult structure that contains the name
2277/// that was present in the source code along with the name-lookup
2278/// criteria used to search for the name. On success, this structure
2279/// will contain the results of name lookup.
2280///
2281/// \param S the scope in which name lookup occurs.
2282///
2283/// \param SS the nested-name-specifier that precedes the name we're
2284/// looking for, if present.
2285///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002286/// \param MemberContext if non-NULL, the context in which to look for
2287/// a member access expression.
2288///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002289/// \param EnteringContext whether we're entering the context described by
2290/// the nested-name-specifier SS.
2291///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002292/// \param OPT when non-NULL, the search for visible declarations will
2293/// also walk the protocols in the qualified interfaces of \p OPT.
2294///
Douglas Gregor546be3c2009-12-30 17:04:44 +00002295/// \returns true if the typo was corrected, in which case the \p Res
2296/// structure will contain the results of name lookup for the
2297/// corrected name. Otherwise, returns false.
2298bool Sema::CorrectTypo(LookupResult &Res, Scope *S, const CXXScopeSpec *SS,
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002299 DeclContext *MemberContext, bool EnteringContext,
2300 const ObjCObjectPointerType *OPT) {
Ted Kremenek1dac3412010-01-06 00:23:04 +00002301
2302 if (Diags.hasFatalErrorOccurred())
2303 return false;
2304
Douglas Gregor546be3c2009-12-30 17:04:44 +00002305 // We only attempt to correct typos for identifiers.
2306 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2307 if (!Typo)
2308 return false;
2309
2310 // If the scope specifier itself was invalid, don't try to correct
2311 // typos.
2312 if (SS && SS->isInvalid())
2313 return false;
2314
2315 // Never try to correct typos during template deduction or
2316 // instantiation.
2317 if (!ActiveTemplateInstantiations.empty())
2318 return false;
2319
2320 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002321 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002322 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002323
2324 // Look in qualified interfaces.
2325 if (OPT) {
2326 for (ObjCObjectPointerType::qual_iterator
2327 I = OPT->qual_begin(), E = OPT->qual_end();
2328 I != E; ++I)
2329 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2330 }
2331 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002332 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2333 if (!DC)
2334 return false;
2335
2336 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2337 } else {
2338 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2339 }
2340
2341 if (Consumer.empty())
2342 return false;
2343
2344 // Only allow a single, closest name in the result set (it's okay to
2345 // have overloads of that name, though).
2346 TypoCorrectionConsumer::iterator I = Consumer.begin();
2347 DeclarationName BestName = (*I)->getDeclName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002348
2349 // If we've found an Objective-C ivar or property, don't perform
2350 // name lookup again; we'll just return the result directly.
2351 NamedDecl *FoundBest = 0;
2352 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I))
2353 FoundBest = *I;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002354 ++I;
2355 for(TypoCorrectionConsumer::iterator IEnd = Consumer.end(); I != IEnd; ++I) {
2356 if (BestName != (*I)->getDeclName())
2357 return false;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002358
2359 // FIXME: If there are both ivars and properties of the same name,
2360 // don't return both because the callee can't handle two
2361 // results. We really need to separate ivar lookup from property
2362 // lookup to avoid this problem.
2363 FoundBest = 0;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002364 }
2365
2366 // BestName is the closest viable name to what the user
2367 // typed. However, to make sure that we don't pick something that's
2368 // way off, make sure that the user typed at least 3 characters for
2369 // each correction.
2370 unsigned ED = Consumer.getBestEditDistance();
2371 if (ED == 0 || (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
2372 return false;
2373
2374 // Perform name lookup again with the name we chose, and declare
2375 // success if we found something that was not ambiguous.
2376 Res.clear();
2377 Res.setLookupName(BestName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002378
2379 // If we found an ivar or property, add that result; no further
2380 // lookup is required.
2381 if (FoundBest)
2382 Res.addDecl(FoundBest);
2383 // If we're looking into the context of a member, perform qualified
2384 // name lookup on the best name.
2385 else if (MemberContext)
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002386 LookupQualifiedName(Res, MemberContext);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002387 // Perform lookup as if we had just parsed the best name.
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002388 else
2389 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2390 EnteringContext);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002391
2392 if (Res.isAmbiguous()) {
2393 Res.suppressDiagnostics();
2394 return false;
2395 }
2396
2397 return Res.getResultKind() != LookupResult::NotFound;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002398}