blob: 8d93eed0dcf7fffbb4579af883edae6756455979 [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 McCall6b2accb2010-02-10 09:31:12 +0000407 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000408 DeclContext::lookup_iterator DI, DE;
409 for (I = P.begin(), E = P.end(); I != E; ++I)
410 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
411 addDecl(*DI);
Douglas 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
Douglas Gregor85910982010-02-12 05:48:04 +0000441/// \brief Lookup a builtin function, when name lookup would otherwise
442/// fail.
443static bool LookupBuiltin(Sema &S, LookupResult &R) {
444 Sema::LookupNameKind NameKind = R.getLookupKind();
445
446 // If we didn't find a use of this identifier, and if the identifier
447 // corresponds to a compiler builtin, create the decl object for the builtin
448 // now, injecting it into translation unit scope, and return it.
449 if (NameKind == Sema::LookupOrdinaryName ||
450 NameKind == Sema::LookupRedeclarationWithLinkage) {
451 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
452 if (II) {
453 // If this is a builtin on this (or all) targets, create the decl.
454 if (unsigned BuiltinID = II->getBuiltinID()) {
455 // In C++, we don't have any predefined library functions like
456 // 'malloc'. Instead, we'll just error.
457 if (S.getLangOptions().CPlusPlus &&
458 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
459 return false;
460
461 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
462 S.TUScope, R.isForRedeclaration(),
463 R.getNameLoc());
464 if (D)
465 R.addDecl(D);
466 return (D != NULL);
467 }
468 }
469 }
470
471 return false;
472}
473
John McCallf36e02d2009-10-09 21:13:30 +0000474// Adds all qualifying matches for a name within a decl context to the
475// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000476static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000477 bool Found = false;
478
John McCalld7be78a2009-11-10 07:01:13 +0000479 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000480 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000481 NamedDecl *D = *I;
482 if (R.isAcceptableDecl(D)) {
483 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000484 Found = true;
485 }
486 }
John McCallf36e02d2009-10-09 21:13:30 +0000487
Douglas Gregor85910982010-02-12 05:48:04 +0000488 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
489 return true;
490
Douglas Gregor48026d22010-01-11 18:40:55 +0000491 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000492 != DeclarationName::CXXConversionFunctionName ||
493 R.getLookupName().getCXXNameType()->isDependentType() ||
494 !isa<CXXRecordDecl>(DC))
495 return Found;
496
497 // C++ [temp.mem]p6:
498 // A specialization of a conversion function template is not found by
499 // name lookup. Instead, any conversion function templates visible in the
500 // context of the use are considered. [...]
501 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
502 if (!Record->isDefinition())
503 return Found;
504
505 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
506 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
507 UEnd = Unresolved->end(); U != UEnd; ++U) {
508 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
509 if (!ConvTemplate)
510 continue;
511
512 // When we're performing lookup for the purposes of redeclaration, just
513 // add the conversion function template. When we deduce template
514 // arguments for specializations, we'll end up unifying the return
515 // type of the new declaration with the type of the function template.
516 if (R.isForRedeclaration()) {
517 R.addDecl(ConvTemplate);
518 Found = true;
519 continue;
520 }
521
Douglas Gregor48026d22010-01-11 18:40:55 +0000522 // C++ [temp.mem]p6:
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000523 // [...] For each such operator, if argument deduction succeeds
524 // (14.9.2.3), the resulting specialization is used as if found by
525 // name lookup.
526 //
527 // When referencing a conversion function for any purpose other than
528 // a redeclaration (such that we'll be building an expression with the
529 // result), perform template argument deduction and place the
530 // specialization into the result set. We do this to avoid forcing all
531 // callers to perform special deduction for conversion functions.
John McCall5769d612010-02-08 23:07:23 +0000532 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000533 FunctionDecl *Specialization = 0;
534
535 const FunctionProtoType *ConvProto
536 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
537 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000538
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000539 // Compute the type of the function that we would expect the conversion
540 // function to have, if it were to match the name given.
541 // FIXME: Calling convention!
542 QualType ExpectedType
543 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
544 0, 0, ConvProto->isVariadic(),
545 ConvProto->getTypeQuals(),
546 false, false, 0, 0,
547 ConvProto->getNoReturnAttr());
548
549 // Perform template argument deduction against the type that we would
550 // expect the function to have.
551 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
552 Specialization, Info)
553 == Sema::TDK_Success) {
554 R.addDecl(Specialization);
555 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000556 }
557 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000558
John McCallf36e02d2009-10-09 21:13:30 +0000559 return Found;
560}
561
John McCalld7be78a2009-11-10 07:01:13 +0000562// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000563static bool
Douglas Gregor85910982010-02-12 05:48:04 +0000564CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
565 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000566
567 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
568
John McCalld7be78a2009-11-10 07:01:13 +0000569 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000570 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000571
John McCalld7be78a2009-11-10 07:01:13 +0000572 // Perform direct name lookup into the namespaces nominated by the
573 // using directives whose common ancestor is this namespace.
574 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
575 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000576
John McCalld7be78a2009-11-10 07:01:13 +0000577 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000578 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000579 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000580
581 R.resolveKind();
582
583 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000584}
585
586static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000587 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000588 return Ctx->isFileContext();
589 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000590}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000591
Douglas Gregore942bbe2009-09-10 16:57:35 +0000592// Find the next outer declaration context corresponding to this scope.
593static DeclContext *findOuterContext(Scope *S) {
594 for (S = S->getParent(); S; S = S->getParent())
595 if (S->getEntity())
596 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
597
598 return 0;
599}
600
John McCalla24dc2e2009-11-17 02:14:36 +0000601bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000602 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000603
604 DeclarationName Name = R.getLookupName();
605
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000606 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000607 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000608 I = IdResolver.begin(Name),
609 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000610
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000611 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000612 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000613 // ...During unqualified name lookup (3.4.1), the names appear as if
614 // they were declared in the nearest enclosing namespace which contains
615 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000616 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000617 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000618 //
619 // For example:
620 // namespace A { int i; }
621 // void foo() {
622 // int i;
623 // {
624 // using namespace A;
625 // ++i; // finds local 'i', A::i appears at global scope
626 // }
627 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000628 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000629 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000630 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000631 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000632 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000633 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000634 Found = true;
635 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000636 }
637 }
John McCallf36e02d2009-10-09 21:13:30 +0000638 if (Found) {
639 R.resolveKind();
640 return true;
641 }
642
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000643 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregore942bbe2009-09-10 16:57:35 +0000644 DeclContext *OuterCtx = findOuterContext(S);
645 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
646 Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000647 // We do not directly look into transparent contexts, since
648 // those entities will be found in the nearest enclosing
649 // non-transparent context.
650 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000651 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000652
653 // We do not look directly into function or method contexts,
654 // since all of the local variables and parameters of the
655 // function/method are present within the Scope.
656 if (Ctx->isFunctionOrMethod()) {
657 // If we have an Objective-C instance method, look for ivars
658 // in the corresponding interface.
659 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
660 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
661 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
662 ObjCInterfaceDecl *ClassDeclared;
663 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
664 Name.getAsIdentifierInfo(),
665 ClassDeclared)) {
666 if (R.isAcceptableDecl(Ivar)) {
667 R.addDecl(Ivar);
668 R.resolveKind();
669 return true;
670 }
671 }
672 }
673 }
674
675 continue;
676 }
677
Douglas Gregore942bbe2009-09-10 16:57:35 +0000678 // Perform qualified name lookup into this context.
679 // FIXME: In some cases, we know that every name that could be found by
680 // this qualified name lookup will also be on the identifier chain. For
681 // example, inside a class without any base classes, we never need to
682 // perform qualified lookup because all of the members are on top of the
683 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000684 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000685 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000686 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000687 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000688 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000689
John McCalld7be78a2009-11-10 07:01:13 +0000690 // Stop if we ran out of scopes.
691 // FIXME: This really, really shouldn't be happening.
692 if (!S) return false;
693
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000694 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000695 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000696 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000697 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
698 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000699
John McCalld7be78a2009-11-10 07:01:13 +0000700 UnqualUsingDirectiveSet UDirs;
701 UDirs.visitScopeChain(Initial, S);
702 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000703
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000704 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000705 // Unqualified name lookup in C++ requires looking into scopes
706 // that aren't strictly lexical, and therefore we walk through the
707 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000708
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000709 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000710 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000711 if (Ctx && Ctx->isTransparentContext())
Douglas Gregora24eb4e2009-08-24 18:55:03 +0000712 continue;
713
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000714 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000715 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000716 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000717 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000718 // We found something. Look for anything else in our scope
719 // with this same name and in an acceptable identifier
720 // namespace, so that we can construct an overload set if we
721 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000722 Found = true;
723 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000724 }
725 }
726
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000727 if (Ctx) {
728 assert(Ctx->isFileContext() &&
729 "We should have been looking only at file context here already.");
730
731 // Look into context considering using-directives.
Douglas Gregor85910982010-02-12 05:48:04 +0000732 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000733 Found = true;
734 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000735
John McCallf36e02d2009-10-09 21:13:30 +0000736 if (Found) {
737 R.resolveKind();
738 return true;
739 }
740
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000741 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000742 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000743 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000744
John McCallf36e02d2009-10-09 21:13:30 +0000745 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000746}
747
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000748/// @brief Perform unqualified name lookup starting from a given
749/// scope.
750///
751/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
752/// used to find names within the current scope. For example, 'x' in
753/// @code
754/// int x;
755/// int f() {
756/// return x; // unqualified name look finds 'x' in the global scope
757/// }
758/// @endcode
759///
760/// Different lookup criteria can find different names. For example, a
761/// particular scope can have both a struct and a function of the same
762/// name, and each can be found by certain lookup criteria. For more
763/// information about lookup criteria, see the documentation for the
764/// class LookupCriteria.
765///
766/// @param S The scope from which unqualified name lookup will
767/// begin. If the lookup criteria permits, name lookup may also search
768/// in the parent scopes.
769///
770/// @param Name The name of the entity that we are searching for.
771///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000772/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +0000773/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +0000774/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000775///
776/// @returns The result of name lookup, which includes zero or more
777/// declarations and possibly additional information used to diagnose
778/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000779bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
780 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +0000781 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000782
John McCalla24dc2e2009-11-17 02:14:36 +0000783 LookupNameKind NameKind = R.getLookupKind();
784
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000785 if (!getLangOptions().CPlusPlus) {
786 // Unqualified name lookup in C/Objective-C is purely lexical, so
787 // search in the declarations attached to the name.
788
John McCall1d7c5282009-12-18 10:40:03 +0000789 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000790 // Find the nearest non-transparent declaration scope.
791 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000792 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000793 static_cast<DeclContext *>(S->getEntity())
794 ->isTransparentContext()))
795 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000796 }
797
John McCall1d7c5282009-12-18 10:40:03 +0000798 unsigned IDNS = R.getIdentifierNamespace();
799
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000800 // Scan up the scope chain looking for a decl that matches this
801 // identifier that is in the appropriate namespace. This search
802 // should not take long, as shadowing of names is uncommon, and
803 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000804 bool LeftStartingScope = false;
805
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000806 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +0000807 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000808 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000809 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000810 if (NameKind == LookupRedeclarationWithLinkage) {
811 // Determine whether this (or a previous) declaration is
812 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000813 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000814 LeftStartingScope = true;
815
816 // If we found something outside of our starting scope that
817 // does not have linkage, skip it.
818 if (LeftStartingScope && !((*I)->hasLinkage()))
819 continue;
820 }
821
John McCallf36e02d2009-10-09 21:13:30 +0000822 R.addDecl(*I);
823
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000824 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000825 // If this declaration has the "overloadable" attribute, we
826 // might have a set of overloaded functions.
827
828 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000829 while (!(S->getFlags() & Scope::DeclScope) ||
830 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000831 S = S->getParent();
832
833 // Find the last declaration in this scope (with the same
834 // name, naturally).
835 IdentifierResolver::iterator LastI = I;
836 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000837 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000838 break;
John McCallf36e02d2009-10-09 21:13:30 +0000839 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000840 }
Douglas Gregorf9201e02009-02-11 23:02:49 +0000841 }
842
John McCallf36e02d2009-10-09 21:13:30 +0000843 R.resolveKind();
844
845 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000846 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000847 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000848 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000849 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +0000850 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000851 }
852
853 // If we didn't find a use of this identifier, and if the identifier
854 // corresponds to a compiler builtin, create the decl object for the builtin
855 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +0000856 if (AllowBuiltinCreation)
857 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000858
John McCallf36e02d2009-10-09 21:13:30 +0000859 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000860}
861
John McCall6e247262009-10-10 05:48:19 +0000862/// @brief Perform qualified name lookup in the namespaces nominated by
863/// using directives by the given context.
864///
865/// C++98 [namespace.qual]p2:
866/// Given X::m (where X is a user-declared namespace), or given ::m
867/// (where X is the global namespace), let S be the set of all
868/// declarations of m in X and in the transitive closure of all
869/// namespaces nominated by using-directives in X and its used
870/// namespaces, except that using-directives are ignored in any
871/// namespace, including X, directly containing one or more
872/// declarations of m. No namespace is searched more than once in
873/// the lookup of a name. If S is the empty set, the program is
874/// ill-formed. Otherwise, if S has exactly one member, or if the
875/// context of the reference is a using-declaration
876/// (namespace.udecl), S is the required set of declarations of
877/// m. Otherwise if the use of m is not one that allows a unique
878/// declaration to be chosen from S, the program is ill-formed.
879/// C++98 [namespace.qual]p5:
880/// During the lookup of a qualified namespace member name, if the
881/// lookup finds more than one declaration of the member, and if one
882/// declaration introduces a class name or enumeration name and the
883/// other declarations either introduce the same object, the same
884/// enumerator or a set of functions, the non-type name hides the
885/// class or enumeration name if and only if the declarations are
886/// from the same namespace; otherwise (the declarations are from
887/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +0000888static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +0000889 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +0000890 assert(StartDC->isFileContext() && "start context is not a file context");
891
892 DeclContext::udir_iterator I = StartDC->using_directives_begin();
893 DeclContext::udir_iterator E = StartDC->using_directives_end();
894
895 if (I == E) return false;
896
897 // We have at least added all these contexts to the queue.
898 llvm::DenseSet<DeclContext*> Visited;
899 Visited.insert(StartDC);
900
901 // We have not yet looked into these namespaces, much less added
902 // their "using-children" to the queue.
903 llvm::SmallVector<NamespaceDecl*, 8> Queue;
904
905 // We have already looked into the initial namespace; seed the queue
906 // with its using-children.
907 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +0000908 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +0000909 if (Visited.insert(ND).second)
910 Queue.push_back(ND);
911 }
912
913 // The easiest way to implement the restriction in [namespace.qual]p5
914 // is to check whether any of the individual results found a tag
915 // and, if so, to declare an ambiguity if the final result is not
916 // a tag.
917 bool FoundTag = false;
918 bool FoundNonTag = false;
919
John McCall7d384dd2009-11-18 07:57:50 +0000920 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +0000921
922 bool Found = false;
923 while (!Queue.empty()) {
924 NamespaceDecl *ND = Queue.back();
925 Queue.pop_back();
926
927 // We go through some convolutions here to avoid copying results
928 // between LookupResults.
929 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +0000930 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +0000931 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +0000932
933 if (FoundDirect) {
934 // First do any local hiding.
935 DirectR.resolveKind();
936
937 // If the local result is a tag, remember that.
938 if (DirectR.isSingleTagDecl())
939 FoundTag = true;
940 else
941 FoundNonTag = true;
942
943 // Append the local results to the total results if necessary.
944 if (UseLocal) {
945 R.addAllDecls(LocalR);
946 LocalR.clear();
947 }
948 }
949
950 // If we find names in this namespace, ignore its using directives.
951 if (FoundDirect) {
952 Found = true;
953 continue;
954 }
955
956 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
957 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
958 if (Visited.insert(Nom).second)
959 Queue.push_back(Nom);
960 }
961 }
962
963 if (Found) {
964 if (FoundTag && FoundNonTag)
965 R.setAmbiguousQualifiedTagHiding();
966 else
967 R.resolveKind();
968 }
969
970 return Found;
971}
972
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000973/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000974///
975/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
976/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000977/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000978///
979/// Different lookup criteria can find different names. For example, a
980/// particular scope can have both a struct and a function of the same
981/// name, and each can be found by certain lookup criteria. For more
982/// information about lookup criteria, see the documentation for the
983/// class LookupCriteria.
984///
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000985/// \param R captures both the lookup criteria and any lookup results found.
986///
987/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000988/// search. If the lookup criteria permits, name lookup may also search
989/// in the parent contexts or (for C++ classes) base classes.
990///
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000991/// \param InUnqualifiedLookup true if this is qualified name lookup that
992/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000993///
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000994/// \returns true if lookup succeeded, false if it failed.
995bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
996 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000997 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +0000998
John McCalla24dc2e2009-11-17 02:14:36 +0000999 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001000 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001002 // Make sure that the declaration context is complete.
1003 assert((!isa<TagDecl>(LookupCtx) ||
1004 LookupCtx->isDependentContext() ||
1005 cast<TagDecl>(LookupCtx)->isDefinition() ||
1006 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1007 ->isBeingDefined()) &&
1008 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001010 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001011 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001012 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001013 if (isa<CXXRecordDecl>(LookupCtx))
1014 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001015 return true;
1016 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001017
John McCall6e247262009-10-10 05:48:19 +00001018 // Don't descend into implied contexts for redeclarations.
1019 // C++98 [namespace.qual]p6:
1020 // In a declaration for a namespace member in which the
1021 // declarator-id is a qualified-id, given that the qualified-id
1022 // for the namespace member has the form
1023 // nested-name-specifier unqualified-id
1024 // the unqualified-id shall name a member of the namespace
1025 // designated by the nested-name-specifier.
1026 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001027 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001028 return false;
1029
John McCalla24dc2e2009-11-17 02:14:36 +00001030 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001031 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001032 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001033
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001034 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001035 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001036 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1037 if (!LookupRec)
John McCallf36e02d2009-10-09 21:13:30 +00001038 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001039
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001040 // If we're performing qualified name lookup into a dependent class,
1041 // then we are actually looking into a current instantiation. If we have any
1042 // dependent base classes, then we either have to delay lookup until
1043 // template instantiation time (at which point all bases will be available)
1044 // or we have to fail.
1045 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1046 LookupRec->hasAnyDependentBases()) {
1047 R.setNotFoundInCurrentInstantiation();
1048 return false;
1049 }
1050
Douglas Gregor7176fff2009-01-15 00:26:24 +00001051 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001052 CXXBasePaths Paths;
1053 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001054
1055 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001056 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001057 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001058 case LookupOrdinaryName:
1059 case LookupMemberName:
1060 case LookupRedeclarationWithLinkage:
1061 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1062 break;
1063
1064 case LookupTagName:
1065 BaseCallback = &CXXRecordDecl::FindTagMember;
1066 break;
John McCall9f54ad42009-12-10 09:41:52 +00001067
1068 case LookupUsingDeclName:
1069 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001070
1071 case LookupOperatorName:
1072 case LookupNamespaceName:
1073 case LookupObjCProtocolName:
1074 case LookupObjCImplementationName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001075 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001076 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001077
1078 case LookupNestedNameSpecifierName:
1079 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1080 break;
1081 }
1082
John McCalla24dc2e2009-11-17 02:14:36 +00001083 if (!LookupRec->lookupInBases(BaseCallback,
1084 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001085 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001086
John McCall92f88312010-01-23 00:46:32 +00001087 R.setNamingClass(LookupRec);
1088
Douglas Gregor7176fff2009-01-15 00:26:24 +00001089 // C++ [class.member.lookup]p2:
1090 // [...] If the resulting set of declarations are not all from
1091 // sub-objects of the same type, or the set has a nonstatic member
1092 // and includes members from distinct sub-objects, there is an
1093 // ambiguity and the program is ill-formed. Otherwise that set is
1094 // the result of the lookup.
1095 // FIXME: support using declarations!
1096 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001097 int SubobjectNumber = 0;
John McCall46460a62010-01-20 21:53:11 +00001098 AccessSpecifier SubobjectAccess = AS_private;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001099 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001100 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001101 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001102
John McCall46460a62010-01-20 21:53:11 +00001103 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1104 // across all paths.
1105 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1106
Douglas Gregor7176fff2009-01-15 00:26:24 +00001107 // Determine whether we're looking at a distinct sub-object or not.
1108 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001109 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001110 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1111 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00001112 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001113 != Context.getCanonicalType(PathElement.Base->getType())) {
1114 // We found members of the given name in two subobjects of
1115 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001116 R.setAmbiguousBaseSubobjectTypes(Paths);
1117 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001118 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1119 // We have a different subobject of the same type.
1120
1121 // C++ [class.member.lookup]p5:
1122 // A static member, a nested type or an enumerator defined in
1123 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001124 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001125 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001126 if (isa<VarDecl>(FirstDecl) ||
1127 isa<TypeDecl>(FirstDecl) ||
1128 isa<EnumConstantDecl>(FirstDecl))
1129 continue;
1130
1131 if (isa<CXXMethodDecl>(FirstDecl)) {
1132 // Determine whether all of the methods are static.
1133 bool AllMethodsAreStatic = true;
1134 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1135 Func != Path->Decls.second; ++Func) {
1136 if (!isa<CXXMethodDecl>(*Func)) {
1137 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1138 break;
1139 }
1140
1141 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1142 AllMethodsAreStatic = false;
1143 break;
1144 }
1145 }
1146
1147 if (AllMethodsAreStatic)
1148 continue;
1149 }
1150
1151 // We have found a nonstatic member name in multiple, distinct
1152 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001153 R.setAmbiguousBaseSubobjects(Paths);
1154 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001155 }
1156 }
1157
1158 // Lookup in a base class succeeded; return these results.
1159
John McCallf36e02d2009-10-09 21:13:30 +00001160 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001161 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1162 NamedDecl *D = *I;
1163 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1164 D->getAccess());
1165 R.addDecl(D, AS);
1166 }
John McCallf36e02d2009-10-09 21:13:30 +00001167 R.resolveKind();
1168 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001169}
1170
1171/// @brief Performs name lookup for a name that was parsed in the
1172/// source code, and may contain a C++ scope specifier.
1173///
1174/// This routine is a convenience routine meant to be called from
1175/// contexts that receive a name and an optional C++ scope specifier
1176/// (e.g., "N::M::x"). It will then perform either qualified or
1177/// unqualified name lookup (with LookupQualifiedName or LookupName,
1178/// respectively) on the given name and return those results.
1179///
1180/// @param S The scope from which unqualified name lookup will
1181/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001182///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001183/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001184///
1185/// @param Name The name of the entity that name lookup will
1186/// search for.
1187///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001188/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001189/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001190/// C library functions (like "malloc") are implicitly declared.
1191///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001192/// @param EnteringContext Indicates whether we are going to enter the
1193/// context of the scope-specifier SS (if present).
1194///
John McCallf36e02d2009-10-09 21:13:30 +00001195/// @returns True if any decls were found (but possibly ambiguous)
1196bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001197 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001198 if (SS && SS->isInvalid()) {
1199 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001200 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001201 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001202 }
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Douglas Gregor495c35d2009-08-25 22:51:20 +00001204 if (SS && SS->isSet()) {
1205 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001206 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001207 // contex, and will perform name lookup in that context.
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001208 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCallf36e02d2009-10-09 21:13:30 +00001209 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001210
John McCalla24dc2e2009-11-17 02:14:36 +00001211 R.setContextRange(SS->getRange());
1212
1213 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001214 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001215
Douglas Gregor495c35d2009-08-25 22:51:20 +00001216 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001217 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001218 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001219 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001220 }
1221
Mike Stump1eb44332009-09-09 15:08:12 +00001222 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001223 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001224}
1225
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001226
Douglas Gregor7176fff2009-01-15 00:26:24 +00001227/// @brief Produce a diagnostic describing the ambiguity that resulted
1228/// from name lookup.
1229///
1230/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001231///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001232/// @param Name The name of the entity that name lookup was
1233/// searching for.
1234///
1235/// @param NameLoc The location of the name within the source code.
1236///
1237/// @param LookupRange A source range that provides more
1238/// source-location information concerning the lookup itself. For
1239/// example, this range might highlight a nested-name-specifier that
1240/// precedes the name.
1241///
1242/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001243bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001244 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1245
John McCalla24dc2e2009-11-17 02:14:36 +00001246 DeclarationName Name = Result.getLookupName();
1247 SourceLocation NameLoc = Result.getNameLoc();
1248 SourceRange LookupRange = Result.getContextRange();
1249
John McCall6e247262009-10-10 05:48:19 +00001250 switch (Result.getAmbiguityKind()) {
1251 case LookupResult::AmbiguousBaseSubobjects: {
1252 CXXBasePaths *Paths = Result.getBasePaths();
1253 QualType SubobjectType = Paths->front().back().Base->getType();
1254 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1255 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1256 << LookupRange;
1257
1258 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1259 while (isa<CXXMethodDecl>(*Found) &&
1260 cast<CXXMethodDecl>(*Found)->isStatic())
1261 ++Found;
1262
1263 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1264
1265 return true;
1266 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001267
John McCall6e247262009-10-10 05:48:19 +00001268 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001269 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1270 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001271
1272 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001273 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001274 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1275 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001276 Path != PathEnd; ++Path) {
1277 Decl *D = *Path->Decls.first;
1278 if (DeclsPrinted.insert(D).second)
1279 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1280 }
1281
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001282 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001283 }
1284
John McCall6e247262009-10-10 05:48:19 +00001285 case LookupResult::AmbiguousTagHiding: {
1286 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001287
John McCall6e247262009-10-10 05:48:19 +00001288 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1289
1290 LookupResult::iterator DI, DE = Result.end();
1291 for (DI = Result.begin(); DI != DE; ++DI)
1292 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1293 TagDecls.insert(TD);
1294 Diag(TD->getLocation(), diag::note_hidden_tag);
1295 }
1296
1297 for (DI = Result.begin(); DI != DE; ++DI)
1298 if (!isa<TagDecl>(*DI))
1299 Diag((*DI)->getLocation(), diag::note_hiding_object);
1300
1301 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001302 LookupResult::Filter F = Result.makeFilter();
1303 while (F.hasNext()) {
1304 if (TagDecls.count(F.next()))
1305 F.erase();
1306 }
1307 F.done();
John McCall6e247262009-10-10 05:48:19 +00001308
1309 return true;
1310 }
1311
1312 case LookupResult::AmbiguousReference: {
1313 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001314
John McCall6e247262009-10-10 05:48:19 +00001315 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1316 for (; DI != DE; ++DI)
1317 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001318
John McCall6e247262009-10-10 05:48:19 +00001319 return true;
1320 }
1321 }
1322
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001323 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001324 return true;
1325}
Douglas Gregorfa047642009-02-04 00:32:51 +00001326
Mike Stump1eb44332009-09-09 15:08:12 +00001327static void
1328addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001329 ASTContext &Context,
1330 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001331 Sema::AssociatedClassSet &AssociatedClasses);
1332
1333static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1334 DeclContext *Ctx) {
1335 if (Ctx->isFileContext())
1336 Namespaces.insert(Ctx);
1337}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001338
Mike Stump1eb44332009-09-09 15:08:12 +00001339// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001340// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001341static void
1342addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001343 ASTContext &Context,
1344 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001345 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001346 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001347 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001348 switch (Arg.getKind()) {
1349 case TemplateArgument::Null:
1350 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Douglas Gregor69be8d62009-07-08 07:51:57 +00001352 case TemplateArgument::Type:
1353 // [...] the namespaces and classes associated with the types of the
1354 // template arguments provided for template type parameters (excluding
1355 // template template parameters)
1356 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1357 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001358 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001359 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Douglas Gregor788cd062009-11-11 01:00:40 +00001361 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001362 // [...] the namespaces in which any template template arguments are
1363 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001364 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001365 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001366 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001367 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001368 DeclContext *Ctx = ClassTemplate->getDeclContext();
1369 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1370 AssociatedClasses.insert(EnclosingClass);
1371 // Add the associated namespace for this class.
1372 while (Ctx->isRecord())
1373 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001374 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001375 }
1376 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001377 }
1378
1379 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001380 case TemplateArgument::Integral:
1381 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001382 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001383 // associated namespaces. ]
1384 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Douglas Gregor69be8d62009-07-08 07:51:57 +00001386 case TemplateArgument::Pack:
1387 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1388 PEnd = Arg.pack_end();
1389 P != PEnd; ++P)
1390 addAssociatedClassesAndNamespaces(*P, Context,
1391 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001392 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001393 break;
1394 }
1395}
1396
Douglas Gregorfa047642009-02-04 00:32:51 +00001397// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001398// argument-dependent lookup with an argument of class type
1399// (C++ [basic.lookup.koenig]p2).
1400static void
1401addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregorfa047642009-02-04 00:32:51 +00001402 ASTContext &Context,
1403 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001404 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001405 // C++ [basic.lookup.koenig]p2:
1406 // [...]
1407 // -- If T is a class type (including unions), its associated
1408 // classes are: the class itself; the class of which it is a
1409 // member, if any; and its direct and indirect base
1410 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001411 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001412
1413 // Add the class of which it is a member, if any.
1414 DeclContext *Ctx = Class->getDeclContext();
1415 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1416 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001417 // Add the associated namespace for this class.
1418 while (Ctx->isRecord())
1419 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001420 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Douglas Gregorfa047642009-02-04 00:32:51 +00001422 // Add the class itself. If we've already seen this class, we don't
1423 // need to visit base classes.
1424 if (!AssociatedClasses.insert(Class))
1425 return;
1426
Mike Stump1eb44332009-09-09 15:08:12 +00001427 // -- If T is a template-id, its associated namespaces and classes are
1428 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001429 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001430 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001431 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001432 // namespaces in which any template template arguments are defined; and
1433 // the classes in which any member templates used as template template
1434 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001435 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001436 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001437 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1438 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1439 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1440 AssociatedClasses.insert(EnclosingClass);
1441 // Add the associated namespace for this class.
1442 while (Ctx->isRecord())
1443 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001444 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Douglas Gregor69be8d62009-07-08 07:51:57 +00001446 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1447 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1448 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1449 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001450 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001451 }
Mike Stump1eb44332009-09-09 15:08:12 +00001452
John McCall86ff3082010-02-04 22:26:26 +00001453 // Only recurse into base classes for complete types.
1454 if (!Class->hasDefinition()) {
1455 // FIXME: we might need to instantiate templates here
1456 return;
1457 }
1458
Douglas Gregorfa047642009-02-04 00:32:51 +00001459 // Add direct and indirect base classes along with their associated
1460 // namespaces.
1461 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1462 Bases.push_back(Class);
1463 while (!Bases.empty()) {
1464 // Pop this class off the stack.
1465 Class = Bases.back();
1466 Bases.pop_back();
1467
1468 // Visit the base classes.
1469 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1470 BaseEnd = Class->bases_end();
1471 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001472 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001473 // In dependent contexts, we do ADL twice, and the first time around,
1474 // the base type might be a dependent TemplateSpecializationType, or a
1475 // TemplateTypeParmType. If that happens, simply ignore it.
1476 // FIXME: If we want to support export, we probably need to add the
1477 // namespace of the template in a TemplateSpecializationType, or even
1478 // the classes and namespaces of known non-dependent arguments.
1479 if (!BaseType)
1480 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001481 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1482 if (AssociatedClasses.insert(BaseDecl)) {
1483 // Find the associated namespace for this base class.
1484 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1485 while (BaseCtx->isRecord())
1486 BaseCtx = BaseCtx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001487 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001488
1489 // Make sure we visit the bases of this base class.
1490 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1491 Bases.push_back(BaseDecl);
1492 }
1493 }
1494 }
1495}
1496
1497// \brief Add the associated classes and namespaces for
1498// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001499// (C++ [basic.lookup.koenig]p2).
1500static void
1501addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregorfa047642009-02-04 00:32:51 +00001502 ASTContext &Context,
1503 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001504 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001505 // C++ [basic.lookup.koenig]p2:
1506 //
1507 // For each argument type T in the function call, there is a set
1508 // of zero or more associated namespaces and a set of zero or more
1509 // associated classes to be considered. The sets of namespaces and
1510 // classes is determined entirely by the types of the function
1511 // arguments (and the namespace of any template template
1512 // argument). Typedef names and using-declarations used to specify
1513 // the types do not contribute to this set. The sets of namespaces
1514 // and classes are determined in the following way:
1515 T = Context.getCanonicalType(T).getUnqualifiedType();
1516
1517 // -- If T is a pointer to U or an array of U, its associated
Mike Stump1eb44332009-09-09 15:08:12 +00001518 // namespaces and classes are those associated with U.
Douglas Gregorfa047642009-02-04 00:32:51 +00001519 //
1520 // We handle this by unwrapping pointer and array types immediately,
1521 // to avoid unnecessary recursion.
1522 while (true) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001523 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001524 T = Ptr->getPointeeType();
1525 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1526 T = Ptr->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001527 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001528 break;
1529 }
1530
1531 // -- If T is a fundamental type, its associated sets of
1532 // namespaces and classes are both empty.
John McCall183700f2009-09-21 23:43:11 +00001533 if (T->getAs<BuiltinType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001534 return;
1535
1536 // -- If T is a class type (including unions), its associated
1537 // classes are: the class itself; the class of which it is a
1538 // member, if any; and its direct and indirect base
1539 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001540 // which its associated classes are defined.
Ted Kremenek6217b802009-07-29 21:53:49 +00001541 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001542 if (CXXRecordDecl *ClassDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001543 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001544 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1545 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001546 AssociatedClasses);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001547 return;
1548 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001549
1550 // -- If T is an enumeration type, its associated namespace is
1551 // the namespace in which it is defined. If it is class
1552 // member, its associated class is the member’s class; else
Mike Stump1eb44332009-09-09 15:08:12 +00001553 // it has no associated class.
John McCall183700f2009-09-21 23:43:11 +00001554 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001555 EnumDecl *Enum = EnumT->getDecl();
1556
1557 DeclContext *Ctx = Enum->getDeclContext();
1558 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1559 AssociatedClasses.insert(EnclosingClass);
1560
1561 // Add the associated namespace for this class.
1562 while (Ctx->isRecord())
1563 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001564 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001565
1566 return;
1567 }
1568
1569 // -- If T is a function type, its associated namespaces and
1570 // classes are those associated with the function parameter
1571 // types and those associated with the return type.
John McCall183700f2009-09-21 23:43:11 +00001572 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001573 // Return type
John McCall183700f2009-09-21 23:43:11 +00001574 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001575 Context,
John McCall6ff07852009-08-07 22:18:02 +00001576 AssociatedNamespaces, AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001577
John McCall183700f2009-09-21 23:43:11 +00001578 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001579 if (!Proto)
1580 return;
1581
1582 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001583 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001584 ArgEnd = Proto->arg_type_end();
Douglas Gregorfa047642009-02-04 00:32:51 +00001585 Arg != ArgEnd; ++Arg)
1586 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCall6ff07852009-08-07 22:18:02 +00001587 AssociatedNamespaces, AssociatedClasses);
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Douglas Gregorfa047642009-02-04 00:32:51 +00001589 return;
1590 }
1591
1592 // -- If T is a pointer to a member function of a class X, its
1593 // associated namespaces and classes are those associated
1594 // with the function parameter types and return type,
Mike Stump1eb44332009-09-09 15:08:12 +00001595 // together with those associated with X.
Douglas Gregorfa047642009-02-04 00:32:51 +00001596 //
1597 // -- If T is a pointer to a data member of class X, its
1598 // associated namespaces and classes are those associated
1599 // with the member type together with those associated with
Mike Stump1eb44332009-09-09 15:08:12 +00001600 // X.
Ted Kremenek6217b802009-07-29 21:53:49 +00001601 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001602 // Handle the type that the pointer to member points to.
1603 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1604 Context,
John McCall6ff07852009-08-07 22:18:02 +00001605 AssociatedNamespaces,
1606 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001607
1608 // Handle the class type into which this points.
Ted Kremenek6217b802009-07-29 21:53:49 +00001609 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001610 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1611 Context,
John McCall6ff07852009-08-07 22:18:02 +00001612 AssociatedNamespaces,
1613 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001614
1615 return;
1616 }
1617
1618 // FIXME: What about block pointers?
1619 // FIXME: What about Objective-C message sends?
1620}
1621
1622/// \brief Find the associated classes and namespaces for
1623/// argument-dependent lookup for a call with the given set of
1624/// arguments.
1625///
1626/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001627/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001628/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001629void
Douglas Gregorfa047642009-02-04 00:32:51 +00001630Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1631 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001632 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001633 AssociatedNamespaces.clear();
1634 AssociatedClasses.clear();
1635
1636 // C++ [basic.lookup.koenig]p2:
1637 // For each argument type T in the function call, there is a set
1638 // of zero or more associated namespaces and a set of zero or more
1639 // associated classes to be considered. The sets of namespaces and
1640 // classes is determined entirely by the types of the function
1641 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001642 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001643 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1644 Expr *Arg = Args[ArgIdx];
1645
1646 if (Arg->getType() != Context.OverloadTy) {
1647 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001648 AssociatedNamespaces,
1649 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001650 continue;
1651 }
1652
1653 // [...] In addition, if the argument is the name or address of a
1654 // set of overloaded functions and/or function templates, its
1655 // associated classes and namespaces are the union of those
1656 // associated with each of the members of the set: the namespace
1657 // in which the function or function template is defined and the
1658 // classes and namespaces associated with its (non-dependent)
1659 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001660 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001661 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1662 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1663 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001664
John McCallba135432009-11-21 08:51:07 +00001665 // TODO: avoid the copies. This should be easy when the cases
1666 // share a storage implementation.
1667 llvm::SmallVector<NamedDecl*, 8> Functions;
1668
1669 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1670 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00001671 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001672 continue;
1673
John McCallba135432009-11-21 08:51:07 +00001674 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1675 E = Functions.end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001676 // Look through any using declarations to find the underlying function.
1677 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001678
Chandler Carruthbd647292009-12-29 06:17:27 +00001679 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1680 if (!FDecl)
1681 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001682
1683 // Add the classes and namespaces associated with the parameter
1684 // types and return type of this function.
1685 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001686 AssociatedNamespaces,
1687 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001688 }
1689 }
1690}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001691
1692/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1693/// an acceptable non-member overloaded operator for a call whose
1694/// arguments have types T1 (and, if non-empty, T2). This routine
1695/// implements the check in C++ [over.match.oper]p3b2 concerning
1696/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001697static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001698IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1699 QualType T1, QualType T2,
1700 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001701 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1702 return true;
1703
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001704 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1705 return true;
1706
John McCall183700f2009-09-21 23:43:11 +00001707 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001708 if (Proto->getNumArgs() < 1)
1709 return false;
1710
1711 if (T1->isEnumeralType()) {
1712 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001713 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001714 return true;
1715 }
1716
1717 if (Proto->getNumArgs() < 2)
1718 return false;
1719
1720 if (!T2.isNull() && T2->isEnumeralType()) {
1721 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001722 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001723 return true;
1724 }
1725
1726 return false;
1727}
1728
John McCall7d384dd2009-11-18 07:57:50 +00001729NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1730 LookupNameKind NameKind,
1731 RedeclarationKind Redecl) {
1732 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1733 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00001734 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00001735}
1736
Douglas Gregor6e378de2009-04-23 23:18:26 +00001737/// \brief Find the protocol with the given name, if any.
1738ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCallf36e02d2009-10-09 21:13:30 +00001739 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001740 return cast_or_null<ObjCProtocolDecl>(D);
1741}
1742
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001743void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001744 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00001745 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001746 // C++ [over.match.oper]p3:
1747 // -- The set of non-member candidates is the result of the
1748 // unqualified lookup of operator@ in the context of the
1749 // expression according to the usual rules for name lookup in
1750 // unqualified function calls (3.4.2) except that all member
1751 // functions are ignored. However, if no operand has a class
1752 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00001753 // that have a first parameter of type T1 or "reference to
1754 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001755 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00001756 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001757 // when T2 is an enumeration type, are candidate functions.
1758 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00001759 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1760 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001762 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1763
John McCallf36e02d2009-10-09 21:13:30 +00001764 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001765 return;
1766
1767 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1768 Op != OpEnd; ++Op) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001769 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001770 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
John McCall6e266892010-01-26 03:27:55 +00001771 Functions.addDecl(FD, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00001772 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor364e0212009-06-27 21:05:07 +00001773 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1774 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00001775 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00001776 // later?
1777 if (!FunTmpl->getDeclContext()->isRecord())
John McCall6e266892010-01-26 03:27:55 +00001778 Functions.addDecl(FunTmpl, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00001779 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001780 }
1781}
1782
John McCall7edb5fd2010-01-26 07:16:45 +00001783void ADLResult::insert(NamedDecl *New) {
1784 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1785
1786 // If we haven't yet seen a decl for this key, or the last decl
1787 // was exactly this one, we're done.
1788 if (Old == 0 || Old == New) {
1789 Old = New;
1790 return;
1791 }
1792
1793 // Otherwise, decide which is a more recent redeclaration.
1794 FunctionDecl *OldFD, *NewFD;
1795 if (isa<FunctionTemplateDecl>(New)) {
1796 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1797 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1798 } else {
1799 OldFD = cast<FunctionDecl>(Old);
1800 NewFD = cast<FunctionDecl>(New);
1801 }
1802
1803 FunctionDecl *Cursor = NewFD;
1804 while (true) {
1805 Cursor = Cursor->getPreviousDeclaration();
1806
1807 // If we got to the end without finding OldFD, OldFD is the newer
1808 // declaration; leave things as they are.
1809 if (!Cursor) return;
1810
1811 // If we do find OldFD, then NewFD is newer.
1812 if (Cursor == OldFD) break;
1813
1814 // Otherwise, keep looking.
1815 }
1816
1817 Old = New;
1818}
1819
Sebastian Redl644be852009-10-23 19:23:15 +00001820void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001821 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00001822 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001823 // Find all of the associated namespaces and classes based on the
1824 // arguments we have.
1825 AssociatedNamespaceSet AssociatedNamespaces;
1826 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00001827 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00001828 AssociatedNamespaces,
1829 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001830
Sebastian Redl644be852009-10-23 19:23:15 +00001831 QualType T1, T2;
1832 if (Operator) {
1833 T1 = Args[0]->getType();
1834 if (NumArgs >= 2)
1835 T2 = Args[1]->getType();
1836 }
1837
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001838 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001839 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1840 // and let Y be the lookup set produced by argument dependent
1841 // lookup (defined as follows). If X contains [...] then Y is
1842 // empty. Otherwise Y is the set of declarations found in the
1843 // namespaces associated with the argument types as described
1844 // below. The set of declarations found by the lookup of the name
1845 // is the union of X and Y.
1846 //
1847 // Here, we compute Y and add its members to the overloaded
1848 // candidate set.
1849 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001850 NSEnd = AssociatedNamespaces.end();
1851 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001852 // When considering an associated namespace, the lookup is the
1853 // same as the lookup performed when the associated namespace is
1854 // used as a qualifier (3.4.3.2) except that:
1855 //
1856 // -- Any using-directives in the associated namespace are
1857 // ignored.
1858 //
John McCall6ff07852009-08-07 22:18:02 +00001859 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001860 // associated classes are visible within their respective
1861 // namespaces even if they are not visible during an ordinary
1862 // lookup (11.4).
1863 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00001864 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00001865 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00001866 // If the only declaration here is an ordinary friend, consider
1867 // it only if it was declared in an associated classes.
1868 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00001869 DeclContext *LexDC = D->getLexicalDeclContext();
1870 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1871 continue;
1872 }
Mike Stump1eb44332009-09-09 15:08:12 +00001873
John McCalla113e722010-01-26 06:04:06 +00001874 if (isa<UsingShadowDecl>(D))
1875 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00001876
John McCalla113e722010-01-26 06:04:06 +00001877 if (isa<FunctionDecl>(D)) {
1878 if (Operator &&
1879 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
1880 T1, T2, Context))
1881 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00001882 } else if (!isa<FunctionTemplateDecl>(D))
1883 continue;
1884
1885 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001886 }
1887 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001888}
Douglas Gregor546be3c2009-12-30 17:04:44 +00001889
1890//----------------------------------------------------------------------------
1891// Search for all visible declarations.
1892//----------------------------------------------------------------------------
1893VisibleDeclConsumer::~VisibleDeclConsumer() { }
1894
1895namespace {
1896
1897class ShadowContextRAII;
1898
1899class VisibleDeclsRecord {
1900public:
1901 /// \brief An entry in the shadow map, which is optimized to store a
1902 /// single declaration (the common case) but can also store a list
1903 /// of declarations.
1904 class ShadowMapEntry {
1905 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1906
1907 /// \brief Contains either the solitary NamedDecl * or a vector
1908 /// of declarations.
1909 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1910
1911 public:
1912 ShadowMapEntry() : DeclOrVector() { }
1913
1914 void Add(NamedDecl *ND);
1915 void Destroy();
1916
1917 // Iteration.
1918 typedef NamedDecl **iterator;
1919 iterator begin();
1920 iterator end();
1921 };
1922
1923private:
1924 /// \brief A mapping from declaration names to the declarations that have
1925 /// this name within a particular scope.
1926 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
1927
1928 /// \brief A list of shadow maps, which is used to model name hiding.
1929 std::list<ShadowMap> ShadowMaps;
1930
1931 /// \brief The declaration contexts we have already visited.
1932 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
1933
1934 friend class ShadowContextRAII;
1935
1936public:
1937 /// \brief Determine whether we have already visited this context
1938 /// (and, if not, note that we are going to visit that context now).
1939 bool visitedContext(DeclContext *Ctx) {
1940 return !VisitedContexts.insert(Ctx);
1941 }
1942
1943 /// \brief Determine whether the given declaration is hidden in the
1944 /// current scope.
1945 ///
1946 /// \returns the declaration that hides the given declaration, or
1947 /// NULL if no such declaration exists.
1948 NamedDecl *checkHidden(NamedDecl *ND);
1949
1950 /// \brief Add a declaration to the current shadow map.
1951 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
1952};
1953
1954/// \brief RAII object that records when we've entered a shadow context.
1955class ShadowContextRAII {
1956 VisibleDeclsRecord &Visible;
1957
1958 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
1959
1960public:
1961 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
1962 Visible.ShadowMaps.push_back(ShadowMap());
1963 }
1964
1965 ~ShadowContextRAII() {
1966 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
1967 EEnd = Visible.ShadowMaps.back().end();
1968 E != EEnd;
1969 ++E)
1970 E->second.Destroy();
1971
1972 Visible.ShadowMaps.pop_back();
1973 }
1974};
1975
1976} // end anonymous namespace
1977
1978void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
1979 if (DeclOrVector.isNull()) {
1980 // 0 - > 1 elements: just set the single element information.
1981 DeclOrVector = ND;
1982 return;
1983 }
1984
1985 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
1986 // 1 -> 2 elements: create the vector of results and push in the
1987 // existing declaration.
1988 DeclVector *Vec = new DeclVector;
1989 Vec->push_back(PrevND);
1990 DeclOrVector = Vec;
1991 }
1992
1993 // Add the new element to the end of the vector.
1994 DeclOrVector.get<DeclVector*>()->push_back(ND);
1995}
1996
1997void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
1998 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
1999 delete Vec;
2000 DeclOrVector = ((NamedDecl *)0);
2001 }
2002}
2003
2004VisibleDeclsRecord::ShadowMapEntry::iterator
2005VisibleDeclsRecord::ShadowMapEntry::begin() {
2006 if (DeclOrVector.isNull())
2007 return 0;
2008
2009 if (DeclOrVector.dyn_cast<NamedDecl *>())
2010 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2011
2012 return DeclOrVector.get<DeclVector *>()->begin();
2013}
2014
2015VisibleDeclsRecord::ShadowMapEntry::iterator
2016VisibleDeclsRecord::ShadowMapEntry::end() {
2017 if (DeclOrVector.isNull())
2018 return 0;
2019
2020 if (DeclOrVector.dyn_cast<NamedDecl *>())
2021 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2022
2023 return DeclOrVector.get<DeclVector *>()->end();
2024}
2025
2026NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002027 // Look through using declarations.
2028 ND = ND->getUnderlyingDecl();
2029
Douglas Gregor546be3c2009-12-30 17:04:44 +00002030 unsigned IDNS = ND->getIdentifierNamespace();
2031 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2032 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2033 SM != SMEnd; ++SM) {
2034 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2035 if (Pos == SM->end())
2036 continue;
2037
2038 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2039 IEnd = Pos->second.end();
2040 I != IEnd; ++I) {
2041 // A tag declaration does not hide a non-tag declaration.
2042 if ((*I)->getIdentifierNamespace() == Decl::IDNS_Tag &&
2043 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2044 Decl::IDNS_ObjCProtocol)))
2045 continue;
2046
2047 // Protocols are in distinct namespaces from everything else.
2048 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2049 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2050 (*I)->getIdentifierNamespace() != IDNS)
2051 continue;
2052
Douglas Gregor0cc84042010-01-14 15:47:35 +00002053 // Functions and function templates in the same scope overload
2054 // rather than hide. FIXME: Look for hiding based on function
2055 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002056 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002057 ND->isFunctionOrFunctionTemplate() &&
2058 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002059 continue;
2060
Douglas Gregor546be3c2009-12-30 17:04:44 +00002061 // We've found a declaration that hides this one.
2062 return *I;
2063 }
2064 }
2065
2066 return 0;
2067}
2068
2069static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2070 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002071 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002072 VisibleDeclConsumer &Consumer,
2073 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002074 if (!Ctx)
2075 return;
2076
Douglas Gregor546be3c2009-12-30 17:04:44 +00002077 // Make sure we don't visit the same context twice.
2078 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2079 return;
2080
2081 // Enumerate all of the results in this context.
2082 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2083 CurCtx = CurCtx->getNextContext()) {
2084 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2085 DEnd = CurCtx->decls_end();
2086 D != DEnd; ++D) {
2087 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2088 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002089 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002090 Visited.add(ND);
2091 }
2092
2093 // Visit transparent contexts inside this context.
2094 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2095 if (InnerCtx->isTransparentContext())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002096 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002097 Consumer, Visited);
2098 }
2099 }
2100 }
2101
2102 // Traverse using directives for qualified name lookup.
2103 if (QualifiedNameLookup) {
2104 ShadowContextRAII Shadow(Visited);
2105 DeclContext::udir_iterator I, E;
2106 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2107 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002108 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002109 }
2110 }
2111
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002112 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002113 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002114 if (!Record->hasDefinition())
2115 return;
2116
Douglas Gregor546be3c2009-12-30 17:04:44 +00002117 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2118 BEnd = Record->bases_end();
2119 B != BEnd; ++B) {
2120 QualType BaseType = B->getType();
2121
2122 // Don't look into dependent bases, because name lookup can't look
2123 // there anyway.
2124 if (BaseType->isDependentType())
2125 continue;
2126
2127 const RecordType *Record = BaseType->getAs<RecordType>();
2128 if (!Record)
2129 continue;
2130
2131 // FIXME: It would be nice to be able to determine whether referencing
2132 // a particular member would be ambiguous. For example, given
2133 //
2134 // struct A { int member; };
2135 // struct B { int member; };
2136 // struct C : A, B { };
2137 //
2138 // void f(C *c) { c->### }
2139 //
2140 // accessing 'member' would result in an ambiguity. However, we
2141 // could be smart enough to qualify the member with the base
2142 // class, e.g.,
2143 //
2144 // c->B::member
2145 //
2146 // or
2147 //
2148 // c->A::member
2149
2150 // Find results in this base class (and its bases).
2151 ShadowContextRAII Shadow(Visited);
2152 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002153 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002154 }
2155 }
2156
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002157 // Traverse the contexts of Objective-C classes.
2158 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2159 // Traverse categories.
2160 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2161 Category; Category = Category->getNextClassCategory()) {
2162 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002163 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2164 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002165 }
2166
2167 // Traverse protocols.
2168 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2169 E = IFace->protocol_end(); I != E; ++I) {
2170 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002171 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2172 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002173 }
2174
2175 // Traverse the superclass.
2176 if (IFace->getSuperClass()) {
2177 ShadowContextRAII Shadow(Visited);
2178 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002179 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002180 }
2181 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2182 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2183 E = Protocol->protocol_end(); I != E; ++I) {
2184 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002185 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2186 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002187 }
2188 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2189 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2190 E = Category->protocol_end(); I != E; ++I) {
2191 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002192 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2193 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002194 }
2195 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002196}
2197
2198static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2199 UnqualUsingDirectiveSet &UDirs,
2200 VisibleDeclConsumer &Consumer,
2201 VisibleDeclsRecord &Visited) {
2202 if (!S)
2203 return;
2204
Douglas Gregor539c5c32010-01-07 00:31:29 +00002205 if (!S->getEntity() || !S->getParent() ||
2206 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2207 // Walk through the declarations in this Scope.
2208 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2209 D != DEnd; ++D) {
2210 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2211 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002212 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002213 Visited.add(ND);
2214 }
2215 }
2216 }
2217
Douglas Gregor546be3c2009-12-30 17:04:44 +00002218 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002219 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002220 // Look into this scope's declaration context, along with any of its
2221 // parent lookup contexts (e.g., enclosing classes), up to the point
2222 // where we hit the context stored in the next outer scope.
2223 Entity = (DeclContext *)S->getEntity();
2224 DeclContext *OuterCtx = findOuterContext(S);
2225
2226 for (DeclContext *Ctx = Entity; Ctx && Ctx->getPrimaryContext() != OuterCtx;
2227 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002228 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2229 if (Method->isInstanceMethod()) {
2230 // For instance methods, look for ivars in the method's interface.
2231 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2232 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor62021192010-02-04 23:42:48 +00002233 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2234 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2235 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002236 }
2237
2238 // We've already performed all of the name lookup that we need
2239 // to for Objective-C methods; the next context will be the
2240 // outer scope.
2241 break;
2242 }
2243
Douglas Gregor546be3c2009-12-30 17:04:44 +00002244 if (Ctx->isFunctionOrMethod())
2245 continue;
2246
2247 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002248 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002249 }
2250 } else if (!S->getParent()) {
2251 // Look into the translation unit scope. We walk through the translation
2252 // unit's declaration context, because the Scope itself won't have all of
2253 // the declarations if we loaded a precompiled header.
2254 // FIXME: We would like the translation unit's Scope object to point to the
2255 // translation unit, so we don't need this special "if" branch. However,
2256 // doing so would force the normal C++ name-lookup code to look into the
2257 // translation unit decl when the IdentifierInfo chains would suffice.
2258 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002259 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002260 Entity = Result.getSema().Context.getTranslationUnitDecl();
2261 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002262 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002263 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002264
2265 if (Entity) {
2266 // Lookup visible declarations in any namespaces found by using
2267 // directives.
2268 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2269 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2270 for (; UI != UEnd; ++UI)
2271 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002272 Result, /*QualifiedNameLookup=*/false,
2273 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002274 }
2275
2276 // Lookup names in the parent scope.
2277 ShadowContextRAII Shadow(Visited);
2278 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2279}
2280
2281void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2282 VisibleDeclConsumer &Consumer) {
2283 // Determine the set of using directives available during
2284 // unqualified name lookup.
2285 Scope *Initial = S;
2286 UnqualUsingDirectiveSet UDirs;
2287 if (getLangOptions().CPlusPlus) {
2288 // Find the first namespace or translation-unit scope.
2289 while (S && !isNamespaceOrTranslationUnitScope(S))
2290 S = S->getParent();
2291
2292 UDirs.visitScopeChain(Initial, S);
2293 }
2294 UDirs.done();
2295
2296 // Look for visible declarations.
2297 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2298 VisibleDeclsRecord Visited;
2299 ShadowContextRAII Shadow(Visited);
2300 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2301}
2302
2303void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2304 VisibleDeclConsumer &Consumer) {
2305 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2306 VisibleDeclsRecord Visited;
2307 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002308 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2309 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002310}
2311
2312//----------------------------------------------------------------------------
2313// Typo correction
2314//----------------------------------------------------------------------------
2315
2316namespace {
2317class TypoCorrectionConsumer : public VisibleDeclConsumer {
2318 /// \brief The name written that is a typo in the source.
2319 llvm::StringRef Typo;
2320
2321 /// \brief The results found that have the smallest edit distance
2322 /// found (so far) with the typo name.
2323 llvm::SmallVector<NamedDecl *, 4> BestResults;
2324
2325 /// \brief The best edit distance found so far.
2326 unsigned BestEditDistance;
2327
2328public:
2329 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2330 : Typo(Typo->getName()) { }
2331
Douglas Gregor0cc84042010-01-14 15:47:35 +00002332 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002333
2334 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2335 iterator begin() const { return BestResults.begin(); }
2336 iterator end() const { return BestResults.end(); }
2337 bool empty() const { return BestResults.empty(); }
2338
2339 unsigned getBestEditDistance() const { return BestEditDistance; }
2340};
2341
2342}
2343
Douglas Gregor0cc84042010-01-14 15:47:35 +00002344void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2345 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002346 // Don't consider hidden names for typo correction.
2347 if (Hiding)
2348 return;
2349
2350 // Only consider entities with identifiers for names, ignoring
2351 // special names (constructors, overloaded operators, selectors,
2352 // etc.).
2353 IdentifierInfo *Name = ND->getIdentifier();
2354 if (!Name)
2355 return;
2356
2357 // Compute the edit distance between the typo and the name of this
2358 // entity. If this edit distance is not worse than the best edit
2359 // distance we've seen so far, add it to the list of results.
2360 unsigned ED = Typo.edit_distance(Name->getName());
2361 if (!BestResults.empty()) {
2362 if (ED < BestEditDistance) {
2363 // This result is better than any we've seen before; clear out
2364 // the previous results.
2365 BestResults.clear();
2366 BestEditDistance = ED;
2367 } else if (ED > BestEditDistance) {
2368 // This result is worse than the best results we've seen so far;
2369 // ignore it.
2370 return;
2371 }
2372 } else
2373 BestEditDistance = ED;
2374
2375 BestResults.push_back(ND);
2376}
2377
2378/// \brief Try to "correct" a typo in the source code by finding
2379/// visible declarations whose names are similar to the name that was
2380/// present in the source code.
2381///
2382/// \param Res the \c LookupResult structure that contains the name
2383/// that was present in the source code along with the name-lookup
2384/// criteria used to search for the name. On success, this structure
2385/// will contain the results of name lookup.
2386///
2387/// \param S the scope in which name lookup occurs.
2388///
2389/// \param SS the nested-name-specifier that precedes the name we're
2390/// looking for, if present.
2391///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002392/// \param MemberContext if non-NULL, the context in which to look for
2393/// a member access expression.
2394///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002395/// \param EnteringContext whether we're entering the context described by
2396/// the nested-name-specifier SS.
2397///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002398/// \param OPT when non-NULL, the search for visible declarations will
2399/// also walk the protocols in the qualified interfaces of \p OPT.
2400///
Douglas Gregor546be3c2009-12-30 17:04:44 +00002401/// \returns true if the typo was corrected, in which case the \p Res
2402/// structure will contain the results of name lookup for the
2403/// corrected name. Otherwise, returns false.
2404bool Sema::CorrectTypo(LookupResult &Res, Scope *S, const CXXScopeSpec *SS,
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002405 DeclContext *MemberContext, bool EnteringContext,
2406 const ObjCObjectPointerType *OPT) {
Ted Kremenek1dac3412010-01-06 00:23:04 +00002407 if (Diags.hasFatalErrorOccurred())
2408 return false;
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002409
2410 // Provide a stop gap for files that are just seriously broken. Trying
2411 // to correct all typos can turn into a HUGE performance penalty, causing
2412 // some files to take minutes to get rejected by the parser.
2413 // FIXME: Is this the right solution?
2414 if (TyposCorrected == 20)
2415 return false;
2416 ++TyposCorrected;
Ted Kremenek1dac3412010-01-06 00:23:04 +00002417
Douglas Gregor546be3c2009-12-30 17:04:44 +00002418 // We only attempt to correct typos for identifiers.
2419 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2420 if (!Typo)
2421 return false;
2422
2423 // If the scope specifier itself was invalid, don't try to correct
2424 // typos.
2425 if (SS && SS->isInvalid())
2426 return false;
2427
2428 // Never try to correct typos during template deduction or
2429 // instantiation.
2430 if (!ActiveTemplateInstantiations.empty())
2431 return false;
2432
2433 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002434 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002435 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002436
2437 // Look in qualified interfaces.
2438 if (OPT) {
2439 for (ObjCObjectPointerType::qual_iterator
2440 I = OPT->qual_begin(), E = OPT->qual_end();
2441 I != E; ++I)
2442 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2443 }
2444 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002445 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2446 if (!DC)
2447 return false;
2448
2449 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2450 } else {
2451 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2452 }
2453
2454 if (Consumer.empty())
2455 return false;
2456
2457 // Only allow a single, closest name in the result set (it's okay to
2458 // have overloads of that name, though).
2459 TypoCorrectionConsumer::iterator I = Consumer.begin();
2460 DeclarationName BestName = (*I)->getDeclName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002461
2462 // If we've found an Objective-C ivar or property, don't perform
2463 // name lookup again; we'll just return the result directly.
2464 NamedDecl *FoundBest = 0;
2465 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I))
2466 FoundBest = *I;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002467 ++I;
2468 for(TypoCorrectionConsumer::iterator IEnd = Consumer.end(); I != IEnd; ++I) {
2469 if (BestName != (*I)->getDeclName())
2470 return false;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002471
2472 // FIXME: If there are both ivars and properties of the same name,
2473 // don't return both because the callee can't handle two
2474 // results. We really need to separate ivar lookup from property
2475 // lookup to avoid this problem.
2476 FoundBest = 0;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002477 }
2478
2479 // BestName is the closest viable name to what the user
2480 // typed. However, to make sure that we don't pick something that's
2481 // way off, make sure that the user typed at least 3 characters for
2482 // each correction.
2483 unsigned ED = Consumer.getBestEditDistance();
2484 if (ED == 0 || (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
2485 return false;
2486
2487 // Perform name lookup again with the name we chose, and declare
2488 // success if we found something that was not ambiguous.
2489 Res.clear();
2490 Res.setLookupName(BestName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002491
2492 // If we found an ivar or property, add that result; no further
2493 // lookup is required.
2494 if (FoundBest)
2495 Res.addDecl(FoundBest);
2496 // If we're looking into the context of a member, perform qualified
2497 // name lookup on the best name.
2498 else if (MemberContext)
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002499 LookupQualifiedName(Res, MemberContext);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002500 // Perform lookup as if we had just parsed the best name.
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002501 else
2502 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2503 EnteringContext);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002504
2505 if (Res.isAmbiguous()) {
2506 Res.suppressDiagnostics();
2507 return false;
2508 }
2509
2510 return Res.getResultKind() != LookupResult::NotFound;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002511}