blob: 837cafda15464e677f8f491a8c0ca7630af928e5 [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor34074322009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6538c932009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2d435302009-12-30 17:04:44 +000030#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000031#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000032#include <vector>
33#include <iterator>
34#include <utility>
35#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000036
37using namespace clang;
38
John McCallf6c8a4e2009-11-10 07:01:13 +000039namespace {
40 class UnqualUsingEntry {
41 const DeclContext *Nominated;
42 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000043
John McCallf6c8a4e2009-11-10 07:01:13 +000044 public:
45 UnqualUsingEntry(const DeclContext *Nominated,
46 const DeclContext *CommonAncestor)
47 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
48 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000049
John McCallf6c8a4e2009-11-10 07:01:13 +000050 const DeclContext *getCommonAncestor() const {
51 return CommonAncestor;
52 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000053
John McCallf6c8a4e2009-11-10 07:01:13 +000054 const DeclContext *getNominatedNamespace() const {
55 return Nominated;
56 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 // Sort by the pointer value of the common ancestor.
59 struct Comparator {
60 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
61 return L.getCommonAncestor() < R.getCommonAncestor();
62 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
65 return E.getCommonAncestor() < DC;
66 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000067
John McCallf6c8a4e2009-11-10 07:01:13 +000068 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
69 return DC < E.getCommonAncestor();
70 }
71 };
72 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 /// A collection of using directives, as used by C++ unqualified
75 /// lookup.
76 class UnqualUsingDirectiveSet {
77 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000078
John McCallf6c8a4e2009-11-10 07:01:13 +000079 ListTy list;
80 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 public:
83 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000084
John McCallf6c8a4e2009-11-10 07:01:13 +000085 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
86 // C++ [namespace.udir]p1:
87 // During unqualified name lookup, the names appear as if they
88 // were declared in the nearest enclosing namespace which contains
89 // both the using-directive and the nominated namespace.
90 DeclContext *InnermostFileDC
91 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
92 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +000095 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
96 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
97 visit(Ctx, EffectiveDC);
98 } else {
99 Scope::udir_iterator I = S->using_directives_begin(),
100 End = S->using_directives_end();
101
102 for (; I != End; ++I)
103 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
104 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000105 }
106 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000107
108 // Visits a context and collect all of its using directives
109 // recursively. Treats all using directives as if they were
110 // declared in the context.
111 //
112 // A given context is only every visited once, so it is important
113 // that contexts be visited from the inside out in order to get
114 // the effective DCs right.
115 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
116 if (!visited.insert(DC))
117 return;
118
119 addUsingDirectives(DC, EffectiveDC);
120 }
121
122 // Visits a using directive and collects all of its using
123 // directives recursively. Treats all using directives as if they
124 // were declared in the effective DC.
125 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
126 DeclContext *NS = UD->getNominatedNamespace();
127 if (!visited.insert(NS))
128 return;
129
130 addUsingDirective(UD, EffectiveDC);
131 addUsingDirectives(NS, EffectiveDC);
132 }
133
134 // Adds all the using directives in a context (and those nominated
135 // by its using directives, transitively) as if they appeared in
136 // the given effective context.
137 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
138 llvm::SmallVector<DeclContext*,4> queue;
139 while (true) {
140 DeclContext::udir_iterator I, End;
141 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
142 UsingDirectiveDecl *UD = *I;
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (visited.insert(NS)) {
145 addUsingDirective(UD, EffectiveDC);
146 queue.push_back(NS);
147 }
148 }
149
150 if (queue.empty())
151 return;
152
153 DC = queue.back();
154 queue.pop_back();
155 }
156 }
157
158 // Add a using directive as if it had been declared in the given
159 // context. This helps implement C++ [namespace.udir]p3:
160 // The using-directive is transitive: if a scope contains a
161 // using-directive that nominates a second namespace that itself
162 // contains using-directives, the effect is as if the
163 // using-directives from the second namespace also appeared in
164 // the first.
165 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
166 // Find the common ancestor between the effective context and
167 // the nominated namespace.
168 DeclContext *Common = UD->getNominatedNamespace();
169 while (!Common->Encloses(EffectiveDC))
170 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000171 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000172
173 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
174 }
175
176 void done() {
177 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
178 }
179
180 typedef ListTy::iterator iterator;
181 typedef ListTy::const_iterator const_iterator;
182
183 iterator begin() { return list.begin(); }
184 iterator end() { return list.end(); }
185 const_iterator begin() const { return list.begin(); }
186 const_iterator end() const { return list.end(); }
187
188 std::pair<const_iterator,const_iterator>
189 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000190 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000191 UnqualUsingEntry::Comparator());
192 }
193 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000194}
195
Douglas Gregor889ceb72009-02-03 19:21:40 +0000196// Retrieve the set of identifier namespaces that correspond to a
197// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000198static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
199 bool CPlusPlus,
200 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000201 unsigned IDNS = 0;
202 switch (NameKind) {
203 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000204 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000206 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCallea305ed2009-12-18 10:40:03 +0000208 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
209 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210 break;
211
John McCallb9467b62010-04-24 01:30:58 +0000212 case Sema::LookupOperatorName:
213 // Operator lookup is its own crazy thing; it is not the same
214 // as (e.g.) looking up an operator name for redeclaration.
215 assert(!Redeclaration && "cannot do redeclaration operator lookup");
216 IDNS = Decl::IDNS_NonMemberOperator;
217 break;
218
Douglas Gregor889ceb72009-02-03 19:21:40 +0000219 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000220 if (CPlusPlus) {
221 IDNS = Decl::IDNS_Type;
222
223 // When looking for a redeclaration of a tag name, we add:
224 // 1) TagFriend to find undeclared friend decls
225 // 2) Namespace because they can't "overload" with tag decls.
226 // 3) Tag because it includes class templates, which can't
227 // "overload" with tag decls.
228 if (Redeclaration)
229 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
230 } else {
231 IDNS = Decl::IDNS_Tag;
232 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000233 break;
234
235 case Sema::LookupMemberName:
236 IDNS = Decl::IDNS_Member;
237 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000238 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000239 break;
240
241 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000242 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
243 break;
244
Douglas Gregor889ceb72009-02-03 19:21:40 +0000245 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000246 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000247 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000248
John McCall84d87672009-12-10 09:41:52 +0000249 case Sema::LookupUsingDeclName:
250 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
251 | Decl::IDNS_Member | Decl::IDNS_Using;
252 break;
253
Douglas Gregor79947a22009-04-24 00:11:27 +0000254 case Sema::LookupObjCProtocolName:
255 IDNS = Decl::IDNS_ObjCProtocol;
256 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000257 }
258 return IDNS;
259}
260
John McCallea305ed2009-12-18 10:40:03 +0000261void LookupResult::configure() {
262 IDNS = getIDNS(LookupKind,
263 SemaRef.getLangOptions().CPlusPlus,
264 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000265
266 // If we're looking for one of the allocation or deallocation
267 // operators, make sure that the implicitly-declared new and delete
268 // operators can be found.
269 if (!isForRedeclaration()) {
270 switch (Name.getCXXOverloadedOperator()) {
271 case OO_New:
272 case OO_Delete:
273 case OO_Array_New:
274 case OO_Array_Delete:
275 SemaRef.DeclareGlobalNewDelete();
276 break;
277
278 default:
279 break;
280 }
281 }
John McCallea305ed2009-12-18 10:40:03 +0000282}
283
John McCall9f3059a2009-10-09 21:13:30 +0000284// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000285void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000286 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000287}
288
John McCall283b9012009-11-22 00:44:51 +0000289/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000290void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000291 unsigned N = Decls.size();
John McCall84d87672009-12-10 09:41:52 +0000292
John McCall9f3059a2009-10-09 21:13:30 +0000293 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000294 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000295 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000296 return;
297 }
298
John McCall283b9012009-11-22 00:44:51 +0000299 // If there's a single decl, we need to examine it to decide what
300 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000301 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000302 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
303 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000304 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000305 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000306 ResultKind = FoundUnresolvedValue;
307 return;
308 }
John McCall9f3059a2009-10-09 21:13:30 +0000309
John McCall6538c932009-10-10 05:48:19 +0000310 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000311 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000312
John McCall9f3059a2009-10-09 21:13:30 +0000313 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000314 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
315
John McCall9f3059a2009-10-09 21:13:30 +0000316 bool Ambiguous = false;
317 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000318 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000319
320 unsigned UniqueTagIndex = 0;
321
322 unsigned I = 0;
323 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000324 NamedDecl *D = Decls[I]->getUnderlyingDecl();
325 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000326
Douglas Gregor13e65872010-08-11 14:45:53 +0000327 // Redeclarations of types via typedef can occur both within a scope
328 // and, through using declarations and directives, across scopes. There is
329 // no ambiguity if they all refer to the same type, so unique based on the
330 // canonical type.
331 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
332 if (!TD->getDeclContext()->isRecord()) {
333 QualType T = SemaRef.Context.getTypeDeclType(TD);
334 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
335 // The type is not unique; pull something off the back and continue
336 // at this index.
337 Decls[I] = Decls[--N];
338 continue;
339 }
340 }
341 }
342
John McCallf0f1cf02009-11-17 07:50:12 +0000343 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000344 // If it's not unique, pull something off the back (and
345 // continue at this index).
346 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000347 continue;
348 }
349
350 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000351
Douglas Gregor13e65872010-08-11 14:45:53 +0000352 if (isa<UnresolvedUsingValueDecl>(D)) {
353 HasUnresolved = true;
354 } else if (isa<TagDecl>(D)) {
355 if (HasTag)
356 Ambiguous = true;
357 UniqueTagIndex = I;
358 HasTag = true;
359 } else if (isa<FunctionTemplateDecl>(D)) {
360 HasFunction = true;
361 HasFunctionTemplate = true;
362 } else if (isa<FunctionDecl>(D)) {
363 HasFunction = true;
364 } else {
365 if (HasNonFunction)
366 Ambiguous = true;
367 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000368 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000369 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000370 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000371
John McCall9f3059a2009-10-09 21:13:30 +0000372 // C++ [basic.scope.hiding]p2:
373 // A class name or enumeration name can be hidden by the name of
374 // an object, function, or enumerator declared in the same
375 // scope. If a class or enumeration name and an object, function,
376 // or enumerator are declared in the same scope (in any order)
377 // with the same name, the class or enumeration name is hidden
378 // wherever the object, function, or enumerator name is visible.
379 // But it's still an error if there are distinct tag types found,
380 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000381 if (HideTags && HasTag && !Ambiguous &&
382 (HasFunction || HasNonFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000383 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000384
John McCall9f3059a2009-10-09 21:13:30 +0000385 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000386
John McCall80053822009-12-03 00:58:24 +0000387 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000388 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000389
John McCall9f3059a2009-10-09 21:13:30 +0000390 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000391 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000392 else if (HasUnresolved)
393 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000394 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000395 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000396 else
John McCall27b18f82009-11-17 02:14:36 +0000397 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000398}
399
John McCall5cebab12009-11-18 07:57:50 +0000400void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000401 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000402 DeclContext::lookup_iterator DI, DE;
403 for (I = P.begin(), E = P.end(); I != E; ++I)
404 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
405 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000406}
407
John McCall5cebab12009-11-18 07:57:50 +0000408void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000409 Paths = new CXXBasePaths;
410 Paths->swap(P);
411 addDeclsFromBasePaths(*Paths);
412 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000413 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000414}
415
John McCall5cebab12009-11-18 07:57:50 +0000416void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000417 Paths = new CXXBasePaths;
418 Paths->swap(P);
419 addDeclsFromBasePaths(*Paths);
420 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000421 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000422}
423
John McCall5cebab12009-11-18 07:57:50 +0000424void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000425 Out << Decls.size() << " result(s)";
426 if (isAmbiguous()) Out << ", ambiguous";
427 if (Paths) Out << ", base paths present";
428
429 for (iterator I = begin(), E = end(); I != E; ++I) {
430 Out << "\n";
431 (*I)->print(Out, 2);
432 }
433}
434
Douglas Gregord3a59182010-02-12 05:48:04 +0000435/// \brief Lookup a builtin function, when name lookup would otherwise
436/// fail.
437static bool LookupBuiltin(Sema &S, LookupResult &R) {
438 Sema::LookupNameKind NameKind = R.getLookupKind();
439
440 // If we didn't find a use of this identifier, and if the identifier
441 // corresponds to a compiler builtin, create the decl object for the builtin
442 // now, injecting it into translation unit scope, and return it.
443 if (NameKind == Sema::LookupOrdinaryName ||
444 NameKind == Sema::LookupRedeclarationWithLinkage) {
445 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
446 if (II) {
447 // If this is a builtin on this (or all) targets, create the decl.
448 if (unsigned BuiltinID = II->getBuiltinID()) {
449 // In C++, we don't have any predefined library functions like
450 // 'malloc'. Instead, we'll just error.
451 if (S.getLangOptions().CPlusPlus &&
452 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
453 return false;
454
455 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
456 S.TUScope, R.isForRedeclaration(),
457 R.getNameLoc());
458 if (D)
459 R.addDecl(D);
460 return (D != NULL);
461 }
462 }
463 }
464
465 return false;
466}
467
Douglas Gregor7454c562010-07-02 20:37:36 +0000468/// \brief Determine whether we can declare a special member function within
469/// the class at this point.
470static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
471 const CXXRecordDecl *Class) {
472 // We need to have a definition for the class.
473 if (!Class->getDefinition() || Class->isDependentContext())
474 return false;
475
476 // We can't be in the middle of defining the class.
477 if (const RecordType *RecordTy
478 = Context.getTypeDeclType(Class)->getAs<RecordType>())
479 return !RecordTy->isBeingDefined();
480
481 return false;
482}
483
484void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000485 if (!CanDeclareSpecialMemberFunction(Context, Class))
486 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000487
488 // If the default constructor has not yet been declared, do so now.
489 if (!Class->hasDeclaredDefaultConstructor())
490 DeclareImplicitDefaultConstructor(Class);
Douglas Gregora6d69502010-07-02 23:41:54 +0000491
492 // If the copy constructor has not yet been declared, do so now.
493 if (!Class->hasDeclaredCopyConstructor())
494 DeclareImplicitCopyConstructor(Class);
495
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000496 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000497 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000498 DeclareImplicitCopyAssignment(Class);
499
Douglas Gregor7454c562010-07-02 20:37:36 +0000500 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000501 if (!Class->hasDeclaredDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +0000502 DeclareImplicitDestructor(Class);
503}
504
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000505/// \brief Determine whether this is the name of an implicitly-declared
506/// special member function.
507static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
508 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000509 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000510 case DeclarationName::CXXDestructorName:
511 return true;
512
513 case DeclarationName::CXXOperatorName:
514 return Name.getCXXOverloadedOperator() == OO_Equal;
515
516 default:
517 break;
518 }
519
520 return false;
521}
522
523/// \brief If there are any implicit member functions with the given name
524/// that need to be declared in the given declaration context, do so.
525static void DeclareImplicitMemberFunctionsWithName(Sema &S,
526 DeclarationName Name,
527 const DeclContext *DC) {
528 if (!DC)
529 return;
530
531 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000532 case DeclarationName::CXXConstructorName:
533 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000534 if (Record->getDefinition() &&
535 CanDeclareSpecialMemberFunction(S.Context, Record)) {
536 if (!Record->hasDeclaredDefaultConstructor())
537 S.DeclareImplicitDefaultConstructor(
538 const_cast<CXXRecordDecl *>(Record));
539 if (!Record->hasDeclaredCopyConstructor())
540 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
541 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000542 break;
543
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000544 case DeclarationName::CXXDestructorName:
545 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
546 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
547 CanDeclareSpecialMemberFunction(S.Context, Record))
548 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000549 break;
550
551 case DeclarationName::CXXOperatorName:
552 if (Name.getCXXOverloadedOperator() != OO_Equal)
553 break;
554
555 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
556 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
557 CanDeclareSpecialMemberFunction(S.Context, Record))
558 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
559 break;
560
561 default:
562 break;
563 }
564}
Douglas Gregor7454c562010-07-02 20:37:36 +0000565
John McCall9f3059a2009-10-09 21:13:30 +0000566// Adds all qualifying matches for a name within a decl context to the
567// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000568static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000569 bool Found = false;
570
Douglas Gregor7454c562010-07-02 20:37:36 +0000571 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000572 if (S.getLangOptions().CPlusPlus)
573 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor7454c562010-07-02 20:37:36 +0000574
575 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000576 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000577 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000578 NamedDecl *D = *I;
579 if (R.isAcceptableDecl(D)) {
580 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000581 Found = true;
582 }
583 }
John McCall9f3059a2009-10-09 21:13:30 +0000584
Douglas Gregord3a59182010-02-12 05:48:04 +0000585 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
586 return true;
587
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000588 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000589 != DeclarationName::CXXConversionFunctionName ||
590 R.getLookupName().getCXXNameType()->isDependentType() ||
591 !isa<CXXRecordDecl>(DC))
592 return Found;
593
594 // C++ [temp.mem]p6:
595 // A specialization of a conversion function template is not found by
596 // name lookup. Instead, any conversion function templates visible in the
597 // context of the use are considered. [...]
598 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
599 if (!Record->isDefinition())
600 return Found;
601
602 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
603 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
604 UEnd = Unresolved->end(); U != UEnd; ++U) {
605 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
606 if (!ConvTemplate)
607 continue;
608
609 // When we're performing lookup for the purposes of redeclaration, just
610 // add the conversion function template. When we deduce template
611 // arguments for specializations, we'll end up unifying the return
612 // type of the new declaration with the type of the function template.
613 if (R.isForRedeclaration()) {
614 R.addDecl(ConvTemplate);
615 Found = true;
616 continue;
617 }
618
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000619 // C++ [temp.mem]p6:
Chandler Carruth3a693b72010-01-31 11:44:02 +0000620 // [...] For each such operator, if argument deduction succeeds
621 // (14.9.2.3), the resulting specialization is used as if found by
622 // name lookup.
623 //
624 // When referencing a conversion function for any purpose other than
625 // a redeclaration (such that we'll be building an expression with the
626 // result), perform template argument deduction and place the
627 // specialization into the result set. We do this to avoid forcing all
628 // callers to perform special deduction for conversion functions.
John McCallbc077cf2010-02-08 23:07:23 +0000629 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000630 FunctionDecl *Specialization = 0;
631
632 const FunctionProtoType *ConvProto
633 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
634 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000635
Chandler Carruth3a693b72010-01-31 11:44:02 +0000636 // Compute the type of the function that we would expect the conversion
637 // function to have, if it were to match the name given.
638 // FIXME: Calling convention!
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000639 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruth3a693b72010-01-31 11:44:02 +0000640 QualType ExpectedType
641 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
642 0, 0, ConvProto->isVariadic(),
643 ConvProto->getTypeQuals(),
644 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000645 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruth3a693b72010-01-31 11:44:02 +0000646
647 // Perform template argument deduction against the type that we would
648 // expect the function to have.
649 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
650 Specialization, Info)
651 == Sema::TDK_Success) {
652 R.addDecl(Specialization);
653 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000654 }
655 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000656
John McCall9f3059a2009-10-09 21:13:30 +0000657 return Found;
658}
659
John McCallf6c8a4e2009-11-10 07:01:13 +0000660// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000661static bool
Douglas Gregord3a59182010-02-12 05:48:04 +0000662CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
663 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000664
665 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
666
John McCallf6c8a4e2009-11-10 07:01:13 +0000667 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000668 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000669
John McCallf6c8a4e2009-11-10 07:01:13 +0000670 // Perform direct name lookup into the namespaces nominated by the
671 // using directives whose common ancestor is this namespace.
672 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
673 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000674
John McCallf6c8a4e2009-11-10 07:01:13 +0000675 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000676 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000677 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000678
679 R.resolveKind();
680
681 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000682}
683
684static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000685 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000686 return Ctx->isFileContext();
687 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000688}
Douglas Gregored8f2882009-01-30 01:04:22 +0000689
Douglas Gregor66230062010-03-15 14:33:29 +0000690// Find the next outer declaration context from this scope. This
691// routine actually returns the semantic outer context, which may
692// differ from the lexical context (encoded directly in the Scope
693// stack) when we are parsing a member of a class template. In this
694// case, the second element of the pair will be true, to indicate that
695// name lookup should continue searching in this semantic context when
696// it leaves the current template parameter scope.
697static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
698 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
699 DeclContext *Lexical = 0;
700 for (Scope *OuterS = S->getParent(); OuterS;
701 OuterS = OuterS->getParent()) {
702 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000703 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000704 break;
705 }
706 }
707
708 // C++ [temp.local]p8:
709 // In the definition of a member of a class template that appears
710 // outside of the namespace containing the class template
711 // definition, the name of a template-parameter hides the name of
712 // a member of this namespace.
713 //
714 // Example:
715 //
716 // namespace N {
717 // class C { };
718 //
719 // template<class T> class B {
720 // void f(T);
721 // };
722 // }
723 //
724 // template<class C> void N::B<C>::f(C) {
725 // C b; // C is the template parameter, not N::C
726 // }
727 //
728 // In this example, the lexical context we return is the
729 // TranslationUnit, while the semantic context is the namespace N.
730 if (!Lexical || !DC || !S->getParent() ||
731 !S->getParent()->isTemplateParamScope())
732 return std::make_pair(Lexical, false);
733
734 // Find the outermost template parameter scope.
735 // For the example, this is the scope for the template parameters of
736 // template<class C>.
737 Scope *OutermostTemplateScope = S->getParent();
738 while (OutermostTemplateScope->getParent() &&
739 OutermostTemplateScope->getParent()->isTemplateParamScope())
740 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregor7f737c02009-09-10 16:57:35 +0000741
Douglas Gregor66230062010-03-15 14:33:29 +0000742 // Find the namespace context in which the original scope occurs. In
743 // the example, this is namespace N.
744 DeclContext *Semantic = DC;
745 while (!Semantic->isFileContext())
746 Semantic = Semantic->getParent();
747
748 // Find the declaration context just outside of the template
749 // parameter scope. This is the context in which the template is
750 // being lexically declaration (a namespace context). In the
751 // example, this is the global scope.
752 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
753 Lexical->Encloses(Semantic))
754 return std::make_pair(Semantic, true);
755
756 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000757}
758
John McCall27b18f82009-11-17 02:14:36 +0000759bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000760 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000761
762 DeclarationName Name = R.getLookupName();
763
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000764 // If this is the name of an implicitly-declared special member function,
765 // go through the scope stack to implicitly declare
766 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
767 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
768 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
769 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
770 }
771
772 // Implicitly declare member functions with the name we're looking for, if in
773 // fact we are in a scope where it matters.
774
Douglas Gregor889ceb72009-02-03 19:21:40 +0000775 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000776 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000777 I = IdResolver.begin(Name),
778 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000779
Douglas Gregor889ceb72009-02-03 19:21:40 +0000780 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000781 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000782 // ...During unqualified name lookup (3.4.1), the names appear as if
783 // they were declared in the nearest enclosing namespace which contains
784 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000785 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000786 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000787 //
788 // For example:
789 // namespace A { int i; }
790 // void foo() {
791 // int i;
792 // {
793 // using namespace A;
794 // ++i; // finds local 'i', A::i appears at global scope
795 // }
796 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000797 //
Douglas Gregor66230062010-03-15 14:33:29 +0000798 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000799 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000800 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
801
Douglas Gregor889ceb72009-02-03 19:21:40 +0000802 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000803 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000804 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000805 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000806 Found = true;
807 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000808 }
809 }
John McCall9f3059a2009-10-09 21:13:30 +0000810 if (Found) {
811 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000812 if (S->isClassScope())
813 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
814 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000815 return true;
816 }
817
Douglas Gregor66230062010-03-15 14:33:29 +0000818 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
819 S->getParent() && !S->getParent()->isTemplateParamScope()) {
820 // We've just searched the last template parameter scope and
821 // found nothing, so look into the the contexts between the
822 // lexical and semantic declaration contexts returned by
823 // findOuterContext(). This implements the name lookup behavior
824 // of C++ [temp.local]p8.
825 Ctx = OutsideOfTemplateParamDC;
826 OutsideOfTemplateParamDC = 0;
827 }
828
829 if (Ctx) {
830 DeclContext *OuterCtx;
831 bool SearchAfterTemplateScope;
832 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
833 if (SearchAfterTemplateScope)
834 OutsideOfTemplateParamDC = OuterCtx;
835
Douglas Gregorea166062010-03-15 15:26:48 +0000836 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000837 // We do not directly look into transparent contexts, since
838 // those entities will be found in the nearest enclosing
839 // non-transparent context.
840 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000841 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000842
843 // We do not look directly into function or method contexts,
844 // since all of the local variables and parameters of the
845 // function/method are present within the Scope.
846 if (Ctx->isFunctionOrMethod()) {
847 // If we have an Objective-C instance method, look for ivars
848 // in the corresponding interface.
849 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
850 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
851 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
852 ObjCInterfaceDecl *ClassDeclared;
853 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
854 Name.getAsIdentifierInfo(),
855 ClassDeclared)) {
856 if (R.isAcceptableDecl(Ivar)) {
857 R.addDecl(Ivar);
858 R.resolveKind();
859 return true;
860 }
861 }
862 }
863 }
864
865 continue;
866 }
867
Douglas Gregor7f737c02009-09-10 16:57:35 +0000868 // Perform qualified name lookup into this context.
869 // FIXME: In some cases, we know that every name that could be found by
870 // this qualified name lookup will also be on the identifier chain. For
871 // example, inside a class without any base classes, we never need to
872 // perform qualified lookup because all of the members are on top of the
873 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000874 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000875 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000876 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000877 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000878 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000879
John McCallf6c8a4e2009-11-10 07:01:13 +0000880 // Stop if we ran out of scopes.
881 // FIXME: This really, really shouldn't be happening.
882 if (!S) return false;
883
Douglas Gregor700792c2009-02-05 19:25:20 +0000884 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000885 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000886 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000887 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
888 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000889
John McCallf6c8a4e2009-11-10 07:01:13 +0000890 UnqualUsingDirectiveSet UDirs;
891 UDirs.visitScopeChain(Initial, S);
892 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000893
Douglas Gregor700792c2009-02-05 19:25:20 +0000894 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000895 // Unqualified name lookup in C++ requires looking into scopes
896 // that aren't strictly lexical, and therefore we walk through the
897 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000898
Douglas Gregor889ceb72009-02-03 19:21:40 +0000899 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000900 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000901 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000902 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000903 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000904 // We found something. Look for anything else in our scope
905 // with this same name and in an acceptable identifier
906 // namespace, so that we can construct an overload set if we
907 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000908 Found = true;
909 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000910 }
911 }
912
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000913 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000914 R.resolveKind();
915 return true;
916 }
917
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000918 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
919 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
920 S->getParent() && !S->getParent()->isTemplateParamScope()) {
921 // We've just searched the last template parameter scope and
922 // found nothing, so look into the the contexts between the
923 // lexical and semantic declaration contexts returned by
924 // findOuterContext(). This implements the name lookup behavior
925 // of C++ [temp.local]p8.
926 Ctx = OutsideOfTemplateParamDC;
927 OutsideOfTemplateParamDC = 0;
928 }
929
930 if (Ctx) {
931 DeclContext *OuterCtx;
932 bool SearchAfterTemplateScope;
933 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
934 if (SearchAfterTemplateScope)
935 OutsideOfTemplateParamDC = OuterCtx;
936
937 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
938 // We do not directly look into transparent contexts, since
939 // those entities will be found in the nearest enclosing
940 // non-transparent context.
941 if (Ctx->isTransparentContext())
942 continue;
943
944 // If we have a context, and it's not a context stashed in the
945 // template parameter scope for an out-of-line definition, also
946 // look into that context.
947 if (!(Found && S && S->isTemplateParamScope())) {
948 assert(Ctx->isFileContext() &&
949 "We should have been looking only at file context here already.");
950
951 // Look into context considering using-directives.
952 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
953 Found = true;
954 }
955
956 if (Found) {
957 R.resolveKind();
958 return true;
959 }
960
961 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
962 return false;
963 }
964 }
965
Douglas Gregor3ce74932010-02-05 07:07:10 +0000966 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000967 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000968 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000969
John McCall9f3059a2009-10-09 21:13:30 +0000970 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000971}
972
Douglas Gregor34074322009-01-14 22:20:51 +0000973/// @brief Perform unqualified name lookup starting from a given
974/// scope.
975///
976/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
977/// used to find names within the current scope. For example, 'x' in
978/// @code
979/// int x;
980/// int f() {
981/// return x; // unqualified name look finds 'x' in the global scope
982/// }
983/// @endcode
984///
985/// Different lookup criteria can find different names. For example, a
986/// particular scope can have both a struct and a function of the same
987/// name, and each can be found by certain lookup criteria. For more
988/// information about lookup criteria, see the documentation for the
989/// class LookupCriteria.
990///
991/// @param S The scope from which unqualified name lookup will
992/// begin. If the lookup criteria permits, name lookup may also search
993/// in the parent scopes.
994///
995/// @param Name The name of the entity that we are searching for.
996///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000997/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000998/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000999/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001000///
1001/// @returns The result of name lookup, which includes zero or more
1002/// declarations and possibly additional information used to diagnose
1003/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001004bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1005 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001006 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001007
John McCall27b18f82009-11-17 02:14:36 +00001008 LookupNameKind NameKind = R.getLookupKind();
1009
Douglas Gregor34074322009-01-14 22:20:51 +00001010 if (!getLangOptions().CPlusPlus) {
1011 // Unqualified name lookup in C/Objective-C is purely lexical, so
1012 // search in the declarations attached to the name.
1013
John McCallea305ed2009-12-18 10:40:03 +00001014 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001015 // Find the nearest non-transparent declaration scope.
1016 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001017 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001018 static_cast<DeclContext *>(S->getEntity())
1019 ->isTransparentContext()))
1020 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001021 }
1022
John McCallea305ed2009-12-18 10:40:03 +00001023 unsigned IDNS = R.getIdentifierNamespace();
1024
Douglas Gregor34074322009-01-14 22:20:51 +00001025 // Scan up the scope chain looking for a decl that matches this
1026 // identifier that is in the appropriate namespace. This search
1027 // should not take long, as shadowing of names is uncommon, and
1028 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001029 bool LeftStartingScope = false;
1030
Douglas Gregored8f2882009-01-30 01:04:22 +00001031 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001032 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001033 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001034 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001035 if (NameKind == LookupRedeclarationWithLinkage) {
1036 // Determine whether this (or a previous) declaration is
1037 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00001038 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001039 LeftStartingScope = true;
1040
1041 // If we found something outside of our starting scope that
1042 // does not have linkage, skip it.
1043 if (LeftStartingScope && !((*I)->hasLinkage()))
1044 continue;
1045 }
1046
John McCall9f3059a2009-10-09 21:13:30 +00001047 R.addDecl(*I);
1048
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001049 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001050 // If this declaration has the "overloadable" attribute, we
1051 // might have a set of overloaded functions.
1052
1053 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001054 while (!(S->getFlags() & Scope::DeclScope) ||
1055 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001056 S = S->getParent();
1057
1058 // Find the last declaration in this scope (with the same
1059 // name, naturally).
1060 IdentifierResolver::iterator LastI = I;
1061 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +00001062 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001063 break;
John McCall9f3059a2009-10-09 21:13:30 +00001064 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001065 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001066 }
1067
John McCall9f3059a2009-10-09 21:13:30 +00001068 R.resolveKind();
1069
1070 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001071 }
Douglas Gregor34074322009-01-14 22:20:51 +00001072 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001073 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001074 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001075 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001076 }
1077
1078 // If we didn't find a use of this identifier, and if the identifier
1079 // corresponds to a compiler builtin, create the decl object for the builtin
1080 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +00001081 if (AllowBuiltinCreation)
1082 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001083
John McCall9f3059a2009-10-09 21:13:30 +00001084 return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001085}
1086
John McCall6538c932009-10-10 05:48:19 +00001087/// @brief Perform qualified name lookup in the namespaces nominated by
1088/// using directives by the given context.
1089///
1090/// C++98 [namespace.qual]p2:
1091/// Given X::m (where X is a user-declared namespace), or given ::m
1092/// (where X is the global namespace), let S be the set of all
1093/// declarations of m in X and in the transitive closure of all
1094/// namespaces nominated by using-directives in X and its used
1095/// namespaces, except that using-directives are ignored in any
1096/// namespace, including X, directly containing one or more
1097/// declarations of m. No namespace is searched more than once in
1098/// the lookup of a name. If S is the empty set, the program is
1099/// ill-formed. Otherwise, if S has exactly one member, or if the
1100/// context of the reference is a using-declaration
1101/// (namespace.udecl), S is the required set of declarations of
1102/// m. Otherwise if the use of m is not one that allows a unique
1103/// declaration to be chosen from S, the program is ill-formed.
1104/// C++98 [namespace.qual]p5:
1105/// During the lookup of a qualified namespace member name, if the
1106/// lookup finds more than one declaration of the member, and if one
1107/// declaration introduces a class name or enumeration name and the
1108/// other declarations either introduce the same object, the same
1109/// enumerator or a set of functions, the non-type name hides the
1110/// class or enumeration name if and only if the declarations are
1111/// from the same namespace; otherwise (the declarations are from
1112/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001113static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001114 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001115 assert(StartDC->isFileContext() && "start context is not a file context");
1116
1117 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1118 DeclContext::udir_iterator E = StartDC->using_directives_end();
1119
1120 if (I == E) return false;
1121
1122 // We have at least added all these contexts to the queue.
1123 llvm::DenseSet<DeclContext*> Visited;
1124 Visited.insert(StartDC);
1125
1126 // We have not yet looked into these namespaces, much less added
1127 // their "using-children" to the queue.
1128 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1129
1130 // We have already looked into the initial namespace; seed the queue
1131 // with its using-children.
1132 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001133 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001134 if (Visited.insert(ND).second)
1135 Queue.push_back(ND);
1136 }
1137
1138 // The easiest way to implement the restriction in [namespace.qual]p5
1139 // is to check whether any of the individual results found a tag
1140 // and, if so, to declare an ambiguity if the final result is not
1141 // a tag.
1142 bool FoundTag = false;
1143 bool FoundNonTag = false;
1144
John McCall5cebab12009-11-18 07:57:50 +00001145 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001146
1147 bool Found = false;
1148 while (!Queue.empty()) {
1149 NamespaceDecl *ND = Queue.back();
1150 Queue.pop_back();
1151
1152 // We go through some convolutions here to avoid copying results
1153 // between LookupResults.
1154 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001155 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001156 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001157
1158 if (FoundDirect) {
1159 // First do any local hiding.
1160 DirectR.resolveKind();
1161
1162 // If the local result is a tag, remember that.
1163 if (DirectR.isSingleTagDecl())
1164 FoundTag = true;
1165 else
1166 FoundNonTag = true;
1167
1168 // Append the local results to the total results if necessary.
1169 if (UseLocal) {
1170 R.addAllDecls(LocalR);
1171 LocalR.clear();
1172 }
1173 }
1174
1175 // If we find names in this namespace, ignore its using directives.
1176 if (FoundDirect) {
1177 Found = true;
1178 continue;
1179 }
1180
1181 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1182 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1183 if (Visited.insert(Nom).second)
1184 Queue.push_back(Nom);
1185 }
1186 }
1187
1188 if (Found) {
1189 if (FoundTag && FoundNonTag)
1190 R.setAmbiguousQualifiedTagHiding();
1191 else
1192 R.resolveKind();
1193 }
1194
1195 return Found;
1196}
1197
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001198/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001199///
1200/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1201/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001202/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001203///
1204/// Different lookup criteria can find different names. For example, a
1205/// particular scope can have both a struct and a function of the same
1206/// name, and each can be found by certain lookup criteria. For more
1207/// information about lookup criteria, see the documentation for the
1208/// class LookupCriteria.
1209///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001210/// \param R captures both the lookup criteria and any lookup results found.
1211///
1212/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001213/// search. If the lookup criteria permits, name lookup may also search
1214/// in the parent contexts or (for C++ classes) base classes.
1215///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001216/// \param InUnqualifiedLookup true if this is qualified name lookup that
1217/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001218///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001219/// \returns true if lookup succeeded, false if it failed.
1220bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1221 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001222 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001223
John McCall27b18f82009-11-17 02:14:36 +00001224 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001225 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001226
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001227 // Make sure that the declaration context is complete.
1228 assert((!isa<TagDecl>(LookupCtx) ||
1229 LookupCtx->isDependentContext() ||
1230 cast<TagDecl>(LookupCtx)->isDefinition() ||
1231 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1232 ->isBeingDefined()) &&
1233 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001234
Douglas Gregor34074322009-01-14 22:20:51 +00001235 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001236 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001237 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001238 if (isa<CXXRecordDecl>(LookupCtx))
1239 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001240 return true;
1241 }
Douglas Gregor34074322009-01-14 22:20:51 +00001242
John McCall6538c932009-10-10 05:48:19 +00001243 // Don't descend into implied contexts for redeclarations.
1244 // C++98 [namespace.qual]p6:
1245 // In a declaration for a namespace member in which the
1246 // declarator-id is a qualified-id, given that the qualified-id
1247 // for the namespace member has the form
1248 // nested-name-specifier unqualified-id
1249 // the unqualified-id shall name a member of the namespace
1250 // designated by the nested-name-specifier.
1251 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001252 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001253 return false;
1254
John McCall27b18f82009-11-17 02:14:36 +00001255 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001256 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001257 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001258
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001259 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001260 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001261 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001262 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001263 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001264
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001265 // If we're performing qualified name lookup into a dependent class,
1266 // then we are actually looking into a current instantiation. If we have any
1267 // dependent base classes, then we either have to delay lookup until
1268 // template instantiation time (at which point all bases will be available)
1269 // or we have to fail.
1270 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1271 LookupRec->hasAnyDependentBases()) {
1272 R.setNotFoundInCurrentInstantiation();
1273 return false;
1274 }
1275
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001276 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001277 CXXBasePaths Paths;
1278 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001279
1280 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001281 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001282 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001283 case LookupOrdinaryName:
1284 case LookupMemberName:
1285 case LookupRedeclarationWithLinkage:
1286 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1287 break;
1288
1289 case LookupTagName:
1290 BaseCallback = &CXXRecordDecl::FindTagMember;
1291 break;
John McCall84d87672009-12-10 09:41:52 +00001292
1293 case LookupUsingDeclName:
1294 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001295
1296 case LookupOperatorName:
1297 case LookupNamespaceName:
1298 case LookupObjCProtocolName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001299 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001300 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001301
1302 case LookupNestedNameSpecifierName:
1303 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1304 break;
1305 }
1306
John McCall27b18f82009-11-17 02:14:36 +00001307 if (!LookupRec->lookupInBases(BaseCallback,
1308 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001309 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001310
John McCall553c0792010-01-23 00:46:32 +00001311 R.setNamingClass(LookupRec);
1312
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001313 // C++ [class.member.lookup]p2:
1314 // [...] If the resulting set of declarations are not all from
1315 // sub-objects of the same type, or the set has a nonstatic member
1316 // and includes members from distinct sub-objects, there is an
1317 // ambiguity and the program is ill-formed. Otherwise that set is
1318 // the result of the lookup.
1319 // FIXME: support using declarations!
1320 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001321 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001322 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001323 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001324 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001325 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001326
John McCall401982f2010-01-20 21:53:11 +00001327 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1328 // across all paths.
1329 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1330
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001331 // Determine whether we're looking at a distinct sub-object or not.
1332 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001333 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001334 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1335 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001336 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001337 != Context.getCanonicalType(PathElement.Base->getType())) {
1338 // We found members of the given name in two subobjects of
1339 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001340 R.setAmbiguousBaseSubobjectTypes(Paths);
1341 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001342 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1343 // We have a different subobject of the same type.
1344
1345 // C++ [class.member.lookup]p5:
1346 // A static member, a nested type or an enumerator defined in
1347 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001348 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001349 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001350 if (isa<VarDecl>(FirstDecl) ||
1351 isa<TypeDecl>(FirstDecl) ||
1352 isa<EnumConstantDecl>(FirstDecl))
1353 continue;
1354
1355 if (isa<CXXMethodDecl>(FirstDecl)) {
1356 // Determine whether all of the methods are static.
1357 bool AllMethodsAreStatic = true;
1358 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1359 Func != Path->Decls.second; ++Func) {
1360 if (!isa<CXXMethodDecl>(*Func)) {
1361 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1362 break;
1363 }
1364
1365 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1366 AllMethodsAreStatic = false;
1367 break;
1368 }
1369 }
1370
1371 if (AllMethodsAreStatic)
1372 continue;
1373 }
1374
1375 // We have found a nonstatic member name in multiple, distinct
1376 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001377 R.setAmbiguousBaseSubobjects(Paths);
1378 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001379 }
1380 }
1381
1382 // Lookup in a base class succeeded; return these results.
1383
John McCall9f3059a2009-10-09 21:13:30 +00001384 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001385 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1386 NamedDecl *D = *I;
1387 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1388 D->getAccess());
1389 R.addDecl(D, AS);
1390 }
John McCall9f3059a2009-10-09 21:13:30 +00001391 R.resolveKind();
1392 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001393}
1394
1395/// @brief Performs name lookup for a name that was parsed in the
1396/// source code, and may contain a C++ scope specifier.
1397///
1398/// This routine is a convenience routine meant to be called from
1399/// contexts that receive a name and an optional C++ scope specifier
1400/// (e.g., "N::M::x"). It will then perform either qualified or
1401/// unqualified name lookup (with LookupQualifiedName or LookupName,
1402/// respectively) on the given name and return those results.
1403///
1404/// @param S The scope from which unqualified name lookup will
1405/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001406///
Douglas Gregore861bac2009-08-25 22:51:20 +00001407/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001408///
1409/// @param Name The name of the entity that name lookup will
1410/// search for.
1411///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001412/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001413/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001414/// C library functions (like "malloc") are implicitly declared.
1415///
Douglas Gregore861bac2009-08-25 22:51:20 +00001416/// @param EnteringContext Indicates whether we are going to enter the
1417/// context of the scope-specifier SS (if present).
1418///
John McCall9f3059a2009-10-09 21:13:30 +00001419/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001420bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001421 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001422 if (SS && SS->isInvalid()) {
1423 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001424 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001425 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001426 }
Mike Stump11289f42009-09-09 15:08:12 +00001427
Douglas Gregore861bac2009-08-25 22:51:20 +00001428 if (SS && SS->isSet()) {
1429 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001430 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001431 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001432 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001433 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001434
John McCall27b18f82009-11-17 02:14:36 +00001435 R.setContextRange(SS->getRange());
1436
1437 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001438 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001439
Douglas Gregore861bac2009-08-25 22:51:20 +00001440 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001441 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001442 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001443 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001444 }
1445
Mike Stump11289f42009-09-09 15:08:12 +00001446 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001447 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001448}
1449
Douglas Gregor889ceb72009-02-03 19:21:40 +00001450
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001451/// @brief Produce a diagnostic describing the ambiguity that resulted
1452/// from name lookup.
1453///
1454/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001455///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001456/// @param Name The name of the entity that name lookup was
1457/// searching for.
1458///
1459/// @param NameLoc The location of the name within the source code.
1460///
1461/// @param LookupRange A source range that provides more
1462/// source-location information concerning the lookup itself. For
1463/// example, this range might highlight a nested-name-specifier that
1464/// precedes the name.
1465///
1466/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001467bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001468 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1469
John McCall27b18f82009-11-17 02:14:36 +00001470 DeclarationName Name = Result.getLookupName();
1471 SourceLocation NameLoc = Result.getNameLoc();
1472 SourceRange LookupRange = Result.getContextRange();
1473
John McCall6538c932009-10-10 05:48:19 +00001474 switch (Result.getAmbiguityKind()) {
1475 case LookupResult::AmbiguousBaseSubobjects: {
1476 CXXBasePaths *Paths = Result.getBasePaths();
1477 QualType SubobjectType = Paths->front().back().Base->getType();
1478 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1479 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1480 << LookupRange;
1481
1482 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1483 while (isa<CXXMethodDecl>(*Found) &&
1484 cast<CXXMethodDecl>(*Found)->isStatic())
1485 ++Found;
1486
1487 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1488
1489 return true;
1490 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001491
John McCall6538c932009-10-10 05:48:19 +00001492 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001493 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1494 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001495
1496 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001497 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001498 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1499 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001500 Path != PathEnd; ++Path) {
1501 Decl *D = *Path->Decls.first;
1502 if (DeclsPrinted.insert(D).second)
1503 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1504 }
1505
Douglas Gregor1c846b02009-01-16 00:38:09 +00001506 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001507 }
1508
John McCall6538c932009-10-10 05:48:19 +00001509 case LookupResult::AmbiguousTagHiding: {
1510 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001511
John McCall6538c932009-10-10 05:48:19 +00001512 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1513
1514 LookupResult::iterator DI, DE = Result.end();
1515 for (DI = Result.begin(); DI != DE; ++DI)
1516 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1517 TagDecls.insert(TD);
1518 Diag(TD->getLocation(), diag::note_hidden_tag);
1519 }
1520
1521 for (DI = Result.begin(); DI != DE; ++DI)
1522 if (!isa<TagDecl>(*DI))
1523 Diag((*DI)->getLocation(), diag::note_hiding_object);
1524
1525 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001526 LookupResult::Filter F = Result.makeFilter();
1527 while (F.hasNext()) {
1528 if (TagDecls.count(F.next()))
1529 F.erase();
1530 }
1531 F.done();
John McCall6538c932009-10-10 05:48:19 +00001532
1533 return true;
1534 }
1535
1536 case LookupResult::AmbiguousReference: {
1537 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001538
John McCall6538c932009-10-10 05:48:19 +00001539 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1540 for (; DI != DE; ++DI)
1541 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001542
John McCall6538c932009-10-10 05:48:19 +00001543 return true;
1544 }
1545 }
1546
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001547 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001548 return true;
1549}
Douglas Gregore254f902009-02-04 00:32:51 +00001550
John McCallf24d7bb2010-05-28 18:45:08 +00001551namespace {
1552 struct AssociatedLookup {
1553 AssociatedLookup(Sema &S,
1554 Sema::AssociatedNamespaceSet &Namespaces,
1555 Sema::AssociatedClassSet &Classes)
1556 : S(S), Namespaces(Namespaces), Classes(Classes) {
1557 }
1558
1559 Sema &S;
1560 Sema::AssociatedNamespaceSet &Namespaces;
1561 Sema::AssociatedClassSet &Classes;
1562 };
1563}
1564
Mike Stump11289f42009-09-09 15:08:12 +00001565static void
John McCallf24d7bb2010-05-28 18:45:08 +00001566addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001567
Douglas Gregor8b895222010-04-30 07:08:38 +00001568static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1569 DeclContext *Ctx) {
1570 // Add the associated namespace for this class.
1571
1572 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1573 // be a locally scoped record.
1574
1575 while (Ctx->isRecord() || Ctx->isTransparentContext())
1576 Ctx = Ctx->getParent();
1577
John McCallc7e8e792009-08-07 22:18:02 +00001578 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001579 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001580}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001581
Mike Stump11289f42009-09-09 15:08:12 +00001582// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001583// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001584static void
John McCallf24d7bb2010-05-28 18:45:08 +00001585addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1586 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001587 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001588 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001589 switch (Arg.getKind()) {
1590 case TemplateArgument::Null:
1591 break;
Mike Stump11289f42009-09-09 15:08:12 +00001592
Douglas Gregor197e5f72009-07-08 07:51:57 +00001593 case TemplateArgument::Type:
1594 // [...] the namespaces and classes associated with the types of the
1595 // template arguments provided for template type parameters (excluding
1596 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001597 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001598 break;
Mike Stump11289f42009-09-09 15:08:12 +00001599
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001600 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001601 // [...] the namespaces in which any template template arguments are
1602 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001603 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001604 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001605 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001606 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001607 DeclContext *Ctx = ClassTemplate->getDeclContext();
1608 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001609 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001610 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001611 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001612 }
1613 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001614 }
1615
1616 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001617 case TemplateArgument::Integral:
1618 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001619 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001620 // associated namespaces. ]
1621 break;
Mike Stump11289f42009-09-09 15:08:12 +00001622
Douglas Gregor197e5f72009-07-08 07:51:57 +00001623 case TemplateArgument::Pack:
1624 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1625 PEnd = Arg.pack_end();
1626 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001627 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001628 break;
1629 }
1630}
1631
Douglas Gregore254f902009-02-04 00:32:51 +00001632// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001633// argument-dependent lookup with an argument of class type
1634// (C++ [basic.lookup.koenig]p2).
1635static void
John McCallf24d7bb2010-05-28 18:45:08 +00001636addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1637 CXXRecordDecl *Class) {
1638
1639 // Just silently ignore anything whose name is __va_list_tag.
1640 if (Class->getDeclName() == Result.S.VAListTagName)
1641 return;
1642
Douglas Gregore254f902009-02-04 00:32:51 +00001643 // C++ [basic.lookup.koenig]p2:
1644 // [...]
1645 // -- If T is a class type (including unions), its associated
1646 // classes are: the class itself; the class of which it is a
1647 // member, if any; and its direct and indirect base
1648 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001649 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001650
1651 // Add the class of which it is a member, if any.
1652 DeclContext *Ctx = Class->getDeclContext();
1653 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001654 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001655 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001656 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001657
Douglas Gregore254f902009-02-04 00:32:51 +00001658 // Add the class itself. If we've already seen this class, we don't
1659 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001660 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001661 return;
1662
Mike Stump11289f42009-09-09 15:08:12 +00001663 // -- If T is a template-id, its associated namespaces and classes are
1664 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001665 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001666 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001667 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001668 // namespaces in which any template template arguments are defined; and
1669 // the classes in which any member templates used as template template
1670 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001671 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001672 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001673 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1674 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1675 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001676 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001677 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001678 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001679
Douglas Gregor197e5f72009-07-08 07:51:57 +00001680 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1681 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001682 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001683 }
Mike Stump11289f42009-09-09 15:08:12 +00001684
John McCall67da35c2010-02-04 22:26:26 +00001685 // Only recurse into base classes for complete types.
1686 if (!Class->hasDefinition()) {
1687 // FIXME: we might need to instantiate templates here
1688 return;
1689 }
1690
Douglas Gregore254f902009-02-04 00:32:51 +00001691 // Add direct and indirect base classes along with their associated
1692 // namespaces.
1693 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1694 Bases.push_back(Class);
1695 while (!Bases.empty()) {
1696 // Pop this class off the stack.
1697 Class = Bases.back();
1698 Bases.pop_back();
1699
1700 // Visit the base classes.
1701 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1702 BaseEnd = Class->bases_end();
1703 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001704 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001705 // In dependent contexts, we do ADL twice, and the first time around,
1706 // the base type might be a dependent TemplateSpecializationType, or a
1707 // TemplateTypeParmType. If that happens, simply ignore it.
1708 // FIXME: If we want to support export, we probably need to add the
1709 // namespace of the template in a TemplateSpecializationType, or even
1710 // the classes and namespaces of known non-dependent arguments.
1711 if (!BaseType)
1712 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001713 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001714 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001715 // Find the associated namespace for this base class.
1716 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001717 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001718
1719 // Make sure we visit the bases of this base class.
1720 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1721 Bases.push_back(BaseDecl);
1722 }
1723 }
1724 }
1725}
1726
1727// \brief Add the associated classes and namespaces for
1728// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001729// (C++ [basic.lookup.koenig]p2).
1730static void
John McCallf24d7bb2010-05-28 18:45:08 +00001731addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001732 // C++ [basic.lookup.koenig]p2:
1733 //
1734 // For each argument type T in the function call, there is a set
1735 // of zero or more associated namespaces and a set of zero or more
1736 // associated classes to be considered. The sets of namespaces and
1737 // classes is determined entirely by the types of the function
1738 // arguments (and the namespace of any template template
1739 // argument). Typedef names and using-declarations used to specify
1740 // the types do not contribute to this set. The sets of namespaces
1741 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001742
John McCall0af3d3b2010-05-28 06:08:54 +00001743 llvm::SmallVector<const Type *, 16> Queue;
1744 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1745
Douglas Gregore254f902009-02-04 00:32:51 +00001746 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001747 switch (T->getTypeClass()) {
1748
1749#define TYPE(Class, Base)
1750#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1751#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1752#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1753#define ABSTRACT_TYPE(Class, Base)
1754#include "clang/AST/TypeNodes.def"
1755 // T is canonical. We can also ignore dependent types because
1756 // we don't need to do ADL at the definition point, but if we
1757 // wanted to implement template export (or if we find some other
1758 // use for associated classes and namespaces...) this would be
1759 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001760 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001761
John McCall0af3d3b2010-05-28 06:08:54 +00001762 // -- If T is a pointer to U or an array of U, its associated
1763 // namespaces and classes are those associated with U.
1764 case Type::Pointer:
1765 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1766 continue;
1767 case Type::ConstantArray:
1768 case Type::IncompleteArray:
1769 case Type::VariableArray:
1770 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1771 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001772
John McCall0af3d3b2010-05-28 06:08:54 +00001773 // -- If T is a fundamental type, its associated sets of
1774 // namespaces and classes are both empty.
1775 case Type::Builtin:
1776 break;
1777
1778 // -- If T is a class type (including unions), its associated
1779 // classes are: the class itself; the class of which it is a
1780 // member, if any; and its direct and indirect base
1781 // classes. Its associated namespaces are the namespaces in
1782 // which its associated classes are defined.
1783 case Type::Record: {
1784 CXXRecordDecl *Class
1785 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001786 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001787 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001788 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001789
John McCall0af3d3b2010-05-28 06:08:54 +00001790 // -- If T is an enumeration type, its associated namespace is
1791 // the namespace in which it is defined. If it is class
1792 // member, its associated class is the member’s class; else
1793 // it has no associated class.
1794 case Type::Enum: {
1795 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001796
John McCall0af3d3b2010-05-28 06:08:54 +00001797 DeclContext *Ctx = Enum->getDeclContext();
1798 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001799 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001800
John McCall0af3d3b2010-05-28 06:08:54 +00001801 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001802 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001803
John McCall0af3d3b2010-05-28 06:08:54 +00001804 break;
1805 }
1806
1807 // -- If T is a function type, its associated namespaces and
1808 // classes are those associated with the function parameter
1809 // types and those associated with the return type.
1810 case Type::FunctionProto: {
1811 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1812 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1813 ArgEnd = Proto->arg_type_end();
1814 Arg != ArgEnd; ++Arg)
1815 Queue.push_back(Arg->getTypePtr());
1816 // fallthrough
1817 }
1818 case Type::FunctionNoProto: {
1819 const FunctionType *FnType = cast<FunctionType>(T);
1820 T = FnType->getResultType().getTypePtr();
1821 continue;
1822 }
1823
1824 // -- If T is a pointer to a member function of a class X, its
1825 // associated namespaces and classes are those associated
1826 // with the function parameter types and return type,
1827 // together with those associated with X.
1828 //
1829 // -- If T is a pointer to a data member of class X, its
1830 // associated namespaces and classes are those associated
1831 // with the member type together with those associated with
1832 // X.
1833 case Type::MemberPointer: {
1834 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1835
1836 // Queue up the class type into which this points.
1837 Queue.push_back(MemberPtr->getClass());
1838
1839 // And directly continue with the pointee type.
1840 T = MemberPtr->getPointeeType().getTypePtr();
1841 continue;
1842 }
1843
1844 // As an extension, treat this like a normal pointer.
1845 case Type::BlockPointer:
1846 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1847 continue;
1848
1849 // References aren't covered by the standard, but that's such an
1850 // obvious defect that we cover them anyway.
1851 case Type::LValueReference:
1852 case Type::RValueReference:
1853 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1854 continue;
1855
1856 // These are fundamental types.
1857 case Type::Vector:
1858 case Type::ExtVector:
1859 case Type::Complex:
1860 break;
1861
1862 // These are ignored by ADL.
1863 case Type::ObjCObject:
1864 case Type::ObjCInterface:
1865 case Type::ObjCObjectPointer:
1866 break;
1867 }
1868
1869 if (Queue.empty()) break;
1870 T = Queue.back();
1871 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001872 }
Douglas Gregore254f902009-02-04 00:32:51 +00001873}
1874
1875/// \brief Find the associated classes and namespaces for
1876/// argument-dependent lookup for a call with the given set of
1877/// arguments.
1878///
1879/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001880/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001881/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001882void
Douglas Gregore254f902009-02-04 00:32:51 +00001883Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1884 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001885 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001886 AssociatedNamespaces.clear();
1887 AssociatedClasses.clear();
1888
John McCallf24d7bb2010-05-28 18:45:08 +00001889 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1890
Douglas Gregore254f902009-02-04 00:32:51 +00001891 // C++ [basic.lookup.koenig]p2:
1892 // For each argument type T in the function call, there is a set
1893 // of zero or more associated namespaces and a set of zero or more
1894 // associated classes to be considered. The sets of namespaces and
1895 // classes is determined entirely by the types of the function
1896 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001897 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001898 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1899 Expr *Arg = Args[ArgIdx];
1900
1901 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00001902 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001903 continue;
1904 }
1905
1906 // [...] In addition, if the argument is the name or address of a
1907 // set of overloaded functions and/or function templates, its
1908 // associated classes and namespaces are the union of those
1909 // associated with each of the members of the set: the namespace
1910 // in which the function or function template is defined and the
1911 // classes and namespaces associated with its (non-dependent)
1912 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001913 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001914 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1915 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1916 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001917
John McCallf24d7bb2010-05-28 18:45:08 +00001918 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1919 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00001920
John McCallf24d7bb2010-05-28 18:45:08 +00001921 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1922 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001923 // Look through any using declarations to find the underlying function.
1924 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001925
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001926 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1927 if (!FDecl)
1928 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001929
1930 // Add the classes and namespaces associated with the parameter
1931 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00001932 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001933 }
1934 }
1935}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001936
1937/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1938/// an acceptable non-member overloaded operator for a call whose
1939/// arguments have types T1 (and, if non-empty, T2). This routine
1940/// implements the check in C++ [over.match.oper]p3b2 concerning
1941/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001942static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001943IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1944 QualType T1, QualType T2,
1945 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001946 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1947 return true;
1948
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001949 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1950 return true;
1951
John McCall9dd450b2009-09-21 23:43:11 +00001952 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001953 if (Proto->getNumArgs() < 1)
1954 return false;
1955
1956 if (T1->isEnumeralType()) {
1957 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001958 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001959 return true;
1960 }
1961
1962 if (Proto->getNumArgs() < 2)
1963 return false;
1964
1965 if (!T2.isNull() && T2->isEnumeralType()) {
1966 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001967 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001968 return true;
1969 }
1970
1971 return false;
1972}
1973
John McCall5cebab12009-11-18 07:57:50 +00001974NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001975 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00001976 LookupNameKind NameKind,
1977 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001978 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00001979 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00001980 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00001981}
1982
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001983/// \brief Find the protocol with the given name, if any.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001984ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
1985 SourceLocation IdLoc) {
1986 Decl *D = LookupSingleName(TUScope, II, IdLoc,
1987 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001988 return cast_or_null<ObjCProtocolDecl>(D);
1989}
1990
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001991void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001992 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00001993 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001994 // C++ [over.match.oper]p3:
1995 // -- The set of non-member candidates is the result of the
1996 // unqualified lookup of operator@ in the context of the
1997 // expression according to the usual rules for name lookup in
1998 // unqualified function calls (3.4.2) except that all member
1999 // functions are ignored. However, if no operand has a class
2000 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002001 // that have a first parameter of type T1 or "reference to
2002 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002003 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002004 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002005 // when T2 is an enumeration type, are candidate functions.
2006 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002007 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2008 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002009
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002010 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2011
John McCall9f3059a2009-10-09 21:13:30 +00002012 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002013 return;
2014
2015 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2016 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002017 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2018 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002019 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002020 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002021 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002022 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002023 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002024 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002025 // later?
2026 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002027 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002028 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002029 }
2030}
2031
Douglas Gregor52b72822010-07-02 23:12:18 +00002032/// \brief Look up the constructors for the given class.
2033DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +00002034 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002035 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2036 if (!Class->hasDeclaredDefaultConstructor())
2037 DeclareImplicitDefaultConstructor(Class);
2038 if (!Class->hasDeclaredCopyConstructor())
2039 DeclareImplicitCopyConstructor(Class);
2040 }
Douglas Gregora6d69502010-07-02 23:41:54 +00002041
Douglas Gregor52b72822010-07-02 23:12:18 +00002042 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2043 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2044 return Class->lookup(Name);
2045}
2046
Douglas Gregore71edda2010-07-01 22:47:18 +00002047/// \brief Look for the destructor of the given class.
2048///
2049/// During semantic analysis, this routine should be used in lieu of
2050/// CXXRecordDecl::getDestructor().
2051///
2052/// \returns The destructor for this class.
2053CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +00002054 // If the destructor has not yet been declared, do so now.
2055 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2056 !Class->hasDeclaredDestructor())
2057 DeclareImplicitDestructor(Class);
2058
Douglas Gregore71edda2010-07-01 22:47:18 +00002059 return Class->getDestructor();
2060}
2061
John McCall8fe68082010-01-26 07:16:45 +00002062void ADLResult::insert(NamedDecl *New) {
2063 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2064
2065 // If we haven't yet seen a decl for this key, or the last decl
2066 // was exactly this one, we're done.
2067 if (Old == 0 || Old == New) {
2068 Old = New;
2069 return;
2070 }
2071
2072 // Otherwise, decide which is a more recent redeclaration.
2073 FunctionDecl *OldFD, *NewFD;
2074 if (isa<FunctionTemplateDecl>(New)) {
2075 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2076 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2077 } else {
2078 OldFD = cast<FunctionDecl>(Old);
2079 NewFD = cast<FunctionDecl>(New);
2080 }
2081
2082 FunctionDecl *Cursor = NewFD;
2083 while (true) {
2084 Cursor = Cursor->getPreviousDeclaration();
2085
2086 // If we got to the end without finding OldFD, OldFD is the newer
2087 // declaration; leave things as they are.
2088 if (!Cursor) return;
2089
2090 // If we do find OldFD, then NewFD is newer.
2091 if (Cursor == OldFD) break;
2092
2093 // Otherwise, keep looking.
2094 }
2095
2096 Old = New;
2097}
2098
Sebastian Redlc057f422009-10-23 19:23:15 +00002099void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002100 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00002101 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002102 // Find all of the associated namespaces and classes based on the
2103 // arguments we have.
2104 AssociatedNamespaceSet AssociatedNamespaces;
2105 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002106 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002107 AssociatedNamespaces,
2108 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002109
Sebastian Redlc057f422009-10-23 19:23:15 +00002110 QualType T1, T2;
2111 if (Operator) {
2112 T1 = Args[0]->getType();
2113 if (NumArgs >= 2)
2114 T2 = Args[1]->getType();
2115 }
2116
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002117 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002118 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2119 // and let Y be the lookup set produced by argument dependent
2120 // lookup (defined as follows). If X contains [...] then Y is
2121 // empty. Otherwise Y is the set of declarations found in the
2122 // namespaces associated with the argument types as described
2123 // below. The set of declarations found by the lookup of the name
2124 // is the union of X and Y.
2125 //
2126 // Here, we compute Y and add its members to the overloaded
2127 // candidate set.
2128 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002129 NSEnd = AssociatedNamespaces.end();
2130 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002131 // When considering an associated namespace, the lookup is the
2132 // same as the lookup performed when the associated namespace is
2133 // used as a qualifier (3.4.3.2) except that:
2134 //
2135 // -- Any using-directives in the associated namespace are
2136 // ignored.
2137 //
John McCallc7e8e792009-08-07 22:18:02 +00002138 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002139 // associated classes are visible within their respective
2140 // namespaces even if they are not visible during an ordinary
2141 // lookup (11.4).
2142 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002143 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002144 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002145 // If the only declaration here is an ordinary friend, consider
2146 // it only if it was declared in an associated classes.
2147 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002148 DeclContext *LexDC = D->getLexicalDeclContext();
2149 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2150 continue;
2151 }
Mike Stump11289f42009-09-09 15:08:12 +00002152
John McCall91f61fc2010-01-26 06:04:06 +00002153 if (isa<UsingShadowDecl>(D))
2154 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002155
John McCall91f61fc2010-01-26 06:04:06 +00002156 if (isa<FunctionDecl>(D)) {
2157 if (Operator &&
2158 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2159 T1, T2, Context))
2160 continue;
John McCall8fe68082010-01-26 07:16:45 +00002161 } else if (!isa<FunctionTemplateDecl>(D))
2162 continue;
2163
2164 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002165 }
2166 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002167}
Douglas Gregor2d435302009-12-30 17:04:44 +00002168
2169//----------------------------------------------------------------------------
2170// Search for all visible declarations.
2171//----------------------------------------------------------------------------
2172VisibleDeclConsumer::~VisibleDeclConsumer() { }
2173
2174namespace {
2175
2176class ShadowContextRAII;
2177
2178class VisibleDeclsRecord {
2179public:
2180 /// \brief An entry in the shadow map, which is optimized to store a
2181 /// single declaration (the common case) but can also store a list
2182 /// of declarations.
2183 class ShadowMapEntry {
2184 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2185
2186 /// \brief Contains either the solitary NamedDecl * or a vector
2187 /// of declarations.
2188 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2189
2190 public:
2191 ShadowMapEntry() : DeclOrVector() { }
2192
2193 void Add(NamedDecl *ND);
2194 void Destroy();
2195
2196 // Iteration.
2197 typedef NamedDecl **iterator;
2198 iterator begin();
2199 iterator end();
2200 };
2201
2202private:
2203 /// \brief A mapping from declaration names to the declarations that have
2204 /// this name within a particular scope.
2205 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2206
2207 /// \brief A list of shadow maps, which is used to model name hiding.
2208 std::list<ShadowMap> ShadowMaps;
2209
2210 /// \brief The declaration contexts we have already visited.
2211 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2212
2213 friend class ShadowContextRAII;
2214
2215public:
2216 /// \brief Determine whether we have already visited this context
2217 /// (and, if not, note that we are going to visit that context now).
2218 bool visitedContext(DeclContext *Ctx) {
2219 return !VisitedContexts.insert(Ctx);
2220 }
2221
2222 /// \brief Determine whether the given declaration is hidden in the
2223 /// current scope.
2224 ///
2225 /// \returns the declaration that hides the given declaration, or
2226 /// NULL if no such declaration exists.
2227 NamedDecl *checkHidden(NamedDecl *ND);
2228
2229 /// \brief Add a declaration to the current shadow map.
2230 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2231};
2232
2233/// \brief RAII object that records when we've entered a shadow context.
2234class ShadowContextRAII {
2235 VisibleDeclsRecord &Visible;
2236
2237 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2238
2239public:
2240 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2241 Visible.ShadowMaps.push_back(ShadowMap());
2242 }
2243
2244 ~ShadowContextRAII() {
2245 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2246 EEnd = Visible.ShadowMaps.back().end();
2247 E != EEnd;
2248 ++E)
2249 E->second.Destroy();
2250
2251 Visible.ShadowMaps.pop_back();
2252 }
2253};
2254
2255} // end anonymous namespace
2256
2257void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2258 if (DeclOrVector.isNull()) {
2259 // 0 - > 1 elements: just set the single element information.
2260 DeclOrVector = ND;
2261 return;
2262 }
2263
2264 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2265 // 1 -> 2 elements: create the vector of results and push in the
2266 // existing declaration.
2267 DeclVector *Vec = new DeclVector;
2268 Vec->push_back(PrevND);
2269 DeclOrVector = Vec;
2270 }
2271
2272 // Add the new element to the end of the vector.
2273 DeclOrVector.get<DeclVector*>()->push_back(ND);
2274}
2275
2276void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2277 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2278 delete Vec;
2279 DeclOrVector = ((NamedDecl *)0);
2280 }
2281}
2282
2283VisibleDeclsRecord::ShadowMapEntry::iterator
2284VisibleDeclsRecord::ShadowMapEntry::begin() {
2285 if (DeclOrVector.isNull())
2286 return 0;
2287
2288 if (DeclOrVector.dyn_cast<NamedDecl *>())
2289 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2290
2291 return DeclOrVector.get<DeclVector *>()->begin();
2292}
2293
2294VisibleDeclsRecord::ShadowMapEntry::iterator
2295VisibleDeclsRecord::ShadowMapEntry::end() {
2296 if (DeclOrVector.isNull())
2297 return 0;
2298
2299 if (DeclOrVector.dyn_cast<NamedDecl *>())
2300 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2301
2302 return DeclOrVector.get<DeclVector *>()->end();
2303}
2304
2305NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002306 // Look through using declarations.
2307 ND = ND->getUnderlyingDecl();
2308
Douglas Gregor2d435302009-12-30 17:04:44 +00002309 unsigned IDNS = ND->getIdentifierNamespace();
2310 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2311 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2312 SM != SMEnd; ++SM) {
2313 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2314 if (Pos == SM->end())
2315 continue;
2316
2317 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2318 IEnd = Pos->second.end();
2319 I != IEnd; ++I) {
2320 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002321 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor2d435302009-12-30 17:04:44 +00002322 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2323 Decl::IDNS_ObjCProtocol)))
2324 continue;
2325
2326 // Protocols are in distinct namespaces from everything else.
2327 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2328 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2329 (*I)->getIdentifierNamespace() != IDNS)
2330 continue;
2331
Douglas Gregor09bbc652010-01-14 15:47:35 +00002332 // Functions and function templates in the same scope overload
2333 // rather than hide. FIXME: Look for hiding based on function
2334 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002335 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002336 ND->isFunctionOrFunctionTemplate() &&
2337 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002338 continue;
2339
Douglas Gregor2d435302009-12-30 17:04:44 +00002340 // We've found a declaration that hides this one.
2341 return *I;
2342 }
2343 }
2344
2345 return 0;
2346}
2347
2348static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2349 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002350 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002351 VisibleDeclConsumer &Consumer,
2352 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002353 if (!Ctx)
2354 return;
2355
Douglas Gregor2d435302009-12-30 17:04:44 +00002356 // Make sure we don't visit the same context twice.
2357 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2358 return;
2359
Douglas Gregor7454c562010-07-02 20:37:36 +00002360 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2361 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2362
Douglas Gregor2d435302009-12-30 17:04:44 +00002363 // Enumerate all of the results in this context.
2364 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2365 CurCtx = CurCtx->getNextContext()) {
2366 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2367 DEnd = CurCtx->decls_end();
2368 D != DEnd; ++D) {
2369 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2370 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002371 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002372 Visited.add(ND);
2373 }
2374
2375 // Visit transparent contexts inside this context.
2376 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2377 if (InnerCtx->isTransparentContext())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002378 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002379 Consumer, Visited);
2380 }
2381 }
2382 }
2383
2384 // Traverse using directives for qualified name lookup.
2385 if (QualifiedNameLookup) {
2386 ShadowContextRAII Shadow(Visited);
2387 DeclContext::udir_iterator I, E;
2388 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2389 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002390 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002391 }
2392 }
2393
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002394 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002395 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002396 if (!Record->hasDefinition())
2397 return;
2398
Douglas Gregor2d435302009-12-30 17:04:44 +00002399 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2400 BEnd = Record->bases_end();
2401 B != BEnd; ++B) {
2402 QualType BaseType = B->getType();
2403
2404 // Don't look into dependent bases, because name lookup can't look
2405 // there anyway.
2406 if (BaseType->isDependentType())
2407 continue;
2408
2409 const RecordType *Record = BaseType->getAs<RecordType>();
2410 if (!Record)
2411 continue;
2412
2413 // FIXME: It would be nice to be able to determine whether referencing
2414 // a particular member would be ambiguous. For example, given
2415 //
2416 // struct A { int member; };
2417 // struct B { int member; };
2418 // struct C : A, B { };
2419 //
2420 // void f(C *c) { c->### }
2421 //
2422 // accessing 'member' would result in an ambiguity. However, we
2423 // could be smart enough to qualify the member with the base
2424 // class, e.g.,
2425 //
2426 // c->B::member
2427 //
2428 // or
2429 //
2430 // c->A::member
2431
2432 // Find results in this base class (and its bases).
2433 ShadowContextRAII Shadow(Visited);
2434 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002435 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002436 }
2437 }
2438
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002439 // Traverse the contexts of Objective-C classes.
2440 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2441 // Traverse categories.
2442 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2443 Category; Category = Category->getNextClassCategory()) {
2444 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002445 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2446 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002447 }
2448
2449 // Traverse protocols.
2450 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2451 E = IFace->protocol_end(); I != E; ++I) {
2452 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002453 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2454 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002455 }
2456
2457 // Traverse the superclass.
2458 if (IFace->getSuperClass()) {
2459 ShadowContextRAII Shadow(Visited);
2460 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002461 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002462 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002463
2464 // If there is an implementation, traverse it. We do this to find
2465 // synthesized ivars.
2466 if (IFace->getImplementation()) {
2467 ShadowContextRAII Shadow(Visited);
2468 LookupVisibleDecls(IFace->getImplementation(), Result,
2469 QualifiedNameLookup, true, Consumer, Visited);
2470 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002471 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2472 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2473 E = Protocol->protocol_end(); I != E; ++I) {
2474 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002475 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2476 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002477 }
2478 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2479 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2480 E = Category->protocol_end(); I != E; ++I) {
2481 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002482 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2483 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002484 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002485
2486 // If there is an implementation, traverse it.
2487 if (Category->getImplementation()) {
2488 ShadowContextRAII Shadow(Visited);
2489 LookupVisibleDecls(Category->getImplementation(), Result,
2490 QualifiedNameLookup, true, Consumer, Visited);
2491 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002492 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002493}
2494
2495static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2496 UnqualUsingDirectiveSet &UDirs,
2497 VisibleDeclConsumer &Consumer,
2498 VisibleDeclsRecord &Visited) {
2499 if (!S)
2500 return;
2501
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002502 if (!S->getEntity() || !S->getParent() ||
2503 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2504 // Walk through the declarations in this Scope.
2505 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2506 D != DEnd; ++D) {
2507 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2508 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002509 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002510 Visited.add(ND);
2511 }
2512 }
2513 }
2514
Douglas Gregor66230062010-03-15 14:33:29 +00002515 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002516 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002517 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002518 // Look into this scope's declaration context, along with any of its
2519 // parent lookup contexts (e.g., enclosing classes), up to the point
2520 // where we hit the context stored in the next outer scope.
2521 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002522 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor2d435302009-12-30 17:04:44 +00002523
Douglas Gregorea166062010-03-15 15:26:48 +00002524 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002525 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002526 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2527 if (Method->isInstanceMethod()) {
2528 // For instance methods, look for ivars in the method's interface.
2529 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2530 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002531 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2532 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2533 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002534 }
2535
2536 // We've already performed all of the name lookup that we need
2537 // to for Objective-C methods; the next context will be the
2538 // outer scope.
2539 break;
2540 }
2541
Douglas Gregor2d435302009-12-30 17:04:44 +00002542 if (Ctx->isFunctionOrMethod())
2543 continue;
2544
2545 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002546 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002547 }
2548 } else if (!S->getParent()) {
2549 // Look into the translation unit scope. We walk through the translation
2550 // unit's declaration context, because the Scope itself won't have all of
2551 // the declarations if we loaded a precompiled header.
2552 // FIXME: We would like the translation unit's Scope object to point to the
2553 // translation unit, so we don't need this special "if" branch. However,
2554 // doing so would force the normal C++ name-lookup code to look into the
2555 // translation unit decl when the IdentifierInfo chains would suffice.
2556 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002557 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002558 Entity = Result.getSema().Context.getTranslationUnitDecl();
2559 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002560 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002561 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002562
2563 if (Entity) {
2564 // Lookup visible declarations in any namespaces found by using
2565 // directives.
2566 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2567 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2568 for (; UI != UEnd; ++UI)
2569 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002570 Result, /*QualifiedNameLookup=*/false,
2571 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002572 }
2573
2574 // Lookup names in the parent scope.
2575 ShadowContextRAII Shadow(Visited);
2576 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2577}
2578
2579void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2580 VisibleDeclConsumer &Consumer) {
2581 // Determine the set of using directives available during
2582 // unqualified name lookup.
2583 Scope *Initial = S;
2584 UnqualUsingDirectiveSet UDirs;
2585 if (getLangOptions().CPlusPlus) {
2586 // Find the first namespace or translation-unit scope.
2587 while (S && !isNamespaceOrTranslationUnitScope(S))
2588 S = S->getParent();
2589
2590 UDirs.visitScopeChain(Initial, S);
2591 }
2592 UDirs.done();
2593
2594 // Look for visible declarations.
2595 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2596 VisibleDeclsRecord Visited;
2597 ShadowContextRAII Shadow(Visited);
2598 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2599}
2600
2601void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2602 VisibleDeclConsumer &Consumer) {
2603 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2604 VisibleDeclsRecord Visited;
2605 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002606 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2607 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002608}
2609
2610//----------------------------------------------------------------------------
2611// Typo correction
2612//----------------------------------------------------------------------------
2613
2614namespace {
2615class TypoCorrectionConsumer : public VisibleDeclConsumer {
2616 /// \brief The name written that is a typo in the source.
2617 llvm::StringRef Typo;
2618
2619 /// \brief The results found that have the smallest edit distance
2620 /// found (so far) with the typo name.
2621 llvm::SmallVector<NamedDecl *, 4> BestResults;
2622
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002623 /// \brief The keywords that have the smallest edit distance.
2624 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2625
Douglas Gregor2d435302009-12-30 17:04:44 +00002626 /// \brief The best edit distance found so far.
2627 unsigned BestEditDistance;
2628
2629public:
2630 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2631 : Typo(Typo->getName()) { }
2632
Douglas Gregor09bbc652010-01-14 15:47:35 +00002633 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002634 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002635
2636 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2637 iterator begin() const { return BestResults.begin(); }
2638 iterator end() const { return BestResults.end(); }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002639 void clear_decls() { BestResults.clear(); }
2640
2641 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002642
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002643 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2644 keyword_iterator;
2645 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2646 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2647 bool keyword_empty() const { return BestKeywords.empty(); }
2648 unsigned keyword_size() const { return BestKeywords.size(); }
2649
2650 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002651};
2652
2653}
2654
Douglas Gregor09bbc652010-01-14 15:47:35 +00002655void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2656 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002657 // Don't consider hidden names for typo correction.
2658 if (Hiding)
2659 return;
2660
2661 // Only consider entities with identifiers for names, ignoring
2662 // special names (constructors, overloaded operators, selectors,
2663 // etc.).
2664 IdentifierInfo *Name = ND->getIdentifier();
2665 if (!Name)
2666 return;
2667
2668 // Compute the edit distance between the typo and the name of this
2669 // entity. If this edit distance is not worse than the best edit
2670 // distance we've seen so far, add it to the list of results.
2671 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002672 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002673 if (ED < BestEditDistance) {
2674 // This result is better than any we've seen before; clear out
2675 // the previous results.
2676 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002677 BestKeywords.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002678 BestEditDistance = ED;
2679 } else if (ED > BestEditDistance) {
2680 // This result is worse than the best results we've seen so far;
2681 // ignore it.
2682 return;
2683 }
2684 } else
2685 BestEditDistance = ED;
2686
2687 BestResults.push_back(ND);
2688}
2689
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002690void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2691 llvm::StringRef Keyword) {
2692 // Compute the edit distance between the typo and this keyword.
2693 // If this edit distance is not worse than the best edit
2694 // distance we've seen so far, add it to the list of results.
2695 unsigned ED = Typo.edit_distance(Keyword);
2696 if (!BestResults.empty() || !BestKeywords.empty()) {
2697 if (ED < BestEditDistance) {
2698 BestResults.clear();
2699 BestKeywords.clear();
2700 BestEditDistance = ED;
2701 } else if (ED > BestEditDistance) {
2702 // This result is worse than the best results we've seen so far;
2703 // ignore it.
2704 return;
2705 }
2706 } else
2707 BestEditDistance = ED;
2708
2709 BestKeywords.push_back(&Context.Idents.get(Keyword));
2710}
2711
Douglas Gregor2d435302009-12-30 17:04:44 +00002712/// \brief Try to "correct" a typo in the source code by finding
2713/// visible declarations whose names are similar to the name that was
2714/// present in the source code.
2715///
2716/// \param Res the \c LookupResult structure that contains the name
2717/// that was present in the source code along with the name-lookup
2718/// criteria used to search for the name. On success, this structure
2719/// will contain the results of name lookup.
2720///
2721/// \param S the scope in which name lookup occurs.
2722///
2723/// \param SS the nested-name-specifier that precedes the name we're
2724/// looking for, if present.
2725///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002726/// \param MemberContext if non-NULL, the context in which to look for
2727/// a member access expression.
2728///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002729/// \param EnteringContext whether we're entering the context described by
2730/// the nested-name-specifier SS.
2731///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002732/// \param CTC The context in which typo correction occurs, which impacts the
2733/// set of keywords permitted.
2734///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002735/// \param OPT when non-NULL, the search for visible declarations will
2736/// also walk the protocols in the qualified interfaces of \p OPT.
2737///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002738/// \returns the corrected name if the typo was corrected, otherwise returns an
2739/// empty \c DeclarationName. When a typo was corrected, the result structure
2740/// may contain the results of name lookup for the correct name or it may be
2741/// empty.
2742DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002743 DeclContext *MemberContext,
2744 bool EnteringContext,
2745 CorrectTypoContext CTC,
2746 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00002747 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002748 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002749
2750 // Provide a stop gap for files that are just seriously broken. Trying
2751 // to correct all typos can turn into a HUGE performance penalty, causing
2752 // some files to take minutes to get rejected by the parser.
2753 // FIXME: Is this the right solution?
2754 if (TyposCorrected == 20)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002755 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002756 ++TyposCorrected;
Ted Kremeneke51136e2010-01-06 00:23:04 +00002757
Douglas Gregor2d435302009-12-30 17:04:44 +00002758 // We only attempt to correct typos for identifiers.
2759 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2760 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002761 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002762
2763 // If the scope specifier itself was invalid, don't try to correct
2764 // typos.
2765 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002766 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002767
2768 // Never try to correct typos during template deduction or
2769 // instantiation.
2770 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002771 return DeclarationName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002772
Douglas Gregor2d435302009-12-30 17:04:44 +00002773 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002774
2775 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002776 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002777 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002778
2779 // Look in qualified interfaces.
2780 if (OPT) {
2781 for (ObjCObjectPointerType::qual_iterator
2782 I = OPT->qual_begin(), E = OPT->qual_end();
2783 I != E; ++I)
2784 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2785 }
2786 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002787 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2788 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002789 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002790
2791 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2792 } else {
2793 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2794 }
2795
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002796 // Add context-dependent keywords.
2797 bool WantTypeSpecifiers = false;
2798 bool WantExpressionKeywords = false;
2799 bool WantCXXNamedCasts = false;
2800 bool WantRemainingKeywords = false;
2801 switch (CTC) {
2802 case CTC_Unknown:
2803 WantTypeSpecifiers = true;
2804 WantExpressionKeywords = true;
2805 WantCXXNamedCasts = true;
2806 WantRemainingKeywords = true;
Douglas Gregor5fd04d42010-05-18 16:14:23 +00002807
2808 if (ObjCMethodDecl *Method = getCurMethodDecl())
2809 if (Method->getClassInterface() &&
2810 Method->getClassInterface()->getSuperClass())
2811 Consumer.addKeywordResult(Context, "super");
2812
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002813 break;
2814
2815 case CTC_NoKeywords:
2816 break;
2817
2818 case CTC_Type:
2819 WantTypeSpecifiers = true;
2820 break;
2821
2822 case CTC_ObjCMessageReceiver:
2823 Consumer.addKeywordResult(Context, "super");
2824 // Fall through to handle message receivers like expressions.
2825
2826 case CTC_Expression:
2827 if (getLangOptions().CPlusPlus)
2828 WantTypeSpecifiers = true;
2829 WantExpressionKeywords = true;
2830 // Fall through to get C++ named casts.
2831
2832 case CTC_CXXCasts:
2833 WantCXXNamedCasts = true;
2834 break;
2835
2836 case CTC_MemberLookup:
2837 if (getLangOptions().CPlusPlus)
2838 Consumer.addKeywordResult(Context, "template");
2839 break;
2840 }
2841
2842 if (WantTypeSpecifiers) {
2843 // Add type-specifier keywords to the set of results.
2844 const char *CTypeSpecs[] = {
2845 "char", "const", "double", "enum", "float", "int", "long", "short",
2846 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2847 "_Complex", "_Imaginary",
2848 // storage-specifiers as well
2849 "extern", "inline", "static", "typedef"
2850 };
2851
2852 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2853 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2854 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2855
2856 if (getLangOptions().C99)
2857 Consumer.addKeywordResult(Context, "restrict");
2858 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2859 Consumer.addKeywordResult(Context, "bool");
2860
2861 if (getLangOptions().CPlusPlus) {
2862 Consumer.addKeywordResult(Context, "class");
2863 Consumer.addKeywordResult(Context, "typename");
2864 Consumer.addKeywordResult(Context, "wchar_t");
2865
2866 if (getLangOptions().CPlusPlus0x) {
2867 Consumer.addKeywordResult(Context, "char16_t");
2868 Consumer.addKeywordResult(Context, "char32_t");
2869 Consumer.addKeywordResult(Context, "constexpr");
2870 Consumer.addKeywordResult(Context, "decltype");
2871 Consumer.addKeywordResult(Context, "thread_local");
2872 }
2873 }
2874
2875 if (getLangOptions().GNUMode)
2876 Consumer.addKeywordResult(Context, "typeof");
2877 }
2878
Douglas Gregor86ad0852010-05-18 16:30:22 +00002879 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002880 Consumer.addKeywordResult(Context, "const_cast");
2881 Consumer.addKeywordResult(Context, "dynamic_cast");
2882 Consumer.addKeywordResult(Context, "reinterpret_cast");
2883 Consumer.addKeywordResult(Context, "static_cast");
2884 }
2885
2886 if (WantExpressionKeywords) {
2887 Consumer.addKeywordResult(Context, "sizeof");
2888 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2889 Consumer.addKeywordResult(Context, "false");
2890 Consumer.addKeywordResult(Context, "true");
2891 }
2892
2893 if (getLangOptions().CPlusPlus) {
2894 const char *CXXExprs[] = {
2895 "delete", "new", "operator", "throw", "typeid"
2896 };
2897 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2898 for (unsigned I = 0; I != NumCXXExprs; ++I)
2899 Consumer.addKeywordResult(Context, CXXExprs[I]);
2900
2901 if (isa<CXXMethodDecl>(CurContext) &&
2902 cast<CXXMethodDecl>(CurContext)->isInstance())
2903 Consumer.addKeywordResult(Context, "this");
2904
2905 if (getLangOptions().CPlusPlus0x) {
2906 Consumer.addKeywordResult(Context, "alignof");
2907 Consumer.addKeywordResult(Context, "nullptr");
2908 }
2909 }
2910 }
2911
2912 if (WantRemainingKeywords) {
2913 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2914 // Statements.
2915 const char *CStmts[] = {
2916 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2917 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2918 for (unsigned I = 0; I != NumCStmts; ++I)
2919 Consumer.addKeywordResult(Context, CStmts[I]);
2920
2921 if (getLangOptions().CPlusPlus) {
2922 Consumer.addKeywordResult(Context, "catch");
2923 Consumer.addKeywordResult(Context, "try");
2924 }
2925
2926 if (S && S->getBreakParent())
2927 Consumer.addKeywordResult(Context, "break");
2928
2929 if (S && S->getContinueParent())
2930 Consumer.addKeywordResult(Context, "continue");
2931
2932 if (!getSwitchStack().empty()) {
2933 Consumer.addKeywordResult(Context, "case");
2934 Consumer.addKeywordResult(Context, "default");
2935 }
2936 } else {
2937 if (getLangOptions().CPlusPlus) {
2938 Consumer.addKeywordResult(Context, "namespace");
2939 Consumer.addKeywordResult(Context, "template");
2940 }
2941
2942 if (S && S->isClassScope()) {
2943 Consumer.addKeywordResult(Context, "explicit");
2944 Consumer.addKeywordResult(Context, "friend");
2945 Consumer.addKeywordResult(Context, "mutable");
2946 Consumer.addKeywordResult(Context, "private");
2947 Consumer.addKeywordResult(Context, "protected");
2948 Consumer.addKeywordResult(Context, "public");
2949 Consumer.addKeywordResult(Context, "virtual");
2950 }
2951 }
2952
2953 if (getLangOptions().CPlusPlus) {
2954 Consumer.addKeywordResult(Context, "using");
2955
2956 if (getLangOptions().CPlusPlus0x)
2957 Consumer.addKeywordResult(Context, "static_assert");
2958 }
2959 }
2960
2961 // If we haven't found anything, we're done.
Douglas Gregor2d435302009-12-30 17:04:44 +00002962 if (Consumer.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002963 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002964
2965 // Only allow a single, closest name in the result set (it's okay to
2966 // have overloads of that name, though).
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002967 DeclarationName BestName;
2968 NamedDecl *BestIvarOrPropertyDecl = 0;
2969 bool FoundIvarOrPropertyDecl = false;
2970
2971 // Check all of the declaration results to find the best name so far.
2972 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2973 IEnd = Consumer.end();
2974 I != IEnd; ++I) {
2975 if (!BestName)
2976 BestName = (*I)->getDeclName();
2977 else if (BestName != (*I)->getDeclName())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002978 return DeclarationName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002979
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002980 // \brief Keep track of either an Objective-C ivar or a property, but not
2981 // both.
2982 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
2983 if (FoundIvarOrPropertyDecl)
2984 BestIvarOrPropertyDecl = 0;
2985 else {
2986 BestIvarOrPropertyDecl = *I;
2987 FoundIvarOrPropertyDecl = true;
2988 }
2989 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002990 }
2991
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002992 // Now check all of the keyword results to find the best name.
2993 switch (Consumer.keyword_size()) {
2994 case 0:
2995 // No keywords matched.
2996 break;
2997
2998 case 1:
2999 // If we already have a name
3000 if (!BestName) {
3001 // We did not have anything previously,
3002 BestName = *Consumer.keyword_begin();
3003 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
3004 // We have a declaration with the same name as a context-sensitive
3005 // keyword. The keyword takes precedence.
3006 BestIvarOrPropertyDecl = 0;
3007 FoundIvarOrPropertyDecl = false;
3008 Consumer.clear_decls();
Douglas Gregor86ad0852010-05-18 16:30:22 +00003009 } else if (CTC == CTC_ObjCMessageReceiver &&
3010 (*Consumer.keyword_begin())->isStr("super")) {
3011 // In an Objective-C message send, give the "super" keyword a slight
3012 // edge over entities not in function or method scope.
3013 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3014 IEnd = Consumer.end();
3015 I != IEnd; ++I) {
3016 if ((*I)->getDeclName() == BestName) {
3017 if ((*I)->getDeclContext()->isFunctionOrMethod())
3018 return DeclarationName();
3019 }
3020 }
3021
3022 // Everything found was outside a function or method; the 'super'
3023 // keyword takes precedence.
3024 BestIvarOrPropertyDecl = 0;
3025 FoundIvarOrPropertyDecl = false;
3026 Consumer.clear_decls();
3027 BestName = *Consumer.keyword_begin();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003028 } else {
3029 // Name collision; we will not correct typos.
3030 return DeclarationName();
3031 }
3032 break;
3033
3034 default:
3035 // Name collision; we will not correct typos.
3036 return DeclarationName();
3037 }
3038
Douglas Gregor2d435302009-12-30 17:04:44 +00003039 // BestName is the closest viable name to what the user
3040 // typed. However, to make sure that we don't pick something that's
3041 // way off, make sure that the user typed at least 3 characters for
3042 // each correction.
3043 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003044 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
3045 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003046 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003047
3048 // Perform name lookup again with the name we chose, and declare
3049 // success if we found something that was not ambiguous.
3050 Res.clear();
3051 Res.setLookupName(BestName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003052
3053 // If we found an ivar or property, add that result; no further
3054 // lookup is required.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003055 if (BestIvarOrPropertyDecl)
3056 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003057 // If we're looking into the context of a member, perform qualified
3058 // name lookup on the best name.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003059 else if (!Consumer.keyword_empty()) {
3060 // The best match was a keyword. Return it.
3061 return BestName;
3062 } else if (MemberContext)
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003063 LookupQualifiedName(Res, MemberContext);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003064 // Perform lookup as if we had just parsed the best name.
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003065 else
3066 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3067 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00003068
3069 if (Res.isAmbiguous()) {
3070 Res.suppressDiagnostics();
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003071 return DeclarationName();
Douglas Gregor598b08f2009-12-31 05:20:13 +00003072 }
3073
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003074 if (Res.getResultKind() != LookupResult::NotFound)
3075 return BestName;
3076
3077 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003078}