blob: a7a1084d319714b7d8bec6e0cb98a550827682f0 [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
John McCall1d7c5282009-12-18 10:40:03 +0000205/// Gets the default result filter for the given lookup.
206static inline
207LookupResult::ResultFilter getResultFilter(Sema::LookupNameKind NameKind) {
208 switch (NameKind) {
209 case Sema::LookupOrdinaryName:
210 case Sema::LookupTagName:
211 case Sema::LookupMemberName:
212 case Sema::LookupRedeclarationWithLinkage: // FIXME: check linkage, scoping
213 case Sema::LookupUsingDeclName:
214 case Sema::LookupObjCProtocolName:
John McCall0d6b1642010-04-23 18:46:30 +0000215 case Sema::LookupNestedNameSpecifierName:
216 case Sema::LookupNamespaceName:
John McCall1d7c5282009-12-18 10:40:03 +0000217 return &IsAcceptableIDNS;
218
219 case Sema::LookupOperatorName:
220 return &IsAcceptableOperatorName;
John McCall1d7c5282009-12-18 10:40:03 +0000221 }
222
223 llvm_unreachable("unkknown lookup kind");
224 return 0;
225}
226
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000227// Retrieve the set of identifier namespaces that correspond to a
228// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000229static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
230 bool CPlusPlus,
231 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000232 unsigned IDNS = 0;
233 switch (NameKind) {
234 case Sema::LookupOrdinaryName:
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000235 case Sema::LookupOperatorName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000236 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000237 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000238 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000239 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCall1d7c5282009-12-18 10:40:03 +0000240 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
241 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000242 break;
243
244 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000245 if (CPlusPlus) {
246 IDNS = Decl::IDNS_Type;
247
248 // When looking for a redeclaration of a tag name, we add:
249 // 1) TagFriend to find undeclared friend decls
250 // 2) Namespace because they can't "overload" with tag decls.
251 // 3) Tag because it includes class templates, which can't
252 // "overload" with tag decls.
253 if (Redeclaration)
254 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
255 } else {
256 IDNS = Decl::IDNS_Tag;
257 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000258 break;
259
260 case Sema::LookupMemberName:
261 IDNS = Decl::IDNS_Member;
262 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000263 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000264 break;
265
266 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000267 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
268 break;
269
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000270 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000271 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000272 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000273
John McCall9f54ad42009-12-10 09:41:52 +0000274 case Sema::LookupUsingDeclName:
275 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
276 | Decl::IDNS_Member | Decl::IDNS_Using;
277 break;
278
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000279 case Sema::LookupObjCProtocolName:
280 IDNS = Decl::IDNS_ObjCProtocol;
281 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000282 }
283 return IDNS;
284}
285
John McCall1d7c5282009-12-18 10:40:03 +0000286void LookupResult::configure() {
287 IDNS = getIDNS(LookupKind,
288 SemaRef.getLangOptions().CPlusPlus,
289 isForRedeclaration());
290 IsAcceptableFn = getResultFilter(LookupKind);
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000291
292 // If we're looking for one of the allocation or deallocation
293 // operators, make sure that the implicitly-declared new and delete
294 // operators can be found.
295 if (!isForRedeclaration()) {
296 switch (Name.getCXXOverloadedOperator()) {
297 case OO_New:
298 case OO_Delete:
299 case OO_Array_New:
300 case OO_Array_Delete:
301 SemaRef.DeclareGlobalNewDelete();
302 break;
303
304 default:
305 break;
306 }
307 }
John McCall1d7c5282009-12-18 10:40:03 +0000308}
309
John McCallf36e02d2009-10-09 21:13:30 +0000310// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000311void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000312 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000313}
314
John McCall7453ed42009-11-22 00:44:51 +0000315/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000316void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000317 unsigned N = Decls.size();
John McCall9f54ad42009-12-10 09:41:52 +0000318
John McCallf36e02d2009-10-09 21:13:30 +0000319 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000320 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000321 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000322 return;
323 }
324
John McCall7453ed42009-11-22 00:44:51 +0000325 // If there's a single decl, we need to examine it to decide what
326 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000327 if (N == 1) {
John McCalleec51cf2010-01-20 00:46:10 +0000328 if (isa<FunctionTemplateDecl>(*Decls.begin()))
John McCall7453ed42009-11-22 00:44:51 +0000329 ResultKind = FoundOverloaded;
John McCalleec51cf2010-01-20 00:46:10 +0000330 else if (isa<UnresolvedUsingValueDecl>(*Decls.begin()))
John McCall7ba107a2009-11-18 02:36:19 +0000331 ResultKind = FoundUnresolvedValue;
332 return;
333 }
John McCallf36e02d2009-10-09 21:13:30 +0000334
John McCall6e247262009-10-10 05:48:19 +0000335 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000336 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000337
John McCallf36e02d2009-10-09 21:13:30 +0000338 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
339
340 bool Ambiguous = false;
341 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000342 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000343
344 unsigned UniqueTagIndex = 0;
345
346 unsigned I = 0;
347 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000348 NamedDecl *D = Decls[I]->getUnderlyingDecl();
349 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000350
John McCall314be4e2009-11-17 07:50:12 +0000351 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000352 // If it's not unique, pull something off the back (and
353 // continue at this index).
354 Decls[I] = Decls[--N];
John McCallf36e02d2009-10-09 21:13:30 +0000355 } else {
356 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000357
358 if (isa<UnresolvedUsingValueDecl>(D)) {
359 HasUnresolved = true;
360 } else if (isa<TagDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000361 if (HasTag)
362 Ambiguous = true;
363 UniqueTagIndex = I;
364 HasTag = true;
John McCall7453ed42009-11-22 00:44:51 +0000365 } else if (isa<FunctionTemplateDecl>(D)) {
366 HasFunction = true;
367 HasFunctionTemplate = true;
368 } else if (isa<FunctionDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000369 HasFunction = true;
370 } else {
371 if (HasNonFunction)
372 Ambiguous = true;
373 HasNonFunction = true;
374 }
375 I++;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000376 }
Mike Stump1eb44332009-09-09 15:08:12 +0000377 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000378
John McCallf36e02d2009-10-09 21:13:30 +0000379 // C++ [basic.scope.hiding]p2:
380 // A class name or enumeration name can be hidden by the name of
381 // an object, function, or enumerator declared in the same
382 // scope. If a class or enumeration name and an object, function,
383 // or enumerator are declared in the same scope (in any order)
384 // with the same name, the class or enumeration name is hidden
385 // wherever the object, function, or enumerator name is visible.
386 // But it's still an error if there are distinct tag types found,
387 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000388 if (HideTags && HasTag && !Ambiguous &&
389 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000390 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000391
John McCallf36e02d2009-10-09 21:13:30 +0000392 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000393
John McCallfda8e122009-12-03 00:58:24 +0000394 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000395 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000396
John McCallf36e02d2009-10-09 21:13:30 +0000397 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000398 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000399 else if (HasUnresolved)
400 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000401 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000402 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000403 else
John McCalla24dc2e2009-11-17 02:14:36 +0000404 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000405}
406
John McCall7d384dd2009-11-18 07:57:50 +0000407void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000408 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000409 DeclContext::lookup_iterator DI, DE;
410 for (I = P.begin(), E = P.end(); I != E; ++I)
411 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
412 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000413}
414
John McCall7d384dd2009-11-18 07:57:50 +0000415void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000416 Paths = new CXXBasePaths;
417 Paths->swap(P);
418 addDeclsFromBasePaths(*Paths);
419 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000420 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000421}
422
John McCall7d384dd2009-11-18 07:57:50 +0000423void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000424 Paths = new CXXBasePaths;
425 Paths->swap(P);
426 addDeclsFromBasePaths(*Paths);
427 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000428 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000429}
430
John McCall7d384dd2009-11-18 07:57:50 +0000431void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000432 Out << Decls.size() << " result(s)";
433 if (isAmbiguous()) Out << ", ambiguous";
434 if (Paths) Out << ", base paths present";
435
436 for (iterator I = begin(), E = end(); I != E; ++I) {
437 Out << "\n";
438 (*I)->print(Out, 2);
439 }
440}
441
Douglas Gregor85910982010-02-12 05:48:04 +0000442/// \brief Lookup a builtin function, when name lookup would otherwise
443/// fail.
444static bool LookupBuiltin(Sema &S, LookupResult &R) {
445 Sema::LookupNameKind NameKind = R.getLookupKind();
446
447 // If we didn't find a use of this identifier, and if the identifier
448 // corresponds to a compiler builtin, create the decl object for the builtin
449 // now, injecting it into translation unit scope, and return it.
450 if (NameKind == Sema::LookupOrdinaryName ||
451 NameKind == Sema::LookupRedeclarationWithLinkage) {
452 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
453 if (II) {
454 // If this is a builtin on this (or all) targets, create the decl.
455 if (unsigned BuiltinID = II->getBuiltinID()) {
456 // In C++, we don't have any predefined library functions like
457 // 'malloc'. Instead, we'll just error.
458 if (S.getLangOptions().CPlusPlus &&
459 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
460 return false;
461
462 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
463 S.TUScope, R.isForRedeclaration(),
464 R.getNameLoc());
465 if (D)
466 R.addDecl(D);
467 return (D != NULL);
468 }
469 }
470 }
471
472 return false;
473}
474
John McCallf36e02d2009-10-09 21:13:30 +0000475// Adds all qualifying matches for a name within a decl context to the
476// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000477static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000478 bool Found = false;
479
John McCalld7be78a2009-11-10 07:01:13 +0000480 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000481 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000482 NamedDecl *D = *I;
483 if (R.isAcceptableDecl(D)) {
484 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000485 Found = true;
486 }
487 }
John McCallf36e02d2009-10-09 21:13:30 +0000488
Douglas Gregor85910982010-02-12 05:48:04 +0000489 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
490 return true;
491
Douglas Gregor48026d22010-01-11 18:40:55 +0000492 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000493 != DeclarationName::CXXConversionFunctionName ||
494 R.getLookupName().getCXXNameType()->isDependentType() ||
495 !isa<CXXRecordDecl>(DC))
496 return Found;
497
498 // C++ [temp.mem]p6:
499 // A specialization of a conversion function template is not found by
500 // name lookup. Instead, any conversion function templates visible in the
501 // context of the use are considered. [...]
502 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
503 if (!Record->isDefinition())
504 return Found;
505
506 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
507 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
508 UEnd = Unresolved->end(); U != UEnd; ++U) {
509 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
510 if (!ConvTemplate)
511 continue;
512
513 // When we're performing lookup for the purposes of redeclaration, just
514 // add the conversion function template. When we deduce template
515 // arguments for specializations, we'll end up unifying the return
516 // type of the new declaration with the type of the function template.
517 if (R.isForRedeclaration()) {
518 R.addDecl(ConvTemplate);
519 Found = true;
520 continue;
521 }
522
Douglas Gregor48026d22010-01-11 18:40:55 +0000523 // C++ [temp.mem]p6:
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000524 // [...] For each such operator, if argument deduction succeeds
525 // (14.9.2.3), the resulting specialization is used as if found by
526 // name lookup.
527 //
528 // When referencing a conversion function for any purpose other than
529 // a redeclaration (such that we'll be building an expression with the
530 // result), perform template argument deduction and place the
531 // specialization into the result set. We do this to avoid forcing all
532 // callers to perform special deduction for conversion functions.
John McCall5769d612010-02-08 23:07:23 +0000533 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000534 FunctionDecl *Specialization = 0;
535
536 const FunctionProtoType *ConvProto
537 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
538 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000539
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000540 // Compute the type of the function that we would expect the conversion
541 // function to have, if it were to match the name given.
542 // FIXME: Calling convention!
Rafael Espindola264ba482010-03-30 20:24:48 +0000543 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000544 QualType ExpectedType
545 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
546 0, 0, ConvProto->isVariadic(),
547 ConvProto->getTypeQuals(),
548 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000549 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000550
551 // Perform template argument deduction against the type that we would
552 // expect the function to have.
553 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
554 Specialization, Info)
555 == Sema::TDK_Success) {
556 R.addDecl(Specialization);
557 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000558 }
559 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000560
John McCallf36e02d2009-10-09 21:13:30 +0000561 return Found;
562}
563
John McCalld7be78a2009-11-10 07:01:13 +0000564// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000565static bool
Douglas Gregor85910982010-02-12 05:48:04 +0000566CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
567 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000568
569 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
570
John McCalld7be78a2009-11-10 07:01:13 +0000571 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000572 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000573
John McCalld7be78a2009-11-10 07:01:13 +0000574 // Perform direct name lookup into the namespaces nominated by the
575 // using directives whose common ancestor is this namespace.
576 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
577 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000578
John McCalld7be78a2009-11-10 07:01:13 +0000579 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000580 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000581 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000582
583 R.resolveKind();
584
585 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000586}
587
588static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000589 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000590 return Ctx->isFileContext();
591 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000592}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000593
Douglas Gregor711be1e2010-03-15 14:33:29 +0000594// Find the next outer declaration context from this scope. This
595// routine actually returns the semantic outer context, which may
596// differ from the lexical context (encoded directly in the Scope
597// stack) when we are parsing a member of a class template. In this
598// case, the second element of the pair will be true, to indicate that
599// name lookup should continue searching in this semantic context when
600// it leaves the current template parameter scope.
601static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
602 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
603 DeclContext *Lexical = 0;
604 for (Scope *OuterS = S->getParent(); OuterS;
605 OuterS = OuterS->getParent()) {
606 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000607 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000608 break;
609 }
610 }
611
612 // C++ [temp.local]p8:
613 // In the definition of a member of a class template that appears
614 // outside of the namespace containing the class template
615 // definition, the name of a template-parameter hides the name of
616 // a member of this namespace.
617 //
618 // Example:
619 //
620 // namespace N {
621 // class C { };
622 //
623 // template<class T> class B {
624 // void f(T);
625 // };
626 // }
627 //
628 // template<class C> void N::B<C>::f(C) {
629 // C b; // C is the template parameter, not N::C
630 // }
631 //
632 // In this example, the lexical context we return is the
633 // TranslationUnit, while the semantic context is the namespace N.
634 if (!Lexical || !DC || !S->getParent() ||
635 !S->getParent()->isTemplateParamScope())
636 return std::make_pair(Lexical, false);
637
638 // Find the outermost template parameter scope.
639 // For the example, this is the scope for the template parameters of
640 // template<class C>.
641 Scope *OutermostTemplateScope = S->getParent();
642 while (OutermostTemplateScope->getParent() &&
643 OutermostTemplateScope->getParent()->isTemplateParamScope())
644 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregore942bbe2009-09-10 16:57:35 +0000645
Douglas Gregor711be1e2010-03-15 14:33:29 +0000646 // Find the namespace context in which the original scope occurs. In
647 // the example, this is namespace N.
648 DeclContext *Semantic = DC;
649 while (!Semantic->isFileContext())
650 Semantic = Semantic->getParent();
651
652 // Find the declaration context just outside of the template
653 // parameter scope. This is the context in which the template is
654 // being lexically declaration (a namespace context). In the
655 // example, this is the global scope.
656 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
657 Lexical->Encloses(Semantic))
658 return std::make_pair(Semantic, true);
659
660 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000661}
662
John McCalla24dc2e2009-11-17 02:14:36 +0000663bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000664 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000665
666 DeclarationName Name = R.getLookupName();
667
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000668 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000669 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000670 I = IdResolver.begin(Name),
671 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000672
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000673 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000674 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000675 // ...During unqualified name lookup (3.4.1), the names appear as if
676 // they were declared in the nearest enclosing namespace which contains
677 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000678 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000679 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000680 //
681 // For example:
682 // namespace A { int i; }
683 // void foo() {
684 // int i;
685 // {
686 // using namespace A;
687 // ++i; // finds local 'i', A::i appears at global scope
688 // }
689 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000690 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000691 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000692 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000693 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000694 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000695 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000696 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000697 Found = true;
698 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000699 }
700 }
John McCallf36e02d2009-10-09 21:13:30 +0000701 if (Found) {
702 R.resolveKind();
703 return true;
704 }
705
Douglas Gregor711be1e2010-03-15 14:33:29 +0000706 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
707 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
708 S->getParent() && !S->getParent()->isTemplateParamScope()) {
709 // We've just searched the last template parameter scope and
710 // found nothing, so look into the the contexts between the
711 // lexical and semantic declaration contexts returned by
712 // findOuterContext(). This implements the name lookup behavior
713 // of C++ [temp.local]p8.
714 Ctx = OutsideOfTemplateParamDC;
715 OutsideOfTemplateParamDC = 0;
716 }
717
718 if (Ctx) {
719 DeclContext *OuterCtx;
720 bool SearchAfterTemplateScope;
721 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
722 if (SearchAfterTemplateScope)
723 OutsideOfTemplateParamDC = OuterCtx;
724
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000725 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000726 // We do not directly look into transparent contexts, since
727 // those entities will be found in the nearest enclosing
728 // non-transparent context.
729 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000730 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000731
732 // We do not look directly into function or method contexts,
733 // since all of the local variables and parameters of the
734 // function/method are present within the Scope.
735 if (Ctx->isFunctionOrMethod()) {
736 // If we have an Objective-C instance method, look for ivars
737 // in the corresponding interface.
738 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
739 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
740 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
741 ObjCInterfaceDecl *ClassDeclared;
742 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
743 Name.getAsIdentifierInfo(),
744 ClassDeclared)) {
745 if (R.isAcceptableDecl(Ivar)) {
746 R.addDecl(Ivar);
747 R.resolveKind();
748 return true;
749 }
750 }
751 }
752 }
753
754 continue;
755 }
756
Douglas Gregore942bbe2009-09-10 16:57:35 +0000757 // Perform qualified name lookup into this context.
758 // FIXME: In some cases, we know that every name that could be found by
759 // this qualified name lookup will also be on the identifier chain. For
760 // example, inside a class without any base classes, we never need to
761 // perform qualified lookup because all of the members are on top of the
762 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000763 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000764 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000765 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000766 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000767 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000768
John McCalld7be78a2009-11-10 07:01:13 +0000769 // Stop if we ran out of scopes.
770 // FIXME: This really, really shouldn't be happening.
771 if (!S) return false;
772
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000773 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000774 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000775 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000776 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
777 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000778
John McCalld7be78a2009-11-10 07:01:13 +0000779 UnqualUsingDirectiveSet UDirs;
780 UDirs.visitScopeChain(Initial, S);
781 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000782
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000783 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000784 // Unqualified name lookup in C++ requires looking into scopes
785 // that aren't strictly lexical, and therefore we walk through the
786 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000787
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000788 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000789 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000790 if (Ctx && Ctx->isTransparentContext())
Douglas Gregora24eb4e2009-08-24 18:55:03 +0000791 continue;
792
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000793 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000794 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000795 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000796 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000797 // We found something. Look for anything else in our scope
798 // with this same name and in an acceptable identifier
799 // namespace, so that we can construct an overload set if we
800 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000801 Found = true;
802 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000803 }
804 }
805
Douglas Gregor711be1e2010-03-15 14:33:29 +0000806 // If we have a context, and it's not a context stashed in the
807 // template parameter scope for an out-of-line definition, also
808 // look into that context.
809 if (Ctx && !(Found && S && S->isTemplateParamScope())) {
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000810 assert(Ctx->isFileContext() &&
811 "We should have been looking only at file context here already.");
812
813 // Look into context considering using-directives.
Douglas Gregor85910982010-02-12 05:48:04 +0000814 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000815 Found = true;
816 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000817
John McCallf36e02d2009-10-09 21:13:30 +0000818 if (Found) {
819 R.resolveKind();
820 return true;
821 }
822
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000823 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000824 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000825 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000826
John McCallf36e02d2009-10-09 21:13:30 +0000827 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000828}
829
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000830/// @brief Perform unqualified name lookup starting from a given
831/// scope.
832///
833/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
834/// used to find names within the current scope. For example, 'x' in
835/// @code
836/// int x;
837/// int f() {
838/// return x; // unqualified name look finds 'x' in the global scope
839/// }
840/// @endcode
841///
842/// Different lookup criteria can find different names. For example, a
843/// particular scope can have both a struct and a function of the same
844/// name, and each can be found by certain lookup criteria. For more
845/// information about lookup criteria, see the documentation for the
846/// class LookupCriteria.
847///
848/// @param S The scope from which unqualified name lookup will
849/// begin. If the lookup criteria permits, name lookup may also search
850/// in the parent scopes.
851///
852/// @param Name The name of the entity that we are searching for.
853///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000854/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +0000855/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +0000856/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000857///
858/// @returns The result of name lookup, which includes zero or more
859/// declarations and possibly additional information used to diagnose
860/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000861bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
862 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +0000863 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000864
John McCalla24dc2e2009-11-17 02:14:36 +0000865 LookupNameKind NameKind = R.getLookupKind();
866
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000867 if (!getLangOptions().CPlusPlus) {
868 // Unqualified name lookup in C/Objective-C is purely lexical, so
869 // search in the declarations attached to the name.
870
John McCall1d7c5282009-12-18 10:40:03 +0000871 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000872 // Find the nearest non-transparent declaration scope.
873 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000874 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000875 static_cast<DeclContext *>(S->getEntity())
876 ->isTransparentContext()))
877 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000878 }
879
John McCall1d7c5282009-12-18 10:40:03 +0000880 unsigned IDNS = R.getIdentifierNamespace();
881
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000882 // Scan up the scope chain looking for a decl that matches this
883 // identifier that is in the appropriate namespace. This search
884 // should not take long, as shadowing of names is uncommon, and
885 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000886 bool LeftStartingScope = false;
887
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000888 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +0000889 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000890 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000891 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000892 if (NameKind == LookupRedeclarationWithLinkage) {
893 // Determine whether this (or a previous) declaration is
894 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000895 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000896 LeftStartingScope = true;
897
898 // If we found something outside of our starting scope that
899 // does not have linkage, skip it.
900 if (LeftStartingScope && !((*I)->hasLinkage()))
901 continue;
902 }
903
John McCallf36e02d2009-10-09 21:13:30 +0000904 R.addDecl(*I);
905
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000906 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000907 // If this declaration has the "overloadable" attribute, we
908 // might have a set of overloaded functions.
909
910 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000911 while (!(S->getFlags() & Scope::DeclScope) ||
912 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000913 S = S->getParent();
914
915 // Find the last declaration in this scope (with the same
916 // name, naturally).
917 IdentifierResolver::iterator LastI = I;
918 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000919 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000920 break;
John McCallf36e02d2009-10-09 21:13:30 +0000921 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000922 }
Douglas Gregorf9201e02009-02-11 23:02:49 +0000923 }
924
John McCallf36e02d2009-10-09 21:13:30 +0000925 R.resolveKind();
926
927 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000928 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000929 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000930 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000931 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +0000932 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000933 }
934
935 // If we didn't find a use of this identifier, and if the identifier
936 // corresponds to a compiler builtin, create the decl object for the builtin
937 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +0000938 if (AllowBuiltinCreation)
939 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000940
John McCallf36e02d2009-10-09 21:13:30 +0000941 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000942}
943
John McCall6e247262009-10-10 05:48:19 +0000944/// @brief Perform qualified name lookup in the namespaces nominated by
945/// using directives by the given context.
946///
947/// C++98 [namespace.qual]p2:
948/// Given X::m (where X is a user-declared namespace), or given ::m
949/// (where X is the global namespace), let S be the set of all
950/// declarations of m in X and in the transitive closure of all
951/// namespaces nominated by using-directives in X and its used
952/// namespaces, except that using-directives are ignored in any
953/// namespace, including X, directly containing one or more
954/// declarations of m. No namespace is searched more than once in
955/// the lookup of a name. If S is the empty set, the program is
956/// ill-formed. Otherwise, if S has exactly one member, or if the
957/// context of the reference is a using-declaration
958/// (namespace.udecl), S is the required set of declarations of
959/// m. Otherwise if the use of m is not one that allows a unique
960/// declaration to be chosen from S, the program is ill-formed.
961/// C++98 [namespace.qual]p5:
962/// During the lookup of a qualified namespace member name, if the
963/// lookup finds more than one declaration of the member, and if one
964/// declaration introduces a class name or enumeration name and the
965/// other declarations either introduce the same object, the same
966/// enumerator or a set of functions, the non-type name hides the
967/// class or enumeration name if and only if the declarations are
968/// from the same namespace; otherwise (the declarations are from
969/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +0000970static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +0000971 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +0000972 assert(StartDC->isFileContext() && "start context is not a file context");
973
974 DeclContext::udir_iterator I = StartDC->using_directives_begin();
975 DeclContext::udir_iterator E = StartDC->using_directives_end();
976
977 if (I == E) return false;
978
979 // We have at least added all these contexts to the queue.
980 llvm::DenseSet<DeclContext*> Visited;
981 Visited.insert(StartDC);
982
983 // We have not yet looked into these namespaces, much less added
984 // their "using-children" to the queue.
985 llvm::SmallVector<NamespaceDecl*, 8> Queue;
986
987 // We have already looked into the initial namespace; seed the queue
988 // with its using-children.
989 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +0000990 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +0000991 if (Visited.insert(ND).second)
992 Queue.push_back(ND);
993 }
994
995 // The easiest way to implement the restriction in [namespace.qual]p5
996 // is to check whether any of the individual results found a tag
997 // and, if so, to declare an ambiguity if the final result is not
998 // a tag.
999 bool FoundTag = false;
1000 bool FoundNonTag = false;
1001
John McCall7d384dd2009-11-18 07:57:50 +00001002 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001003
1004 bool Found = false;
1005 while (!Queue.empty()) {
1006 NamespaceDecl *ND = Queue.back();
1007 Queue.pop_back();
1008
1009 // We go through some convolutions here to avoid copying results
1010 // between LookupResults.
1011 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001012 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001013 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001014
1015 if (FoundDirect) {
1016 // First do any local hiding.
1017 DirectR.resolveKind();
1018
1019 // If the local result is a tag, remember that.
1020 if (DirectR.isSingleTagDecl())
1021 FoundTag = true;
1022 else
1023 FoundNonTag = true;
1024
1025 // Append the local results to the total results if necessary.
1026 if (UseLocal) {
1027 R.addAllDecls(LocalR);
1028 LocalR.clear();
1029 }
1030 }
1031
1032 // If we find names in this namespace, ignore its using directives.
1033 if (FoundDirect) {
1034 Found = true;
1035 continue;
1036 }
1037
1038 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1039 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1040 if (Visited.insert(Nom).second)
1041 Queue.push_back(Nom);
1042 }
1043 }
1044
1045 if (Found) {
1046 if (FoundTag && FoundNonTag)
1047 R.setAmbiguousQualifiedTagHiding();
1048 else
1049 R.resolveKind();
1050 }
1051
1052 return Found;
1053}
1054
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001055/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001056///
1057/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1058/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001059/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001060///
1061/// Different lookup criteria can find different names. For example, a
1062/// particular scope can have both a struct and a function of the same
1063/// name, and each can be found by certain lookup criteria. For more
1064/// information about lookup criteria, see the documentation for the
1065/// class LookupCriteria.
1066///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001067/// \param R captures both the lookup criteria and any lookup results found.
1068///
1069/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001070/// search. If the lookup criteria permits, name lookup may also search
1071/// in the parent contexts or (for C++ classes) base classes.
1072///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001073/// \param InUnqualifiedLookup true if this is qualified name lookup that
1074/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001075///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001076/// \returns true if lookup succeeded, false if it failed.
1077bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1078 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001079 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001080
John McCalla24dc2e2009-11-17 02:14:36 +00001081 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001082 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001084 // Make sure that the declaration context is complete.
1085 assert((!isa<TagDecl>(LookupCtx) ||
1086 LookupCtx->isDependentContext() ||
1087 cast<TagDecl>(LookupCtx)->isDefinition() ||
1088 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1089 ->isBeingDefined()) &&
1090 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001092 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001093 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001094 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001095 if (isa<CXXRecordDecl>(LookupCtx))
1096 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001097 return true;
1098 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001099
John McCall6e247262009-10-10 05:48:19 +00001100 // Don't descend into implied contexts for redeclarations.
1101 // C++98 [namespace.qual]p6:
1102 // In a declaration for a namespace member in which the
1103 // declarator-id is a qualified-id, given that the qualified-id
1104 // for the namespace member has the form
1105 // nested-name-specifier unqualified-id
1106 // the unqualified-id shall name a member of the namespace
1107 // designated by the nested-name-specifier.
1108 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001109 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001110 return false;
1111
John McCalla24dc2e2009-11-17 02:14:36 +00001112 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001113 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001114 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001115
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001116 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001117 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001118 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1119 if (!LookupRec)
John McCallf36e02d2009-10-09 21:13:30 +00001120 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001121
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001122 // If we're performing qualified name lookup into a dependent class,
1123 // then we are actually looking into a current instantiation. If we have any
1124 // dependent base classes, then we either have to delay lookup until
1125 // template instantiation time (at which point all bases will be available)
1126 // or we have to fail.
1127 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1128 LookupRec->hasAnyDependentBases()) {
1129 R.setNotFoundInCurrentInstantiation();
1130 return false;
1131 }
1132
Douglas Gregor7176fff2009-01-15 00:26:24 +00001133 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001134 CXXBasePaths Paths;
1135 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001136
1137 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001138 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001139 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001140 case LookupOrdinaryName:
1141 case LookupMemberName:
1142 case LookupRedeclarationWithLinkage:
1143 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1144 break;
1145
1146 case LookupTagName:
1147 BaseCallback = &CXXRecordDecl::FindTagMember;
1148 break;
John McCall9f54ad42009-12-10 09:41:52 +00001149
1150 case LookupUsingDeclName:
1151 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001152
1153 case LookupOperatorName:
1154 case LookupNamespaceName:
1155 case LookupObjCProtocolName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001156 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001157 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001158
1159 case LookupNestedNameSpecifierName:
1160 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1161 break;
1162 }
1163
John McCalla24dc2e2009-11-17 02:14:36 +00001164 if (!LookupRec->lookupInBases(BaseCallback,
1165 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001166 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001167
John McCall92f88312010-01-23 00:46:32 +00001168 R.setNamingClass(LookupRec);
1169
Douglas Gregor7176fff2009-01-15 00:26:24 +00001170 // C++ [class.member.lookup]p2:
1171 // [...] If the resulting set of declarations are not all from
1172 // sub-objects of the same type, or the set has a nonstatic member
1173 // and includes members from distinct sub-objects, there is an
1174 // ambiguity and the program is ill-formed. Otherwise that set is
1175 // the result of the lookup.
1176 // FIXME: support using declarations!
1177 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001178 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001179 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001180 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001181 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001182 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001183
John McCall46460a62010-01-20 21:53:11 +00001184 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1185 // across all paths.
1186 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1187
Douglas Gregor7176fff2009-01-15 00:26:24 +00001188 // Determine whether we're looking at a distinct sub-object or not.
1189 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001190 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001191 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1192 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00001193 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001194 != Context.getCanonicalType(PathElement.Base->getType())) {
1195 // We found members of the given name in two subobjects of
1196 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001197 R.setAmbiguousBaseSubobjectTypes(Paths);
1198 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001199 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1200 // We have a different subobject of the same type.
1201
1202 // C++ [class.member.lookup]p5:
1203 // A static member, a nested type or an enumerator defined in
1204 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001205 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001206 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001207 if (isa<VarDecl>(FirstDecl) ||
1208 isa<TypeDecl>(FirstDecl) ||
1209 isa<EnumConstantDecl>(FirstDecl))
1210 continue;
1211
1212 if (isa<CXXMethodDecl>(FirstDecl)) {
1213 // Determine whether all of the methods are static.
1214 bool AllMethodsAreStatic = true;
1215 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1216 Func != Path->Decls.second; ++Func) {
1217 if (!isa<CXXMethodDecl>(*Func)) {
1218 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1219 break;
1220 }
1221
1222 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1223 AllMethodsAreStatic = false;
1224 break;
1225 }
1226 }
1227
1228 if (AllMethodsAreStatic)
1229 continue;
1230 }
1231
1232 // We have found a nonstatic member name in multiple, distinct
1233 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001234 R.setAmbiguousBaseSubobjects(Paths);
1235 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001236 }
1237 }
1238
1239 // Lookup in a base class succeeded; return these results.
1240
John McCallf36e02d2009-10-09 21:13:30 +00001241 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001242 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1243 NamedDecl *D = *I;
1244 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1245 D->getAccess());
1246 R.addDecl(D, AS);
1247 }
John McCallf36e02d2009-10-09 21:13:30 +00001248 R.resolveKind();
1249 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001250}
1251
1252/// @brief Performs name lookup for a name that was parsed in the
1253/// source code, and may contain a C++ scope specifier.
1254///
1255/// This routine is a convenience routine meant to be called from
1256/// contexts that receive a name and an optional C++ scope specifier
1257/// (e.g., "N::M::x"). It will then perform either qualified or
1258/// unqualified name lookup (with LookupQualifiedName or LookupName,
1259/// respectively) on the given name and return those results.
1260///
1261/// @param S The scope from which unqualified name lookup will
1262/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001263///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001264/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001265///
1266/// @param Name The name of the entity that name lookup will
1267/// search for.
1268///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001269/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001270/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001271/// C library functions (like "malloc") are implicitly declared.
1272///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001273/// @param EnteringContext Indicates whether we are going to enter the
1274/// context of the scope-specifier SS (if present).
1275///
John McCallf36e02d2009-10-09 21:13:30 +00001276/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001277bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001278 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001279 if (SS && SS->isInvalid()) {
1280 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001281 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001282 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001283 }
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Douglas Gregor495c35d2009-08-25 22:51:20 +00001285 if (SS && SS->isSet()) {
1286 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001287 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001288 // contex, and will perform name lookup in that context.
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001289 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCallf36e02d2009-10-09 21:13:30 +00001290 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001291
John McCalla24dc2e2009-11-17 02:14:36 +00001292 R.setContextRange(SS->getRange());
1293
1294 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001295 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001296
Douglas Gregor495c35d2009-08-25 22:51:20 +00001297 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001298 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001299 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001300 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001301 }
1302
Mike Stump1eb44332009-09-09 15:08:12 +00001303 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001304 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001305}
1306
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001307
Douglas Gregor7176fff2009-01-15 00:26:24 +00001308/// @brief Produce a diagnostic describing the ambiguity that resulted
1309/// from name lookup.
1310///
1311/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001312///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001313/// @param Name The name of the entity that name lookup was
1314/// searching for.
1315///
1316/// @param NameLoc The location of the name within the source code.
1317///
1318/// @param LookupRange A source range that provides more
1319/// source-location information concerning the lookup itself. For
1320/// example, this range might highlight a nested-name-specifier that
1321/// precedes the name.
1322///
1323/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001324bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001325 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1326
John McCalla24dc2e2009-11-17 02:14:36 +00001327 DeclarationName Name = Result.getLookupName();
1328 SourceLocation NameLoc = Result.getNameLoc();
1329 SourceRange LookupRange = Result.getContextRange();
1330
John McCall6e247262009-10-10 05:48:19 +00001331 switch (Result.getAmbiguityKind()) {
1332 case LookupResult::AmbiguousBaseSubobjects: {
1333 CXXBasePaths *Paths = Result.getBasePaths();
1334 QualType SubobjectType = Paths->front().back().Base->getType();
1335 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1336 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1337 << LookupRange;
1338
1339 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1340 while (isa<CXXMethodDecl>(*Found) &&
1341 cast<CXXMethodDecl>(*Found)->isStatic())
1342 ++Found;
1343
1344 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1345
1346 return true;
1347 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001348
John McCall6e247262009-10-10 05:48:19 +00001349 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001350 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1351 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001352
1353 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001354 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001355 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1356 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001357 Path != PathEnd; ++Path) {
1358 Decl *D = *Path->Decls.first;
1359 if (DeclsPrinted.insert(D).second)
1360 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1361 }
1362
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001363 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001364 }
1365
John McCall6e247262009-10-10 05:48:19 +00001366 case LookupResult::AmbiguousTagHiding: {
1367 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001368
John McCall6e247262009-10-10 05:48:19 +00001369 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1370
1371 LookupResult::iterator DI, DE = Result.end();
1372 for (DI = Result.begin(); DI != DE; ++DI)
1373 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1374 TagDecls.insert(TD);
1375 Diag(TD->getLocation(), diag::note_hidden_tag);
1376 }
1377
1378 for (DI = Result.begin(); DI != DE; ++DI)
1379 if (!isa<TagDecl>(*DI))
1380 Diag((*DI)->getLocation(), diag::note_hiding_object);
1381
1382 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001383 LookupResult::Filter F = Result.makeFilter();
1384 while (F.hasNext()) {
1385 if (TagDecls.count(F.next()))
1386 F.erase();
1387 }
1388 F.done();
John McCall6e247262009-10-10 05:48:19 +00001389
1390 return true;
1391 }
1392
1393 case LookupResult::AmbiguousReference: {
1394 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001395
John McCall6e247262009-10-10 05:48:19 +00001396 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1397 for (; DI != DE; ++DI)
1398 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001399
John McCall6e247262009-10-10 05:48:19 +00001400 return true;
1401 }
1402 }
1403
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001404 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001405 return true;
1406}
Douglas Gregorfa047642009-02-04 00:32:51 +00001407
Mike Stump1eb44332009-09-09 15:08:12 +00001408static void
1409addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001410 ASTContext &Context,
1411 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001412 Sema::AssociatedClassSet &AssociatedClasses);
1413
1414static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1415 DeclContext *Ctx) {
1416 if (Ctx->isFileContext())
1417 Namespaces.insert(Ctx);
1418}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001419
Mike Stump1eb44332009-09-09 15:08:12 +00001420// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001421// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001422static void
1423addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001424 ASTContext &Context,
1425 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001426 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001427 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001428 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001429 switch (Arg.getKind()) {
1430 case TemplateArgument::Null:
1431 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Douglas Gregor69be8d62009-07-08 07:51:57 +00001433 case TemplateArgument::Type:
1434 // [...] the namespaces and classes associated with the types of the
1435 // template arguments provided for template type parameters (excluding
1436 // template template parameters)
1437 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1438 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001439 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001440 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Douglas Gregor788cd062009-11-11 01:00:40 +00001442 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001443 // [...] the namespaces in which any template template arguments are
1444 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001445 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001446 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001447 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001448 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001449 DeclContext *Ctx = ClassTemplate->getDeclContext();
1450 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1451 AssociatedClasses.insert(EnclosingClass);
1452 // Add the associated namespace for this class.
1453 while (Ctx->isRecord())
1454 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001455 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001456 }
1457 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001458 }
1459
1460 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001461 case TemplateArgument::Integral:
1462 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001463 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001464 // associated namespaces. ]
1465 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Douglas Gregor69be8d62009-07-08 07:51:57 +00001467 case TemplateArgument::Pack:
1468 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1469 PEnd = Arg.pack_end();
1470 P != PEnd; ++P)
1471 addAssociatedClassesAndNamespaces(*P, Context,
1472 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001473 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001474 break;
1475 }
1476}
1477
Douglas Gregorfa047642009-02-04 00:32:51 +00001478// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001479// argument-dependent lookup with an argument of class type
1480// (C++ [basic.lookup.koenig]p2).
1481static void
1482addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregorfa047642009-02-04 00:32:51 +00001483 ASTContext &Context,
1484 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001485 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001486 // C++ [basic.lookup.koenig]p2:
1487 // [...]
1488 // -- If T is a class type (including unions), its associated
1489 // classes are: the class itself; the class of which it is a
1490 // member, if any; and its direct and indirect base
1491 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001492 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001493
1494 // Add the class of which it is a member, if any.
1495 DeclContext *Ctx = Class->getDeclContext();
1496 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1497 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001498 // Add the associated namespace for this class.
1499 while (Ctx->isRecord())
1500 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001501 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Douglas Gregorfa047642009-02-04 00:32:51 +00001503 // Add the class itself. If we've already seen this class, we don't
1504 // need to visit base classes.
1505 if (!AssociatedClasses.insert(Class))
1506 return;
1507
Mike Stump1eb44332009-09-09 15:08:12 +00001508 // -- If T is a template-id, its associated namespaces and classes are
1509 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001510 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001511 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001512 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001513 // namespaces in which any template template arguments are defined; and
1514 // the classes in which any member templates used as template template
1515 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001516 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001517 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001518 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1519 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1520 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1521 AssociatedClasses.insert(EnclosingClass);
1522 // Add the associated namespace for this class.
1523 while (Ctx->isRecord())
1524 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001525 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Douglas Gregor69be8d62009-07-08 07:51:57 +00001527 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1528 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1529 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1530 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001531 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001532 }
Mike Stump1eb44332009-09-09 15:08:12 +00001533
John McCall86ff3082010-02-04 22:26:26 +00001534 // Only recurse into base classes for complete types.
1535 if (!Class->hasDefinition()) {
1536 // FIXME: we might need to instantiate templates here
1537 return;
1538 }
1539
Douglas Gregorfa047642009-02-04 00:32:51 +00001540 // Add direct and indirect base classes along with their associated
1541 // namespaces.
1542 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1543 Bases.push_back(Class);
1544 while (!Bases.empty()) {
1545 // Pop this class off the stack.
1546 Class = Bases.back();
1547 Bases.pop_back();
1548
1549 // Visit the base classes.
1550 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1551 BaseEnd = Class->bases_end();
1552 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001553 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001554 // In dependent contexts, we do ADL twice, and the first time around,
1555 // the base type might be a dependent TemplateSpecializationType, or a
1556 // TemplateTypeParmType. If that happens, simply ignore it.
1557 // FIXME: If we want to support export, we probably need to add the
1558 // namespace of the template in a TemplateSpecializationType, or even
1559 // the classes and namespaces of known non-dependent arguments.
1560 if (!BaseType)
1561 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001562 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1563 if (AssociatedClasses.insert(BaseDecl)) {
1564 // Find the associated namespace for this base class.
1565 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1566 while (BaseCtx->isRecord())
1567 BaseCtx = BaseCtx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001568 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001569
1570 // Make sure we visit the bases of this base class.
1571 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1572 Bases.push_back(BaseDecl);
1573 }
1574 }
1575 }
1576}
1577
1578// \brief Add the associated classes and namespaces for
1579// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001580// (C++ [basic.lookup.koenig]p2).
1581static void
1582addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregorfa047642009-02-04 00:32:51 +00001583 ASTContext &Context,
1584 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001585 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001586 // C++ [basic.lookup.koenig]p2:
1587 //
1588 // For each argument type T in the function call, there is a set
1589 // of zero or more associated namespaces and a set of zero or more
1590 // associated classes to be considered. The sets of namespaces and
1591 // classes is determined entirely by the types of the function
1592 // arguments (and the namespace of any template template
1593 // argument). Typedef names and using-declarations used to specify
1594 // the types do not contribute to this set. The sets of namespaces
1595 // and classes are determined in the following way:
1596 T = Context.getCanonicalType(T).getUnqualifiedType();
1597
1598 // -- If T is a pointer to U or an array of U, its associated
Mike Stump1eb44332009-09-09 15:08:12 +00001599 // namespaces and classes are those associated with U.
Douglas Gregorfa047642009-02-04 00:32:51 +00001600 //
1601 // We handle this by unwrapping pointer and array types immediately,
1602 // to avoid unnecessary recursion.
1603 while (true) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001604 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001605 T = Ptr->getPointeeType();
1606 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1607 T = Ptr->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001608 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001609 break;
1610 }
1611
1612 // -- If T is a fundamental type, its associated sets of
1613 // namespaces and classes are both empty.
John McCall183700f2009-09-21 23:43:11 +00001614 if (T->getAs<BuiltinType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001615 return;
1616
1617 // -- If T is a class type (including unions), its associated
1618 // classes are: the class itself; the class of which it is a
1619 // member, if any; and its direct and indirect base
1620 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001621 // which its associated classes are defined.
Ted Kremenek6217b802009-07-29 21:53:49 +00001622 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001623 if (CXXRecordDecl *ClassDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001624 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001625 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1626 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001627 AssociatedClasses);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001628 return;
1629 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001630
1631 // -- If T is an enumeration type, its associated namespace is
1632 // the namespace in which it is defined. If it is class
1633 // member, its associated class is the member’s class; else
Mike Stump1eb44332009-09-09 15:08:12 +00001634 // it has no associated class.
John McCall183700f2009-09-21 23:43:11 +00001635 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001636 EnumDecl *Enum = EnumT->getDecl();
1637
1638 DeclContext *Ctx = Enum->getDeclContext();
1639 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1640 AssociatedClasses.insert(EnclosingClass);
1641
1642 // Add the associated namespace for this class.
1643 while (Ctx->isRecord())
1644 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001645 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001646
1647 return;
1648 }
1649
1650 // -- If T is a function type, its associated namespaces and
1651 // classes are those associated with the function parameter
1652 // types and those associated with the return type.
John McCall183700f2009-09-21 23:43:11 +00001653 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001654 // Return type
John McCall183700f2009-09-21 23:43:11 +00001655 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001656 Context,
John McCall6ff07852009-08-07 22:18:02 +00001657 AssociatedNamespaces, AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001658
John McCall183700f2009-09-21 23:43:11 +00001659 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001660 if (!Proto)
1661 return;
1662
1663 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001664 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001665 ArgEnd = Proto->arg_type_end();
Douglas Gregorfa047642009-02-04 00:32:51 +00001666 Arg != ArgEnd; ++Arg)
1667 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCall6ff07852009-08-07 22:18:02 +00001668 AssociatedNamespaces, AssociatedClasses);
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Douglas Gregorfa047642009-02-04 00:32:51 +00001670 return;
1671 }
1672
1673 // -- If T is a pointer to a member function of a class X, its
1674 // associated namespaces and classes are those associated
1675 // with the function parameter types and return type,
Mike Stump1eb44332009-09-09 15:08:12 +00001676 // together with those associated with X.
Douglas Gregorfa047642009-02-04 00:32:51 +00001677 //
1678 // -- If T is a pointer to a data member of class X, its
1679 // associated namespaces and classes are those associated
1680 // with the member type together with those associated with
Mike Stump1eb44332009-09-09 15:08:12 +00001681 // X.
Ted Kremenek6217b802009-07-29 21:53:49 +00001682 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001683 // Handle the type that the pointer to member points to.
1684 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1685 Context,
John McCall6ff07852009-08-07 22:18:02 +00001686 AssociatedNamespaces,
1687 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001688
1689 // Handle the class type into which this points.
Ted Kremenek6217b802009-07-29 21:53:49 +00001690 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001691 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1692 Context,
John McCall6ff07852009-08-07 22:18:02 +00001693 AssociatedNamespaces,
1694 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001695
1696 return;
1697 }
1698
1699 // FIXME: What about block pointers?
1700 // FIXME: What about Objective-C message sends?
1701}
1702
1703/// \brief Find the associated classes and namespaces for
1704/// argument-dependent lookup for a call with the given set of
1705/// arguments.
1706///
1707/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001708/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001709/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001710void
Douglas Gregorfa047642009-02-04 00:32:51 +00001711Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1712 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001713 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001714 AssociatedNamespaces.clear();
1715 AssociatedClasses.clear();
1716
1717 // C++ [basic.lookup.koenig]p2:
1718 // For each argument type T in the function call, there is a set
1719 // of zero or more associated namespaces and a set of zero or more
1720 // associated classes to be considered. The sets of namespaces and
1721 // classes is determined entirely by the types of the function
1722 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001723 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001724 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1725 Expr *Arg = Args[ArgIdx];
1726
1727 if (Arg->getType() != Context.OverloadTy) {
1728 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001729 AssociatedNamespaces,
1730 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001731 continue;
1732 }
1733
1734 // [...] In addition, if the argument is the name or address of a
1735 // set of overloaded functions and/or function templates, its
1736 // associated classes and namespaces are the union of those
1737 // associated with each of the members of the set: the namespace
1738 // in which the function or function template is defined and the
1739 // classes and namespaces associated with its (non-dependent)
1740 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001741 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001742 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1743 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1744 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001745
John McCallba135432009-11-21 08:51:07 +00001746 // TODO: avoid the copies. This should be easy when the cases
1747 // share a storage implementation.
1748 llvm::SmallVector<NamedDecl*, 8> Functions;
1749
1750 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1751 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00001752 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001753 continue;
1754
John McCallba135432009-11-21 08:51:07 +00001755 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1756 E = Functions.end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001757 // Look through any using declarations to find the underlying function.
1758 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001759
Chandler Carruthbd647292009-12-29 06:17:27 +00001760 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1761 if (!FDecl)
1762 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001763
1764 // Add the classes and namespaces associated with the parameter
1765 // types and return type of this function.
1766 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001767 AssociatedNamespaces,
1768 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001769 }
1770 }
1771}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001772
1773/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1774/// an acceptable non-member overloaded operator for a call whose
1775/// arguments have types T1 (and, if non-empty, T2). This routine
1776/// implements the check in C++ [over.match.oper]p3b2 concerning
1777/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001778static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001779IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1780 QualType T1, QualType T2,
1781 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001782 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1783 return true;
1784
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001785 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1786 return true;
1787
John McCall183700f2009-09-21 23:43:11 +00001788 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001789 if (Proto->getNumArgs() < 1)
1790 return false;
1791
1792 if (T1->isEnumeralType()) {
1793 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001794 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001795 return true;
1796 }
1797
1798 if (Proto->getNumArgs() < 2)
1799 return false;
1800
1801 if (!T2.isNull() && T2->isEnumeralType()) {
1802 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001803 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001804 return true;
1805 }
1806
1807 return false;
1808}
1809
John McCall7d384dd2009-11-18 07:57:50 +00001810NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00001811 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00001812 LookupNameKind NameKind,
1813 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00001814 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00001815 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00001816 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00001817}
1818
Douglas Gregor6e378de2009-04-23 23:18:26 +00001819/// \brief Find the protocol with the given name, if any.
Douglas Gregorc83c6872010-04-15 22:33:43 +00001820ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
1821 SourceLocation IdLoc) {
1822 Decl *D = LookupSingleName(TUScope, II, IdLoc,
1823 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001824 return cast_or_null<ObjCProtocolDecl>(D);
1825}
1826
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001827void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001828 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00001829 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001830 // C++ [over.match.oper]p3:
1831 // -- The set of non-member candidates is the result of the
1832 // unqualified lookup of operator@ in the context of the
1833 // expression according to the usual rules for name lookup in
1834 // unqualified function calls (3.4.2) except that all member
1835 // functions are ignored. However, if no operand has a class
1836 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00001837 // that have a first parameter of type T1 or "reference to
1838 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001839 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00001840 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001841 // when T2 is an enumeration type, are candidate functions.
1842 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00001843 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1844 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001846 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1847
John McCallf36e02d2009-10-09 21:13:30 +00001848 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001849 return;
1850
1851 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1852 Op != OpEnd; ++Op) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001853 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001854 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
John McCall6e266892010-01-26 03:27:55 +00001855 Functions.addDecl(FD, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00001856 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor364e0212009-06-27 21:05:07 +00001857 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1858 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00001859 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00001860 // later?
1861 if (!FunTmpl->getDeclContext()->isRecord())
John McCall6e266892010-01-26 03:27:55 +00001862 Functions.addDecl(FunTmpl, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00001863 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001864 }
1865}
1866
John McCall7edb5fd2010-01-26 07:16:45 +00001867void ADLResult::insert(NamedDecl *New) {
1868 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1869
1870 // If we haven't yet seen a decl for this key, or the last decl
1871 // was exactly this one, we're done.
1872 if (Old == 0 || Old == New) {
1873 Old = New;
1874 return;
1875 }
1876
1877 // Otherwise, decide which is a more recent redeclaration.
1878 FunctionDecl *OldFD, *NewFD;
1879 if (isa<FunctionTemplateDecl>(New)) {
1880 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1881 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1882 } else {
1883 OldFD = cast<FunctionDecl>(Old);
1884 NewFD = cast<FunctionDecl>(New);
1885 }
1886
1887 FunctionDecl *Cursor = NewFD;
1888 while (true) {
1889 Cursor = Cursor->getPreviousDeclaration();
1890
1891 // If we got to the end without finding OldFD, OldFD is the newer
1892 // declaration; leave things as they are.
1893 if (!Cursor) return;
1894
1895 // If we do find OldFD, then NewFD is newer.
1896 if (Cursor == OldFD) break;
1897
1898 // Otherwise, keep looking.
1899 }
1900
1901 Old = New;
1902}
1903
Sebastian Redl644be852009-10-23 19:23:15 +00001904void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001905 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00001906 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001907 // Find all of the associated namespaces and classes based on the
1908 // arguments we have.
1909 AssociatedNamespaceSet AssociatedNamespaces;
1910 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00001911 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00001912 AssociatedNamespaces,
1913 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001914
Sebastian Redl644be852009-10-23 19:23:15 +00001915 QualType T1, T2;
1916 if (Operator) {
1917 T1 = Args[0]->getType();
1918 if (NumArgs >= 2)
1919 T2 = Args[1]->getType();
1920 }
1921
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001922 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001923 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1924 // and let Y be the lookup set produced by argument dependent
1925 // lookup (defined as follows). If X contains [...] then Y is
1926 // empty. Otherwise Y is the set of declarations found in the
1927 // namespaces associated with the argument types as described
1928 // below. The set of declarations found by the lookup of the name
1929 // is the union of X and Y.
1930 //
1931 // Here, we compute Y and add its members to the overloaded
1932 // candidate set.
1933 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001934 NSEnd = AssociatedNamespaces.end();
1935 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001936 // When considering an associated namespace, the lookup is the
1937 // same as the lookup performed when the associated namespace is
1938 // used as a qualifier (3.4.3.2) except that:
1939 //
1940 // -- Any using-directives in the associated namespace are
1941 // ignored.
1942 //
John McCall6ff07852009-08-07 22:18:02 +00001943 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001944 // associated classes are visible within their respective
1945 // namespaces even if they are not visible during an ordinary
1946 // lookup (11.4).
1947 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00001948 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00001949 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00001950 // If the only declaration here is an ordinary friend, consider
1951 // it only if it was declared in an associated classes.
1952 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00001953 DeclContext *LexDC = D->getLexicalDeclContext();
1954 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1955 continue;
1956 }
Mike Stump1eb44332009-09-09 15:08:12 +00001957
John McCalla113e722010-01-26 06:04:06 +00001958 if (isa<UsingShadowDecl>(D))
1959 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00001960
John McCalla113e722010-01-26 06:04:06 +00001961 if (isa<FunctionDecl>(D)) {
1962 if (Operator &&
1963 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
1964 T1, T2, Context))
1965 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00001966 } else if (!isa<FunctionTemplateDecl>(D))
1967 continue;
1968
1969 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001970 }
1971 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001972}
Douglas Gregor546be3c2009-12-30 17:04:44 +00001973
1974//----------------------------------------------------------------------------
1975// Search for all visible declarations.
1976//----------------------------------------------------------------------------
1977VisibleDeclConsumer::~VisibleDeclConsumer() { }
1978
1979namespace {
1980
1981class ShadowContextRAII;
1982
1983class VisibleDeclsRecord {
1984public:
1985 /// \brief An entry in the shadow map, which is optimized to store a
1986 /// single declaration (the common case) but can also store a list
1987 /// of declarations.
1988 class ShadowMapEntry {
1989 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1990
1991 /// \brief Contains either the solitary NamedDecl * or a vector
1992 /// of declarations.
1993 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1994
1995 public:
1996 ShadowMapEntry() : DeclOrVector() { }
1997
1998 void Add(NamedDecl *ND);
1999 void Destroy();
2000
2001 // Iteration.
2002 typedef NamedDecl **iterator;
2003 iterator begin();
2004 iterator end();
2005 };
2006
2007private:
2008 /// \brief A mapping from declaration names to the declarations that have
2009 /// this name within a particular scope.
2010 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2011
2012 /// \brief A list of shadow maps, which is used to model name hiding.
2013 std::list<ShadowMap> ShadowMaps;
2014
2015 /// \brief The declaration contexts we have already visited.
2016 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2017
2018 friend class ShadowContextRAII;
2019
2020public:
2021 /// \brief Determine whether we have already visited this context
2022 /// (and, if not, note that we are going to visit that context now).
2023 bool visitedContext(DeclContext *Ctx) {
2024 return !VisitedContexts.insert(Ctx);
2025 }
2026
2027 /// \brief Determine whether the given declaration is hidden in the
2028 /// current scope.
2029 ///
2030 /// \returns the declaration that hides the given declaration, or
2031 /// NULL if no such declaration exists.
2032 NamedDecl *checkHidden(NamedDecl *ND);
2033
2034 /// \brief Add a declaration to the current shadow map.
2035 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2036};
2037
2038/// \brief RAII object that records when we've entered a shadow context.
2039class ShadowContextRAII {
2040 VisibleDeclsRecord &Visible;
2041
2042 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2043
2044public:
2045 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2046 Visible.ShadowMaps.push_back(ShadowMap());
2047 }
2048
2049 ~ShadowContextRAII() {
2050 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2051 EEnd = Visible.ShadowMaps.back().end();
2052 E != EEnd;
2053 ++E)
2054 E->second.Destroy();
2055
2056 Visible.ShadowMaps.pop_back();
2057 }
2058};
2059
2060} // end anonymous namespace
2061
2062void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2063 if (DeclOrVector.isNull()) {
2064 // 0 - > 1 elements: just set the single element information.
2065 DeclOrVector = ND;
2066 return;
2067 }
2068
2069 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2070 // 1 -> 2 elements: create the vector of results and push in the
2071 // existing declaration.
2072 DeclVector *Vec = new DeclVector;
2073 Vec->push_back(PrevND);
2074 DeclOrVector = Vec;
2075 }
2076
2077 // Add the new element to the end of the vector.
2078 DeclOrVector.get<DeclVector*>()->push_back(ND);
2079}
2080
2081void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2082 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2083 delete Vec;
2084 DeclOrVector = ((NamedDecl *)0);
2085 }
2086}
2087
2088VisibleDeclsRecord::ShadowMapEntry::iterator
2089VisibleDeclsRecord::ShadowMapEntry::begin() {
2090 if (DeclOrVector.isNull())
2091 return 0;
2092
2093 if (DeclOrVector.dyn_cast<NamedDecl *>())
2094 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2095
2096 return DeclOrVector.get<DeclVector *>()->begin();
2097}
2098
2099VisibleDeclsRecord::ShadowMapEntry::iterator
2100VisibleDeclsRecord::ShadowMapEntry::end() {
2101 if (DeclOrVector.isNull())
2102 return 0;
2103
2104 if (DeclOrVector.dyn_cast<NamedDecl *>())
2105 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2106
2107 return DeclOrVector.get<DeclVector *>()->end();
2108}
2109
2110NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002111 // Look through using declarations.
2112 ND = ND->getUnderlyingDecl();
2113
Douglas Gregor546be3c2009-12-30 17:04:44 +00002114 unsigned IDNS = ND->getIdentifierNamespace();
2115 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2116 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2117 SM != SMEnd; ++SM) {
2118 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2119 if (Pos == SM->end())
2120 continue;
2121
2122 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2123 IEnd = Pos->second.end();
2124 I != IEnd; ++I) {
2125 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002126 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor546be3c2009-12-30 17:04:44 +00002127 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2128 Decl::IDNS_ObjCProtocol)))
2129 continue;
2130
2131 // Protocols are in distinct namespaces from everything else.
2132 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2133 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2134 (*I)->getIdentifierNamespace() != IDNS)
2135 continue;
2136
Douglas Gregor0cc84042010-01-14 15:47:35 +00002137 // Functions and function templates in the same scope overload
2138 // rather than hide. FIXME: Look for hiding based on function
2139 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002140 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002141 ND->isFunctionOrFunctionTemplate() &&
2142 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002143 continue;
2144
Douglas Gregor546be3c2009-12-30 17:04:44 +00002145 // We've found a declaration that hides this one.
2146 return *I;
2147 }
2148 }
2149
2150 return 0;
2151}
2152
2153static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2154 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002155 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002156 VisibleDeclConsumer &Consumer,
2157 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002158 if (!Ctx)
2159 return;
2160
Douglas Gregor546be3c2009-12-30 17:04:44 +00002161 // Make sure we don't visit the same context twice.
2162 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2163 return;
2164
2165 // Enumerate all of the results in this context.
2166 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2167 CurCtx = CurCtx->getNextContext()) {
2168 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2169 DEnd = CurCtx->decls_end();
2170 D != DEnd; ++D) {
2171 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2172 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002173 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002174 Visited.add(ND);
2175 }
2176
2177 // Visit transparent contexts inside this context.
2178 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2179 if (InnerCtx->isTransparentContext())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002180 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002181 Consumer, Visited);
2182 }
2183 }
2184 }
2185
2186 // Traverse using directives for qualified name lookup.
2187 if (QualifiedNameLookup) {
2188 ShadowContextRAII Shadow(Visited);
2189 DeclContext::udir_iterator I, E;
2190 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2191 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002192 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002193 }
2194 }
2195
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002196 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002197 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002198 if (!Record->hasDefinition())
2199 return;
2200
Douglas Gregor546be3c2009-12-30 17:04:44 +00002201 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2202 BEnd = Record->bases_end();
2203 B != BEnd; ++B) {
2204 QualType BaseType = B->getType();
2205
2206 // Don't look into dependent bases, because name lookup can't look
2207 // there anyway.
2208 if (BaseType->isDependentType())
2209 continue;
2210
2211 const RecordType *Record = BaseType->getAs<RecordType>();
2212 if (!Record)
2213 continue;
2214
2215 // FIXME: It would be nice to be able to determine whether referencing
2216 // a particular member would be ambiguous. For example, given
2217 //
2218 // struct A { int member; };
2219 // struct B { int member; };
2220 // struct C : A, B { };
2221 //
2222 // void f(C *c) { c->### }
2223 //
2224 // accessing 'member' would result in an ambiguity. However, we
2225 // could be smart enough to qualify the member with the base
2226 // class, e.g.,
2227 //
2228 // c->B::member
2229 //
2230 // or
2231 //
2232 // c->A::member
2233
2234 // Find results in this base class (and its bases).
2235 ShadowContextRAII Shadow(Visited);
2236 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002237 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002238 }
2239 }
2240
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002241 // Traverse the contexts of Objective-C classes.
2242 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2243 // Traverse categories.
2244 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2245 Category; Category = Category->getNextClassCategory()) {
2246 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002247 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2248 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002249 }
2250
2251 // Traverse protocols.
2252 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2253 E = IFace->protocol_end(); I != E; ++I) {
2254 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002255 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2256 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002257 }
2258
2259 // Traverse the superclass.
2260 if (IFace->getSuperClass()) {
2261 ShadowContextRAII Shadow(Visited);
2262 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002263 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002264 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002265
2266 // If there is an implementation, traverse it. We do this to find
2267 // synthesized ivars.
2268 if (IFace->getImplementation()) {
2269 ShadowContextRAII Shadow(Visited);
2270 LookupVisibleDecls(IFace->getImplementation(), Result,
2271 QualifiedNameLookup, true, Consumer, Visited);
2272 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002273 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2274 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2275 E = Protocol->protocol_end(); I != E; ++I) {
2276 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002277 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2278 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002279 }
2280 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2281 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2282 E = Category->protocol_end(); I != E; ++I) {
2283 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002284 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2285 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002286 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002287
2288 // If there is an implementation, traverse it.
2289 if (Category->getImplementation()) {
2290 ShadowContextRAII Shadow(Visited);
2291 LookupVisibleDecls(Category->getImplementation(), Result,
2292 QualifiedNameLookup, true, Consumer, Visited);
2293 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002294 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002295}
2296
2297static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2298 UnqualUsingDirectiveSet &UDirs,
2299 VisibleDeclConsumer &Consumer,
2300 VisibleDeclsRecord &Visited) {
2301 if (!S)
2302 return;
2303
Douglas Gregor539c5c32010-01-07 00:31:29 +00002304 if (!S->getEntity() || !S->getParent() ||
2305 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2306 // Walk through the declarations in this Scope.
2307 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2308 D != DEnd; ++D) {
2309 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2310 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002311 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002312 Visited.add(ND);
2313 }
2314 }
2315 }
2316
Douglas Gregor711be1e2010-03-15 14:33:29 +00002317 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002318 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002319 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002320 // Look into this scope's declaration context, along with any of its
2321 // parent lookup contexts (e.g., enclosing classes), up to the point
2322 // where we hit the context stored in the next outer scope.
2323 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002324 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor546be3c2009-12-30 17:04:44 +00002325
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002326 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002327 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002328 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2329 if (Method->isInstanceMethod()) {
2330 // For instance methods, look for ivars in the method's interface.
2331 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2332 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor62021192010-02-04 23:42:48 +00002333 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2334 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2335 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002336 }
2337
2338 // We've already performed all of the name lookup that we need
2339 // to for Objective-C methods; the next context will be the
2340 // outer scope.
2341 break;
2342 }
2343
Douglas Gregor546be3c2009-12-30 17:04:44 +00002344 if (Ctx->isFunctionOrMethod())
2345 continue;
2346
2347 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002348 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002349 }
2350 } else if (!S->getParent()) {
2351 // Look into the translation unit scope. We walk through the translation
2352 // unit's declaration context, because the Scope itself won't have all of
2353 // the declarations if we loaded a precompiled header.
2354 // FIXME: We would like the translation unit's Scope object to point to the
2355 // translation unit, so we don't need this special "if" branch. However,
2356 // doing so would force the normal C++ name-lookup code to look into the
2357 // translation unit decl when the IdentifierInfo chains would suffice.
2358 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002359 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002360 Entity = Result.getSema().Context.getTranslationUnitDecl();
2361 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002362 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002363 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002364
2365 if (Entity) {
2366 // Lookup visible declarations in any namespaces found by using
2367 // directives.
2368 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2369 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2370 for (; UI != UEnd; ++UI)
2371 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002372 Result, /*QualifiedNameLookup=*/false,
2373 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002374 }
2375
2376 // Lookup names in the parent scope.
2377 ShadowContextRAII Shadow(Visited);
2378 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2379}
2380
2381void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2382 VisibleDeclConsumer &Consumer) {
2383 // Determine the set of using directives available during
2384 // unqualified name lookup.
2385 Scope *Initial = S;
2386 UnqualUsingDirectiveSet UDirs;
2387 if (getLangOptions().CPlusPlus) {
2388 // Find the first namespace or translation-unit scope.
2389 while (S && !isNamespaceOrTranslationUnitScope(S))
2390 S = S->getParent();
2391
2392 UDirs.visitScopeChain(Initial, S);
2393 }
2394 UDirs.done();
2395
2396 // Look for visible declarations.
2397 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2398 VisibleDeclsRecord Visited;
2399 ShadowContextRAII Shadow(Visited);
2400 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2401}
2402
2403void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2404 VisibleDeclConsumer &Consumer) {
2405 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2406 VisibleDeclsRecord Visited;
2407 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002408 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2409 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002410}
2411
2412//----------------------------------------------------------------------------
2413// Typo correction
2414//----------------------------------------------------------------------------
2415
2416namespace {
2417class TypoCorrectionConsumer : public VisibleDeclConsumer {
2418 /// \brief The name written that is a typo in the source.
2419 llvm::StringRef Typo;
2420
2421 /// \brief The results found that have the smallest edit distance
2422 /// found (so far) with the typo name.
2423 llvm::SmallVector<NamedDecl *, 4> BestResults;
2424
Douglas Gregoraaf87162010-04-14 20:04:41 +00002425 /// \brief The keywords that have the smallest edit distance.
2426 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2427
Douglas Gregor546be3c2009-12-30 17:04:44 +00002428 /// \brief The best edit distance found so far.
2429 unsigned BestEditDistance;
2430
2431public:
2432 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2433 : Typo(Typo->getName()) { }
2434
Douglas Gregor0cc84042010-01-14 15:47:35 +00002435 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002436 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002437
2438 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2439 iterator begin() const { return BestResults.begin(); }
2440 iterator end() const { return BestResults.end(); }
Douglas Gregoraaf87162010-04-14 20:04:41 +00002441 void clear_decls() { BestResults.clear(); }
2442
2443 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002444
Douglas Gregoraaf87162010-04-14 20:04:41 +00002445 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2446 keyword_iterator;
2447 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2448 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2449 bool keyword_empty() const { return BestKeywords.empty(); }
2450 unsigned keyword_size() const { return BestKeywords.size(); }
2451
2452 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002453};
2454
2455}
2456
Douglas Gregor0cc84042010-01-14 15:47:35 +00002457void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2458 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002459 // Don't consider hidden names for typo correction.
2460 if (Hiding)
2461 return;
2462
2463 // Only consider entities with identifiers for names, ignoring
2464 // special names (constructors, overloaded operators, selectors,
2465 // etc.).
2466 IdentifierInfo *Name = ND->getIdentifier();
2467 if (!Name)
2468 return;
2469
2470 // Compute the edit distance between the typo and the name of this
2471 // entity. If this edit distance is not worse than the best edit
2472 // distance we've seen so far, add it to the list of results.
2473 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregoraaf87162010-04-14 20:04:41 +00002474 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002475 if (ED < BestEditDistance) {
2476 // This result is better than any we've seen before; clear out
2477 // the previous results.
2478 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002479 BestKeywords.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002480 BestEditDistance = ED;
2481 } else if (ED > BestEditDistance) {
2482 // This result is worse than the best results we've seen so far;
2483 // ignore it.
2484 return;
2485 }
2486 } else
2487 BestEditDistance = ED;
2488
2489 BestResults.push_back(ND);
2490}
2491
Douglas Gregoraaf87162010-04-14 20:04:41 +00002492void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2493 llvm::StringRef Keyword) {
2494 // Compute the edit distance between the typo and this keyword.
2495 // If this edit distance is not worse than the best edit
2496 // distance we've seen so far, add it to the list of results.
2497 unsigned ED = Typo.edit_distance(Keyword);
2498 if (!BestResults.empty() || !BestKeywords.empty()) {
2499 if (ED < BestEditDistance) {
2500 BestResults.clear();
2501 BestKeywords.clear();
2502 BestEditDistance = ED;
2503 } else if (ED > BestEditDistance) {
2504 // This result is worse than the best results we've seen so far;
2505 // ignore it.
2506 return;
2507 }
2508 } else
2509 BestEditDistance = ED;
2510
2511 BestKeywords.push_back(&Context.Idents.get(Keyword));
2512}
2513
Douglas Gregor546be3c2009-12-30 17:04:44 +00002514/// \brief Try to "correct" a typo in the source code by finding
2515/// visible declarations whose names are similar to the name that was
2516/// present in the source code.
2517///
2518/// \param Res the \c LookupResult structure that contains the name
2519/// that was present in the source code along with the name-lookup
2520/// criteria used to search for the name. On success, this structure
2521/// will contain the results of name lookup.
2522///
2523/// \param S the scope in which name lookup occurs.
2524///
2525/// \param SS the nested-name-specifier that precedes the name we're
2526/// looking for, if present.
2527///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002528/// \param MemberContext if non-NULL, the context in which to look for
2529/// a member access expression.
2530///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002531/// \param EnteringContext whether we're entering the context described by
2532/// the nested-name-specifier SS.
2533///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002534/// \param CTC The context in which typo correction occurs, which impacts the
2535/// set of keywords permitted.
2536///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002537/// \param OPT when non-NULL, the search for visible declarations will
2538/// also walk the protocols in the qualified interfaces of \p OPT.
2539///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002540/// \returns the corrected name if the typo was corrected, otherwise returns an
2541/// empty \c DeclarationName. When a typo was corrected, the result structure
2542/// may contain the results of name lookup for the correct name or it may be
2543/// empty.
2544DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002545 DeclContext *MemberContext,
2546 bool EnteringContext,
2547 CorrectTypoContext CTC,
2548 const ObjCObjectPointerType *OPT) {
Ted Kremenek1dac3412010-01-06 00:23:04 +00002549 if (Diags.hasFatalErrorOccurred())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002550 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002551
2552 // Provide a stop gap for files that are just seriously broken. Trying
2553 // to correct all typos can turn into a HUGE performance penalty, causing
2554 // some files to take minutes to get rejected by the parser.
2555 // FIXME: Is this the right solution?
2556 if (TyposCorrected == 20)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002557 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002558 ++TyposCorrected;
Ted Kremenek1dac3412010-01-06 00:23:04 +00002559
Douglas Gregor546be3c2009-12-30 17:04:44 +00002560 // We only attempt to correct typos for identifiers.
2561 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2562 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002563 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002564
2565 // If the scope specifier itself was invalid, don't try to correct
2566 // typos.
2567 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002568 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002569
2570 // Never try to correct typos during template deduction or
2571 // instantiation.
2572 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002573 return DeclarationName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002574
Douglas Gregor546be3c2009-12-30 17:04:44 +00002575 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002576
2577 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002578 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002579 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002580
2581 // Look in qualified interfaces.
2582 if (OPT) {
2583 for (ObjCObjectPointerType::qual_iterator
2584 I = OPT->qual_begin(), E = OPT->qual_end();
2585 I != E; ++I)
2586 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2587 }
2588 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002589 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2590 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002591 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002592
2593 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2594 } else {
2595 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2596 }
2597
Douglas Gregoraaf87162010-04-14 20:04:41 +00002598 // Add context-dependent keywords.
2599 bool WantTypeSpecifiers = false;
2600 bool WantExpressionKeywords = false;
2601 bool WantCXXNamedCasts = false;
2602 bool WantRemainingKeywords = false;
2603 switch (CTC) {
2604 case CTC_Unknown:
2605 WantTypeSpecifiers = true;
2606 WantExpressionKeywords = true;
2607 WantCXXNamedCasts = true;
2608 WantRemainingKeywords = true;
2609 break;
2610
2611 case CTC_NoKeywords:
2612 break;
2613
2614 case CTC_Type:
2615 WantTypeSpecifiers = true;
2616 break;
2617
2618 case CTC_ObjCMessageReceiver:
2619 Consumer.addKeywordResult(Context, "super");
2620 // Fall through to handle message receivers like expressions.
2621
2622 case CTC_Expression:
2623 if (getLangOptions().CPlusPlus)
2624 WantTypeSpecifiers = true;
2625 WantExpressionKeywords = true;
2626 // Fall through to get C++ named casts.
2627
2628 case CTC_CXXCasts:
2629 WantCXXNamedCasts = true;
2630 break;
2631
2632 case CTC_MemberLookup:
2633 if (getLangOptions().CPlusPlus)
2634 Consumer.addKeywordResult(Context, "template");
2635 break;
2636 }
2637
2638 if (WantTypeSpecifiers) {
2639 // Add type-specifier keywords to the set of results.
2640 const char *CTypeSpecs[] = {
2641 "char", "const", "double", "enum", "float", "int", "long", "short",
2642 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2643 "_Complex", "_Imaginary",
2644 // storage-specifiers as well
2645 "extern", "inline", "static", "typedef"
2646 };
2647
2648 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2649 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2650 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2651
2652 if (getLangOptions().C99)
2653 Consumer.addKeywordResult(Context, "restrict");
2654 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2655 Consumer.addKeywordResult(Context, "bool");
2656
2657 if (getLangOptions().CPlusPlus) {
2658 Consumer.addKeywordResult(Context, "class");
2659 Consumer.addKeywordResult(Context, "typename");
2660 Consumer.addKeywordResult(Context, "wchar_t");
2661
2662 if (getLangOptions().CPlusPlus0x) {
2663 Consumer.addKeywordResult(Context, "char16_t");
2664 Consumer.addKeywordResult(Context, "char32_t");
2665 Consumer.addKeywordResult(Context, "constexpr");
2666 Consumer.addKeywordResult(Context, "decltype");
2667 Consumer.addKeywordResult(Context, "thread_local");
2668 }
2669 }
2670
2671 if (getLangOptions().GNUMode)
2672 Consumer.addKeywordResult(Context, "typeof");
2673 }
2674
2675 if (WantCXXNamedCasts) {
2676 Consumer.addKeywordResult(Context, "const_cast");
2677 Consumer.addKeywordResult(Context, "dynamic_cast");
2678 Consumer.addKeywordResult(Context, "reinterpret_cast");
2679 Consumer.addKeywordResult(Context, "static_cast");
2680 }
2681
2682 if (WantExpressionKeywords) {
2683 Consumer.addKeywordResult(Context, "sizeof");
2684 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2685 Consumer.addKeywordResult(Context, "false");
2686 Consumer.addKeywordResult(Context, "true");
2687 }
2688
2689 if (getLangOptions().CPlusPlus) {
2690 const char *CXXExprs[] = {
2691 "delete", "new", "operator", "throw", "typeid"
2692 };
2693 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2694 for (unsigned I = 0; I != NumCXXExprs; ++I)
2695 Consumer.addKeywordResult(Context, CXXExprs[I]);
2696
2697 if (isa<CXXMethodDecl>(CurContext) &&
2698 cast<CXXMethodDecl>(CurContext)->isInstance())
2699 Consumer.addKeywordResult(Context, "this");
2700
2701 if (getLangOptions().CPlusPlus0x) {
2702 Consumer.addKeywordResult(Context, "alignof");
2703 Consumer.addKeywordResult(Context, "nullptr");
2704 }
2705 }
2706 }
2707
2708 if (WantRemainingKeywords) {
2709 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2710 // Statements.
2711 const char *CStmts[] = {
2712 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2713 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2714 for (unsigned I = 0; I != NumCStmts; ++I)
2715 Consumer.addKeywordResult(Context, CStmts[I]);
2716
2717 if (getLangOptions().CPlusPlus) {
2718 Consumer.addKeywordResult(Context, "catch");
2719 Consumer.addKeywordResult(Context, "try");
2720 }
2721
2722 if (S && S->getBreakParent())
2723 Consumer.addKeywordResult(Context, "break");
2724
2725 if (S && S->getContinueParent())
2726 Consumer.addKeywordResult(Context, "continue");
2727
2728 if (!getSwitchStack().empty()) {
2729 Consumer.addKeywordResult(Context, "case");
2730 Consumer.addKeywordResult(Context, "default");
2731 }
2732 } else {
2733 if (getLangOptions().CPlusPlus) {
2734 Consumer.addKeywordResult(Context, "namespace");
2735 Consumer.addKeywordResult(Context, "template");
2736 }
2737
2738 if (S && S->isClassScope()) {
2739 Consumer.addKeywordResult(Context, "explicit");
2740 Consumer.addKeywordResult(Context, "friend");
2741 Consumer.addKeywordResult(Context, "mutable");
2742 Consumer.addKeywordResult(Context, "private");
2743 Consumer.addKeywordResult(Context, "protected");
2744 Consumer.addKeywordResult(Context, "public");
2745 Consumer.addKeywordResult(Context, "virtual");
2746 }
2747 }
2748
2749 if (getLangOptions().CPlusPlus) {
2750 Consumer.addKeywordResult(Context, "using");
2751
2752 if (getLangOptions().CPlusPlus0x)
2753 Consumer.addKeywordResult(Context, "static_assert");
2754 }
2755 }
2756
2757 // If we haven't found anything, we're done.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002758 if (Consumer.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002759 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002760
2761 // Only allow a single, closest name in the result set (it's okay to
2762 // have overloads of that name, though).
Douglas Gregoraaf87162010-04-14 20:04:41 +00002763 DeclarationName BestName;
2764 NamedDecl *BestIvarOrPropertyDecl = 0;
2765 bool FoundIvarOrPropertyDecl = false;
2766
2767 // Check all of the declaration results to find the best name so far.
2768 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2769 IEnd = Consumer.end();
2770 I != IEnd; ++I) {
2771 if (!BestName)
2772 BestName = (*I)->getDeclName();
2773 else if (BestName != (*I)->getDeclName())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002774 return DeclarationName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002775
Douglas Gregoraaf87162010-04-14 20:04:41 +00002776 // \brief Keep track of either an Objective-C ivar or a property, but not
2777 // both.
2778 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
2779 if (FoundIvarOrPropertyDecl)
2780 BestIvarOrPropertyDecl = 0;
2781 else {
2782 BestIvarOrPropertyDecl = *I;
2783 FoundIvarOrPropertyDecl = true;
2784 }
2785 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002786 }
2787
Douglas Gregoraaf87162010-04-14 20:04:41 +00002788 // Now check all of the keyword results to find the best name.
2789 switch (Consumer.keyword_size()) {
2790 case 0:
2791 // No keywords matched.
2792 break;
2793
2794 case 1:
2795 // If we already have a name
2796 if (!BestName) {
2797 // We did not have anything previously,
2798 BestName = *Consumer.keyword_begin();
2799 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
2800 // We have a declaration with the same name as a context-sensitive
2801 // keyword. The keyword takes precedence.
2802 BestIvarOrPropertyDecl = 0;
2803 FoundIvarOrPropertyDecl = false;
2804 Consumer.clear_decls();
2805 } else {
2806 // Name collision; we will not correct typos.
2807 return DeclarationName();
2808 }
2809 break;
2810
2811 default:
2812 // Name collision; we will not correct typos.
2813 return DeclarationName();
2814 }
2815
Douglas Gregor546be3c2009-12-30 17:04:44 +00002816 // BestName is the closest viable name to what the user
2817 // typed. However, to make sure that we don't pick something that's
2818 // way off, make sure that the user typed at least 3 characters for
2819 // each correction.
2820 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002821 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
2822 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002823 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002824
2825 // Perform name lookup again with the name we chose, and declare
2826 // success if we found something that was not ambiguous.
2827 Res.clear();
2828 Res.setLookupName(BestName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002829
2830 // If we found an ivar or property, add that result; no further
2831 // lookup is required.
Douglas Gregoraaf87162010-04-14 20:04:41 +00002832 if (BestIvarOrPropertyDecl)
2833 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002834 // If we're looking into the context of a member, perform qualified
2835 // name lookup on the best name.
Douglas Gregoraaf87162010-04-14 20:04:41 +00002836 else if (!Consumer.keyword_empty()) {
2837 // The best match was a keyword. Return it.
2838 return BestName;
2839 } else if (MemberContext)
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002840 LookupQualifiedName(Res, MemberContext);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002841 // Perform lookup as if we had just parsed the best name.
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002842 else
2843 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2844 EnteringContext);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002845
2846 if (Res.isAmbiguous()) {
2847 Res.suppressDiagnostics();
Douglas Gregor931f98a2010-04-14 17:09:22 +00002848 return DeclarationName();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002849 }
2850
Douglas Gregor931f98a2010-04-14 17:09:22 +00002851 if (Res.getResultKind() != LookupResult::NotFound)
2852 return BestName;
2853
2854 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002855}