blob: 2e651838df954d4a5a5485ea4e50f33457a8b855 [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6e247262009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor546be3c2009-12-30 17:04:44 +000030#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000031#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000032#include <vector>
33#include <iterator>
34#include <utility>
35#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000036
37using namespace clang;
38
John McCalld7be78a2009-11-10 07:01:13 +000039namespace {
40 class UnqualUsingEntry {
41 const DeclContext *Nominated;
42 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000043
John McCalld7be78a2009-11-10 07:01:13 +000044 public:
45 UnqualUsingEntry(const DeclContext *Nominated,
46 const DeclContext *CommonAncestor)
47 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
48 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000049
John McCalld7be78a2009-11-10 07:01:13 +000050 const DeclContext *getCommonAncestor() const {
51 return CommonAncestor;
52 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000053
John McCalld7be78a2009-11-10 07:01:13 +000054 const DeclContext *getNominatedNamespace() const {
55 return Nominated;
56 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000057
John McCalld7be78a2009-11-10 07:01:13 +000058 // Sort by the pointer value of the common ancestor.
59 struct Comparator {
60 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
61 return L.getCommonAncestor() < R.getCommonAncestor();
62 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000063
John McCalld7be78a2009-11-10 07:01:13 +000064 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
65 return E.getCommonAncestor() < DC;
66 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000067
John McCalld7be78a2009-11-10 07:01:13 +000068 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
69 return DC < E.getCommonAncestor();
70 }
71 };
72 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000073
John McCalld7be78a2009-11-10 07:01:13 +000074 /// A collection of using directives, as used by C++ unqualified
75 /// lookup.
76 class UnqualUsingDirectiveSet {
77 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000078
John McCalld7be78a2009-11-10 07:01:13 +000079 ListTy list;
80 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000081
John McCalld7be78a2009-11-10 07:01:13 +000082 public:
83 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000084
John McCalld7be78a2009-11-10 07:01:13 +000085 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
86 // C++ [namespace.udir]p1:
87 // During unqualified name lookup, the names appear as if they
88 // were declared in the nearest enclosing namespace which contains
89 // both the using-directive and the nominated namespace.
90 DeclContext *InnermostFileDC
91 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
92 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +000093
John McCalld7be78a2009-11-10 07:01:13 +000094 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +000095 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
96 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
97 visit(Ctx, EffectiveDC);
98 } else {
99 Scope::udir_iterator I = S->using_directives_begin(),
100 End = S->using_directives_end();
101
102 for (; I != End; ++I)
103 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
104 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000105 }
106 }
John McCalld7be78a2009-11-10 07:01:13 +0000107
108 // Visits a context and collect all of its using directives
109 // recursively. Treats all using directives as if they were
110 // declared in the context.
111 //
112 // A given context is only every visited once, so it is important
113 // that contexts be visited from the inside out in order to get
114 // the effective DCs right.
115 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
116 if (!visited.insert(DC))
117 return;
118
119 addUsingDirectives(DC, EffectiveDC);
120 }
121
122 // Visits a using directive and collects all of its using
123 // directives recursively. Treats all using directives as if they
124 // were declared in the effective DC.
125 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
126 DeclContext *NS = UD->getNominatedNamespace();
127 if (!visited.insert(NS))
128 return;
129
130 addUsingDirective(UD, EffectiveDC);
131 addUsingDirectives(NS, EffectiveDC);
132 }
133
134 // Adds all the using directives in a context (and those nominated
135 // by its using directives, transitively) as if they appeared in
136 // the given effective context.
137 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
138 llvm::SmallVector<DeclContext*,4> queue;
139 while (true) {
140 DeclContext::udir_iterator I, End;
141 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
142 UsingDirectiveDecl *UD = *I;
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (visited.insert(NS)) {
145 addUsingDirective(UD, EffectiveDC);
146 queue.push_back(NS);
147 }
148 }
149
150 if (queue.empty())
151 return;
152
153 DC = queue.back();
154 queue.pop_back();
155 }
156 }
157
158 // Add a using directive as if it had been declared in the given
159 // context. This helps implement C++ [namespace.udir]p3:
160 // The using-directive is transitive: if a scope contains a
161 // using-directive that nominates a second namespace that itself
162 // contains using-directives, the effect is as if the
163 // using-directives from the second namespace also appeared in
164 // the first.
165 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
166 // Find the common ancestor between the effective context and
167 // the nominated namespace.
168 DeclContext *Common = UD->getNominatedNamespace();
169 while (!Common->Encloses(EffectiveDC))
170 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000171 Common = Common->getPrimaryContext();
John McCalld7be78a2009-11-10 07:01:13 +0000172
173 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
174 }
175
176 void done() {
177 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
178 }
179
180 typedef ListTy::iterator iterator;
181 typedef ListTy::const_iterator const_iterator;
182
183 iterator begin() { return list.begin(); }
184 iterator end() { return list.end(); }
185 const_iterator begin() const { return list.begin(); }
186 const_iterator end() const { return list.end(); }
187
188 std::pair<const_iterator,const_iterator>
189 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000190 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000191 UnqualUsingEntry::Comparator());
192 }
193 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000194}
195
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000196// Retrieve the set of identifier namespaces that correspond to a
197// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000198static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
199 bool CPlusPlus,
200 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000201 unsigned IDNS = 0;
202 switch (NameKind) {
203 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000204 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000205 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000206 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCall1d7c5282009-12-18 10:40:03 +0000208 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
209 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000210 break;
211
John McCall76d32642010-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 Gregor2a3009a2009-02-03 19:21:40 +0000219 case Sema::LookupTagName:
John McCall0d6b1642010-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 Gregor2a3009a2009-02-03 19:21:40 +0000233 break;
234
235 case Sema::LookupMemberName:
236 IDNS = Decl::IDNS_Member;
237 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000238 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000239 break;
240
241 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000242 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
243 break;
244
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000245 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000246 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000247 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000248
John McCall9f54ad42009-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 Gregor8fc463a2009-04-24 00:11:27 +0000254 case Sema::LookupObjCProtocolName:
255 IDNS = Decl::IDNS_ObjCProtocol;
256 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000257 }
258 return IDNS;
259}
260
John McCall1d7c5282009-12-18 10:40:03 +0000261void LookupResult::configure() {
262 IDNS = getIDNS(LookupKind,
263 SemaRef.getLangOptions().CPlusPlus,
264 isForRedeclaration());
Douglas Gregorb5b2ccb2010-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 McCall1d7c5282009-12-18 10:40:03 +0000282}
283
John McCallf36e02d2009-10-09 21:13:30 +0000284// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000285void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000286 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000287}
288
John McCall7453ed42009-11-22 00:44:51 +0000289/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000290void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000291 unsigned N = Decls.size();
John McCall9f54ad42009-12-10 09:41:52 +0000292
John McCallf36e02d2009-10-09 21:13:30 +0000293 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000294 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000295 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000296 return;
297 }
298
John McCall7453ed42009-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 McCall7ba107a2009-11-18 02:36:19 +0000301 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000302 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
303 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000304 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000305 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000306 ResultKind = FoundUnresolvedValue;
307 return;
308 }
John McCallf36e02d2009-10-09 21:13:30 +0000309
John McCall6e247262009-10-10 05:48:19 +0000310 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000311 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000312
John McCallf36e02d2009-10-09 21:13:30 +0000313 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
314
315 bool Ambiguous = false;
316 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000317 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000318
319 unsigned UniqueTagIndex = 0;
320
321 unsigned I = 0;
322 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000323 NamedDecl *D = Decls[I]->getUnderlyingDecl();
324 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000325
John McCall314be4e2009-11-17 07:50:12 +0000326 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000327 // If it's not unique, pull something off the back (and
328 // continue at this index).
329 Decls[I] = Decls[--N];
John McCallf36e02d2009-10-09 21:13:30 +0000330 } else {
331 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000332
333 if (isa<UnresolvedUsingValueDecl>(D)) {
334 HasUnresolved = true;
335 } else if (isa<TagDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000336 if (HasTag)
337 Ambiguous = true;
338 UniqueTagIndex = I;
339 HasTag = true;
John McCall7453ed42009-11-22 00:44:51 +0000340 } else if (isa<FunctionTemplateDecl>(D)) {
341 HasFunction = true;
342 HasFunctionTemplate = true;
343 } else if (isa<FunctionDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000344 HasFunction = true;
345 } else {
346 if (HasNonFunction)
347 Ambiguous = true;
348 HasNonFunction = true;
349 }
350 I++;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000351 }
Mike Stump1eb44332009-09-09 15:08:12 +0000352 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000353
John McCallf36e02d2009-10-09 21:13:30 +0000354 // C++ [basic.scope.hiding]p2:
355 // A class name or enumeration name can be hidden by the name of
356 // an object, function, or enumerator declared in the same
357 // scope. If a class or enumeration name and an object, function,
358 // or enumerator are declared in the same scope (in any order)
359 // with the same name, the class or enumeration name is hidden
360 // wherever the object, function, or enumerator name is visible.
361 // But it's still an error if there are distinct tag types found,
362 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000363 if (HideTags && HasTag && !Ambiguous &&
364 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000365 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000366
John McCallf36e02d2009-10-09 21:13:30 +0000367 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000368
John McCallfda8e122009-12-03 00:58:24 +0000369 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000370 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000371
John McCallf36e02d2009-10-09 21:13:30 +0000372 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000373 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000374 else if (HasUnresolved)
375 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000376 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000377 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000378 else
John McCalla24dc2e2009-11-17 02:14:36 +0000379 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000380}
381
John McCall7d384dd2009-11-18 07:57:50 +0000382void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000383 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000384 DeclContext::lookup_iterator DI, DE;
385 for (I = P.begin(), E = P.end(); I != E; ++I)
386 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
387 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000388}
389
John McCall7d384dd2009-11-18 07:57:50 +0000390void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000391 Paths = new CXXBasePaths;
392 Paths->swap(P);
393 addDeclsFromBasePaths(*Paths);
394 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000395 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000396}
397
John McCall7d384dd2009-11-18 07:57:50 +0000398void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000399 Paths = new CXXBasePaths;
400 Paths->swap(P);
401 addDeclsFromBasePaths(*Paths);
402 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000403 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000404}
405
John McCall7d384dd2009-11-18 07:57:50 +0000406void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000407 Out << Decls.size() << " result(s)";
408 if (isAmbiguous()) Out << ", ambiguous";
409 if (Paths) Out << ", base paths present";
410
411 for (iterator I = begin(), E = end(); I != E; ++I) {
412 Out << "\n";
413 (*I)->print(Out, 2);
414 }
415}
416
Douglas Gregor85910982010-02-12 05:48:04 +0000417/// \brief Lookup a builtin function, when name lookup would otherwise
418/// fail.
419static bool LookupBuiltin(Sema &S, LookupResult &R) {
420 Sema::LookupNameKind NameKind = R.getLookupKind();
421
422 // If we didn't find a use of this identifier, and if the identifier
423 // corresponds to a compiler builtin, create the decl object for the builtin
424 // now, injecting it into translation unit scope, and return it.
425 if (NameKind == Sema::LookupOrdinaryName ||
426 NameKind == Sema::LookupRedeclarationWithLinkage) {
427 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
428 if (II) {
429 // If this is a builtin on this (or all) targets, create the decl.
430 if (unsigned BuiltinID = II->getBuiltinID()) {
431 // In C++, we don't have any predefined library functions like
432 // 'malloc'. Instead, we'll just error.
433 if (S.getLangOptions().CPlusPlus &&
434 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
435 return false;
436
437 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
438 S.TUScope, R.isForRedeclaration(),
439 R.getNameLoc());
440 if (D)
441 R.addDecl(D);
442 return (D != NULL);
443 }
444 }
445 }
446
447 return false;
448}
449
Douglas Gregor4923aa22010-07-02 20:37:36 +0000450/// \brief Determine whether we can declare a special member function within
451/// the class at this point.
452static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
453 const CXXRecordDecl *Class) {
454 // We need to have a definition for the class.
455 if (!Class->getDefinition() || Class->isDependentContext())
456 return false;
457
458 // We can't be in the middle of defining the class.
459 if (const RecordType *RecordTy
460 = Context.getTypeDeclType(Class)->getAs<RecordType>())
461 return !RecordTy->isBeingDefined();
462
463 return false;
464}
465
466void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000467 if (!CanDeclareSpecialMemberFunction(Context, Class))
468 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000469
470 // If the default constructor has not yet been declared, do so now.
471 if (!Class->hasDeclaredDefaultConstructor())
472 DeclareImplicitDefaultConstructor(Class);
Douglas Gregor22584312010-07-02 23:41:54 +0000473
474 // If the copy constructor has not yet been declared, do so now.
475 if (!Class->hasDeclaredCopyConstructor())
476 DeclareImplicitCopyConstructor(Class);
477
Douglas Gregora376d102010-07-02 21:50:04 +0000478 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000479 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000480 DeclareImplicitCopyAssignment(Class);
481
Douglas Gregor4923aa22010-07-02 20:37:36 +0000482 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000483 if (!Class->hasDeclaredDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +0000484 DeclareImplicitDestructor(Class);
485}
486
Douglas Gregora376d102010-07-02 21:50:04 +0000487/// \brief Determine whether this is the name of an implicitly-declared
488/// special member function.
489static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
490 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000491 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000492 case DeclarationName::CXXDestructorName:
493 return true;
494
495 case DeclarationName::CXXOperatorName:
496 return Name.getCXXOverloadedOperator() == OO_Equal;
497
498 default:
499 break;
500 }
501
502 return false;
503}
504
505/// \brief If there are any implicit member functions with the given name
506/// that need to be declared in the given declaration context, do so.
507static void DeclareImplicitMemberFunctionsWithName(Sema &S,
508 DeclarationName Name,
509 const DeclContext *DC) {
510 if (!DC)
511 return;
512
513 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000514 case DeclarationName::CXXConstructorName:
515 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000516 if (Record->getDefinition() &&
517 CanDeclareSpecialMemberFunction(S.Context, Record)) {
518 if (!Record->hasDeclaredDefaultConstructor())
519 S.DeclareImplicitDefaultConstructor(
520 const_cast<CXXRecordDecl *>(Record));
521 if (!Record->hasDeclaredCopyConstructor())
522 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
523 }
Douglas Gregor22584312010-07-02 23:41:54 +0000524 break;
525
Douglas Gregora376d102010-07-02 21:50:04 +0000526 case DeclarationName::CXXDestructorName:
527 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
528 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
529 CanDeclareSpecialMemberFunction(S.Context, Record))
530 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000531 break;
532
533 case DeclarationName::CXXOperatorName:
534 if (Name.getCXXOverloadedOperator() != OO_Equal)
535 break;
536
537 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
538 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
539 CanDeclareSpecialMemberFunction(S.Context, Record))
540 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
541 break;
542
543 default:
544 break;
545 }
546}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000547
John McCallf36e02d2009-10-09 21:13:30 +0000548// Adds all qualifying matches for a name within a decl context to the
549// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000550static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000551 bool Found = false;
552
Douglas Gregor4923aa22010-07-02 20:37:36 +0000553 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000554 if (S.getLangOptions().CPlusPlus)
555 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000556
557 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000558 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000559 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000560 NamedDecl *D = *I;
561 if (R.isAcceptableDecl(D)) {
562 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000563 Found = true;
564 }
565 }
John McCallf36e02d2009-10-09 21:13:30 +0000566
Douglas Gregor85910982010-02-12 05:48:04 +0000567 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
568 return true;
569
Douglas Gregor48026d22010-01-11 18:40:55 +0000570 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000571 != DeclarationName::CXXConversionFunctionName ||
572 R.getLookupName().getCXXNameType()->isDependentType() ||
573 !isa<CXXRecordDecl>(DC))
574 return Found;
575
576 // C++ [temp.mem]p6:
577 // A specialization of a conversion function template is not found by
578 // name lookup. Instead, any conversion function templates visible in the
579 // context of the use are considered. [...]
580 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
581 if (!Record->isDefinition())
582 return Found;
583
584 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
585 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
586 UEnd = Unresolved->end(); U != UEnd; ++U) {
587 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
588 if (!ConvTemplate)
589 continue;
590
591 // When we're performing lookup for the purposes of redeclaration, just
592 // add the conversion function template. When we deduce template
593 // arguments for specializations, we'll end up unifying the return
594 // type of the new declaration with the type of the function template.
595 if (R.isForRedeclaration()) {
596 R.addDecl(ConvTemplate);
597 Found = true;
598 continue;
599 }
600
Douglas Gregor48026d22010-01-11 18:40:55 +0000601 // C++ [temp.mem]p6:
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000602 // [...] For each such operator, if argument deduction succeeds
603 // (14.9.2.3), the resulting specialization is used as if found by
604 // name lookup.
605 //
606 // When referencing a conversion function for any purpose other than
607 // a redeclaration (such that we'll be building an expression with the
608 // result), perform template argument deduction and place the
609 // specialization into the result set. We do this to avoid forcing all
610 // callers to perform special deduction for conversion functions.
John McCall5769d612010-02-08 23:07:23 +0000611 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000612 FunctionDecl *Specialization = 0;
613
614 const FunctionProtoType *ConvProto
615 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
616 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000617
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000618 // Compute the type of the function that we would expect the conversion
619 // function to have, if it were to match the name given.
620 // FIXME: Calling convention!
Rafael Espindola264ba482010-03-30 20:24:48 +0000621 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000622 QualType ExpectedType
623 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
624 0, 0, ConvProto->isVariadic(),
625 ConvProto->getTypeQuals(),
626 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000627 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000628
629 // Perform template argument deduction against the type that we would
630 // expect the function to have.
631 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
632 Specialization, Info)
633 == Sema::TDK_Success) {
634 R.addDecl(Specialization);
635 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000636 }
637 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000638
John McCallf36e02d2009-10-09 21:13:30 +0000639 return Found;
640}
641
John McCalld7be78a2009-11-10 07:01:13 +0000642// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000643static bool
Douglas Gregor85910982010-02-12 05:48:04 +0000644CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
645 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000646
647 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
648
John McCalld7be78a2009-11-10 07:01:13 +0000649 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000650 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000651
John McCalld7be78a2009-11-10 07:01:13 +0000652 // Perform direct name lookup into the namespaces nominated by the
653 // using directives whose common ancestor is this namespace.
654 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
655 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000656
John McCalld7be78a2009-11-10 07:01:13 +0000657 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000658 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000659 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000660
661 R.resolveKind();
662
663 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000664}
665
666static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000667 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000668 return Ctx->isFileContext();
669 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000670}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000671
Douglas Gregor711be1e2010-03-15 14:33:29 +0000672// Find the next outer declaration context from this scope. This
673// routine actually returns the semantic outer context, which may
674// differ from the lexical context (encoded directly in the Scope
675// stack) when we are parsing a member of a class template. In this
676// case, the second element of the pair will be true, to indicate that
677// name lookup should continue searching in this semantic context when
678// it leaves the current template parameter scope.
679static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
680 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
681 DeclContext *Lexical = 0;
682 for (Scope *OuterS = S->getParent(); OuterS;
683 OuterS = OuterS->getParent()) {
684 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000685 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000686 break;
687 }
688 }
689
690 // C++ [temp.local]p8:
691 // In the definition of a member of a class template that appears
692 // outside of the namespace containing the class template
693 // definition, the name of a template-parameter hides the name of
694 // a member of this namespace.
695 //
696 // Example:
697 //
698 // namespace N {
699 // class C { };
700 //
701 // template<class T> class B {
702 // void f(T);
703 // };
704 // }
705 //
706 // template<class C> void N::B<C>::f(C) {
707 // C b; // C is the template parameter, not N::C
708 // }
709 //
710 // In this example, the lexical context we return is the
711 // TranslationUnit, while the semantic context is the namespace N.
712 if (!Lexical || !DC || !S->getParent() ||
713 !S->getParent()->isTemplateParamScope())
714 return std::make_pair(Lexical, false);
715
716 // Find the outermost template parameter scope.
717 // For the example, this is the scope for the template parameters of
718 // template<class C>.
719 Scope *OutermostTemplateScope = S->getParent();
720 while (OutermostTemplateScope->getParent() &&
721 OutermostTemplateScope->getParent()->isTemplateParamScope())
722 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregore942bbe2009-09-10 16:57:35 +0000723
Douglas Gregor711be1e2010-03-15 14:33:29 +0000724 // Find the namespace context in which the original scope occurs. In
725 // the example, this is namespace N.
726 DeclContext *Semantic = DC;
727 while (!Semantic->isFileContext())
728 Semantic = Semantic->getParent();
729
730 // Find the declaration context just outside of the template
731 // parameter scope. This is the context in which the template is
732 // being lexically declaration (a namespace context). In the
733 // example, this is the global scope.
734 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
735 Lexical->Encloses(Semantic))
736 return std::make_pair(Semantic, true);
737
738 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000739}
740
John McCalla24dc2e2009-11-17 02:14:36 +0000741bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000742 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000743
744 DeclarationName Name = R.getLookupName();
745
Douglas Gregora376d102010-07-02 21:50:04 +0000746 // If this is the name of an implicitly-declared special member function,
747 // go through the scope stack to implicitly declare
748 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
749 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
750 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
751 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
752 }
753
754 // Implicitly declare member functions with the name we're looking for, if in
755 // fact we are in a scope where it matters.
756
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000757 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000758 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000759 I = IdResolver.begin(Name),
760 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000761
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000762 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000763 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000764 // ...During unqualified name lookup (3.4.1), the names appear as if
765 // they were declared in the nearest enclosing namespace which contains
766 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000767 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000768 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000769 //
770 // For example:
771 // namespace A { int i; }
772 // void foo() {
773 // int i;
774 // {
775 // using namespace A;
776 // ++i; // finds local 'i', A::i appears at global scope
777 // }
778 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000779 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000780 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000781 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000782 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
783
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000784 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000785 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000786 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000787 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000788 Found = true;
789 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000790 }
791 }
John McCallf36e02d2009-10-09 21:13:30 +0000792 if (Found) {
793 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000794 if (S->isClassScope())
795 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
796 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000797 return true;
798 }
799
Douglas Gregor711be1e2010-03-15 14:33:29 +0000800 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
801 S->getParent() && !S->getParent()->isTemplateParamScope()) {
802 // We've just searched the last template parameter scope and
803 // found nothing, so look into the the contexts between the
804 // lexical and semantic declaration contexts returned by
805 // findOuterContext(). This implements the name lookup behavior
806 // of C++ [temp.local]p8.
807 Ctx = OutsideOfTemplateParamDC;
808 OutsideOfTemplateParamDC = 0;
809 }
810
811 if (Ctx) {
812 DeclContext *OuterCtx;
813 bool SearchAfterTemplateScope;
814 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
815 if (SearchAfterTemplateScope)
816 OutsideOfTemplateParamDC = OuterCtx;
817
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000818 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000819 // We do not directly look into transparent contexts, since
820 // those entities will be found in the nearest enclosing
821 // non-transparent context.
822 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000823 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000824
825 // We do not look directly into function or method contexts,
826 // since all of the local variables and parameters of the
827 // function/method are present within the Scope.
828 if (Ctx->isFunctionOrMethod()) {
829 // If we have an Objective-C instance method, look for ivars
830 // in the corresponding interface.
831 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
832 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
833 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
834 ObjCInterfaceDecl *ClassDeclared;
835 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
836 Name.getAsIdentifierInfo(),
837 ClassDeclared)) {
838 if (R.isAcceptableDecl(Ivar)) {
839 R.addDecl(Ivar);
840 R.resolveKind();
841 return true;
842 }
843 }
844 }
845 }
846
847 continue;
848 }
849
Douglas Gregore942bbe2009-09-10 16:57:35 +0000850 // Perform qualified name lookup into this context.
851 // FIXME: In some cases, we know that every name that could be found by
852 // this qualified name lookup will also be on the identifier chain. For
853 // example, inside a class without any base classes, we never need to
854 // perform qualified lookup because all of the members are on top of the
855 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000856 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000857 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000858 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000859 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000860 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000861
John McCalld7be78a2009-11-10 07:01:13 +0000862 // Stop if we ran out of scopes.
863 // FIXME: This really, really shouldn't be happening.
864 if (!S) return false;
865
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000866 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000867 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000868 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000869 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
870 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000871
John McCalld7be78a2009-11-10 07:01:13 +0000872 UnqualUsingDirectiveSet UDirs;
873 UDirs.visitScopeChain(Initial, S);
874 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000875
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000876 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000877 // Unqualified name lookup in C++ requires looking into scopes
878 // that aren't strictly lexical, and therefore we walk through the
879 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000880
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000881 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000882 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000883 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000884 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000885 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000886 // We found something. Look for anything else in our scope
887 // with this same name and in an acceptable identifier
888 // namespace, so that we can construct an overload set if we
889 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000890 Found = true;
891 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000892 }
893 }
894
Douglas Gregor00b4b032010-05-14 04:53:42 +0000895 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000896 R.resolveKind();
897 return true;
898 }
899
Douglas Gregor00b4b032010-05-14 04:53:42 +0000900 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
901 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
902 S->getParent() && !S->getParent()->isTemplateParamScope()) {
903 // We've just searched the last template parameter scope and
904 // found nothing, so look into the the contexts between the
905 // lexical and semantic declaration contexts returned by
906 // findOuterContext(). This implements the name lookup behavior
907 // of C++ [temp.local]p8.
908 Ctx = OutsideOfTemplateParamDC;
909 OutsideOfTemplateParamDC = 0;
910 }
911
912 if (Ctx) {
913 DeclContext *OuterCtx;
914 bool SearchAfterTemplateScope;
915 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
916 if (SearchAfterTemplateScope)
917 OutsideOfTemplateParamDC = OuterCtx;
918
919 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
920 // We do not directly look into transparent contexts, since
921 // those entities will be found in the nearest enclosing
922 // non-transparent context.
923 if (Ctx->isTransparentContext())
924 continue;
925
926 // If we have a context, and it's not a context stashed in the
927 // template parameter scope for an out-of-line definition, also
928 // look into that context.
929 if (!(Found && S && S->isTemplateParamScope())) {
930 assert(Ctx->isFileContext() &&
931 "We should have been looking only at file context here already.");
932
933 // Look into context considering using-directives.
934 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
935 Found = true;
936 }
937
938 if (Found) {
939 R.resolveKind();
940 return true;
941 }
942
943 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
944 return false;
945 }
946 }
947
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000948 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000949 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000950 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000951
John McCallf36e02d2009-10-09 21:13:30 +0000952 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000953}
954
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000955/// @brief Perform unqualified name lookup starting from a given
956/// scope.
957///
958/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
959/// used to find names within the current scope. For example, 'x' in
960/// @code
961/// int x;
962/// int f() {
963/// return x; // unqualified name look finds 'x' in the global scope
964/// }
965/// @endcode
966///
967/// Different lookup criteria can find different names. For example, a
968/// particular scope can have both a struct and a function of the same
969/// name, and each can be found by certain lookup criteria. For more
970/// information about lookup criteria, see the documentation for the
971/// class LookupCriteria.
972///
973/// @param S The scope from which unqualified name lookup will
974/// begin. If the lookup criteria permits, name lookup may also search
975/// in the parent scopes.
976///
977/// @param Name The name of the entity that we are searching for.
978///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000979/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +0000980/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +0000981/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000982///
983/// @returns The result of name lookup, which includes zero or more
984/// declarations and possibly additional information used to diagnose
985/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000986bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
987 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +0000988 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000989
John McCalla24dc2e2009-11-17 02:14:36 +0000990 LookupNameKind NameKind = R.getLookupKind();
991
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000992 if (!getLangOptions().CPlusPlus) {
993 // Unqualified name lookup in C/Objective-C is purely lexical, so
994 // search in the declarations attached to the name.
995
John McCall1d7c5282009-12-18 10:40:03 +0000996 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000997 // Find the nearest non-transparent declaration scope.
998 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000999 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001000 static_cast<DeclContext *>(S->getEntity())
1001 ->isTransparentContext()))
1002 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001003 }
1004
John McCall1d7c5282009-12-18 10:40:03 +00001005 unsigned IDNS = R.getIdentifierNamespace();
1006
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001007 // Scan up the scope chain looking for a decl that matches this
1008 // identifier that is in the appropriate namespace. This search
1009 // should not take long, as shadowing of names is uncommon, and
1010 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001011 bool LeftStartingScope = false;
1012
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001013 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001014 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001015 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001016 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001017 if (NameKind == LookupRedeclarationWithLinkage) {
1018 // Determine whether this (or a previous) declaration is
1019 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001020 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001021 LeftStartingScope = true;
1022
1023 // If we found something outside of our starting scope that
1024 // does not have linkage, skip it.
1025 if (LeftStartingScope && !((*I)->hasLinkage()))
1026 continue;
1027 }
1028
John McCallf36e02d2009-10-09 21:13:30 +00001029 R.addDecl(*I);
1030
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001031 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001032 // If this declaration has the "overloadable" attribute, we
1033 // might have a set of overloaded functions.
1034
1035 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001036 while (!(S->getFlags() & Scope::DeclScope) ||
1037 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001038 S = S->getParent();
1039
1040 // Find the last declaration in this scope (with the same
1041 // name, naturally).
1042 IdentifierResolver::iterator LastI = I;
1043 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00001044 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001045 break;
John McCallf36e02d2009-10-09 21:13:30 +00001046 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001047 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001048 }
1049
John McCallf36e02d2009-10-09 21:13:30 +00001050 R.resolveKind();
1051
1052 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001053 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001054 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001055 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001056 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001057 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001058 }
1059
1060 // If we didn't find a use of this identifier, and if the identifier
1061 // corresponds to a compiler builtin, create the decl object for the builtin
1062 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +00001063 if (AllowBuiltinCreation)
1064 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001065
John McCallf36e02d2009-10-09 21:13:30 +00001066 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001067}
1068
John McCall6e247262009-10-10 05:48:19 +00001069/// @brief Perform qualified name lookup in the namespaces nominated by
1070/// using directives by the given context.
1071///
1072/// C++98 [namespace.qual]p2:
1073/// Given X::m (where X is a user-declared namespace), or given ::m
1074/// (where X is the global namespace), let S be the set of all
1075/// declarations of m in X and in the transitive closure of all
1076/// namespaces nominated by using-directives in X and its used
1077/// namespaces, except that using-directives are ignored in any
1078/// namespace, including X, directly containing one or more
1079/// declarations of m. No namespace is searched more than once in
1080/// the lookup of a name. If S is the empty set, the program is
1081/// ill-formed. Otherwise, if S has exactly one member, or if the
1082/// context of the reference is a using-declaration
1083/// (namespace.udecl), S is the required set of declarations of
1084/// m. Otherwise if the use of m is not one that allows a unique
1085/// declaration to be chosen from S, the program is ill-formed.
1086/// C++98 [namespace.qual]p5:
1087/// During the lookup of a qualified namespace member name, if the
1088/// lookup finds more than one declaration of the member, and if one
1089/// declaration introduces a class name or enumeration name and the
1090/// other declarations either introduce the same object, the same
1091/// enumerator or a set of functions, the non-type name hides the
1092/// class or enumeration name if and only if the declarations are
1093/// from the same namespace; otherwise (the declarations are from
1094/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001095static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001096 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001097 assert(StartDC->isFileContext() && "start context is not a file context");
1098
1099 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1100 DeclContext::udir_iterator E = StartDC->using_directives_end();
1101
1102 if (I == E) return false;
1103
1104 // We have at least added all these contexts to the queue.
1105 llvm::DenseSet<DeclContext*> Visited;
1106 Visited.insert(StartDC);
1107
1108 // We have not yet looked into these namespaces, much less added
1109 // their "using-children" to the queue.
1110 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1111
1112 // We have already looked into the initial namespace; seed the queue
1113 // with its using-children.
1114 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001115 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001116 if (Visited.insert(ND).second)
1117 Queue.push_back(ND);
1118 }
1119
1120 // The easiest way to implement the restriction in [namespace.qual]p5
1121 // is to check whether any of the individual results found a tag
1122 // and, if so, to declare an ambiguity if the final result is not
1123 // a tag.
1124 bool FoundTag = false;
1125 bool FoundNonTag = false;
1126
John McCall7d384dd2009-11-18 07:57:50 +00001127 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001128
1129 bool Found = false;
1130 while (!Queue.empty()) {
1131 NamespaceDecl *ND = Queue.back();
1132 Queue.pop_back();
1133
1134 // We go through some convolutions here to avoid copying results
1135 // between LookupResults.
1136 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001137 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001138 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001139
1140 if (FoundDirect) {
1141 // First do any local hiding.
1142 DirectR.resolveKind();
1143
1144 // If the local result is a tag, remember that.
1145 if (DirectR.isSingleTagDecl())
1146 FoundTag = true;
1147 else
1148 FoundNonTag = true;
1149
1150 // Append the local results to the total results if necessary.
1151 if (UseLocal) {
1152 R.addAllDecls(LocalR);
1153 LocalR.clear();
1154 }
1155 }
1156
1157 // If we find names in this namespace, ignore its using directives.
1158 if (FoundDirect) {
1159 Found = true;
1160 continue;
1161 }
1162
1163 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1164 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1165 if (Visited.insert(Nom).second)
1166 Queue.push_back(Nom);
1167 }
1168 }
1169
1170 if (Found) {
1171 if (FoundTag && FoundNonTag)
1172 R.setAmbiguousQualifiedTagHiding();
1173 else
1174 R.resolveKind();
1175 }
1176
1177 return Found;
1178}
1179
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001180/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001181///
1182/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1183/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001184/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001185///
1186/// Different lookup criteria can find different names. For example, a
1187/// particular scope can have both a struct and a function of the same
1188/// name, and each can be found by certain lookup criteria. For more
1189/// information about lookup criteria, see the documentation for the
1190/// class LookupCriteria.
1191///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001192/// \param R captures both the lookup criteria and any lookup results found.
1193///
1194/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001195/// search. If the lookup criteria permits, name lookup may also search
1196/// in the parent contexts or (for C++ classes) base classes.
1197///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001198/// \param InUnqualifiedLookup true if this is qualified name lookup that
1199/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001200///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001201/// \returns true if lookup succeeded, false if it failed.
1202bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1203 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001204 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001205
John McCalla24dc2e2009-11-17 02:14:36 +00001206 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001207 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001209 // Make sure that the declaration context is complete.
1210 assert((!isa<TagDecl>(LookupCtx) ||
1211 LookupCtx->isDependentContext() ||
1212 cast<TagDecl>(LookupCtx)->isDefinition() ||
1213 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1214 ->isBeingDefined()) &&
1215 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001217 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001218 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001219 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001220 if (isa<CXXRecordDecl>(LookupCtx))
1221 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001222 return true;
1223 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001224
John McCall6e247262009-10-10 05:48:19 +00001225 // Don't descend into implied contexts for redeclarations.
1226 // C++98 [namespace.qual]p6:
1227 // In a declaration for a namespace member in which the
1228 // declarator-id is a qualified-id, given that the qualified-id
1229 // for the namespace member has the form
1230 // nested-name-specifier unqualified-id
1231 // the unqualified-id shall name a member of the namespace
1232 // designated by the nested-name-specifier.
1233 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001234 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001235 return false;
1236
John McCalla24dc2e2009-11-17 02:14:36 +00001237 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001238 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001239 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001240
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001241 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001242 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001243 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001244 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001245 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001246
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001247 // If we're performing qualified name lookup into a dependent class,
1248 // then we are actually looking into a current instantiation. If we have any
1249 // dependent base classes, then we either have to delay lookup until
1250 // template instantiation time (at which point all bases will be available)
1251 // or we have to fail.
1252 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1253 LookupRec->hasAnyDependentBases()) {
1254 R.setNotFoundInCurrentInstantiation();
1255 return false;
1256 }
1257
Douglas Gregor7176fff2009-01-15 00:26:24 +00001258 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001259 CXXBasePaths Paths;
1260 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001261
1262 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001263 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001264 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001265 case LookupOrdinaryName:
1266 case LookupMemberName:
1267 case LookupRedeclarationWithLinkage:
1268 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1269 break;
1270
1271 case LookupTagName:
1272 BaseCallback = &CXXRecordDecl::FindTagMember;
1273 break;
John McCall9f54ad42009-12-10 09:41:52 +00001274
1275 case LookupUsingDeclName:
1276 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001277
1278 case LookupOperatorName:
1279 case LookupNamespaceName:
1280 case LookupObjCProtocolName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001281 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001282 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001283
1284 case LookupNestedNameSpecifierName:
1285 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1286 break;
1287 }
1288
John McCalla24dc2e2009-11-17 02:14:36 +00001289 if (!LookupRec->lookupInBases(BaseCallback,
1290 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001291 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001292
John McCall92f88312010-01-23 00:46:32 +00001293 R.setNamingClass(LookupRec);
1294
Douglas Gregor7176fff2009-01-15 00:26:24 +00001295 // C++ [class.member.lookup]p2:
1296 // [...] If the resulting set of declarations are not all from
1297 // sub-objects of the same type, or the set has a nonstatic member
1298 // and includes members from distinct sub-objects, there is an
1299 // ambiguity and the program is ill-formed. Otherwise that set is
1300 // the result of the lookup.
1301 // FIXME: support using declarations!
1302 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001303 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001304 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001305 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001306 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001307 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001308
John McCall46460a62010-01-20 21:53:11 +00001309 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1310 // across all paths.
1311 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1312
Douglas Gregor7176fff2009-01-15 00:26:24 +00001313 // Determine whether we're looking at a distinct sub-object or not.
1314 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001315 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001316 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1317 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00001318 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001319 != Context.getCanonicalType(PathElement.Base->getType())) {
1320 // We found members of the given name in two subobjects of
1321 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001322 R.setAmbiguousBaseSubobjectTypes(Paths);
1323 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001324 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1325 // We have a different subobject of the same type.
1326
1327 // C++ [class.member.lookup]p5:
1328 // A static member, a nested type or an enumerator defined in
1329 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001330 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001331 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001332 if (isa<VarDecl>(FirstDecl) ||
1333 isa<TypeDecl>(FirstDecl) ||
1334 isa<EnumConstantDecl>(FirstDecl))
1335 continue;
1336
1337 if (isa<CXXMethodDecl>(FirstDecl)) {
1338 // Determine whether all of the methods are static.
1339 bool AllMethodsAreStatic = true;
1340 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1341 Func != Path->Decls.second; ++Func) {
1342 if (!isa<CXXMethodDecl>(*Func)) {
1343 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1344 break;
1345 }
1346
1347 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1348 AllMethodsAreStatic = false;
1349 break;
1350 }
1351 }
1352
1353 if (AllMethodsAreStatic)
1354 continue;
1355 }
1356
1357 // We have found a nonstatic member name in multiple, distinct
1358 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001359 R.setAmbiguousBaseSubobjects(Paths);
1360 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001361 }
1362 }
1363
1364 // Lookup in a base class succeeded; return these results.
1365
John McCallf36e02d2009-10-09 21:13:30 +00001366 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001367 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1368 NamedDecl *D = *I;
1369 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1370 D->getAccess());
1371 R.addDecl(D, AS);
1372 }
John McCallf36e02d2009-10-09 21:13:30 +00001373 R.resolveKind();
1374 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001375}
1376
1377/// @brief Performs name lookup for a name that was parsed in the
1378/// source code, and may contain a C++ scope specifier.
1379///
1380/// This routine is a convenience routine meant to be called from
1381/// contexts that receive a name and an optional C++ scope specifier
1382/// (e.g., "N::M::x"). It will then perform either qualified or
1383/// unqualified name lookup (with LookupQualifiedName or LookupName,
1384/// respectively) on the given name and return those results.
1385///
1386/// @param S The scope from which unqualified name lookup will
1387/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001388///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001389/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001390///
1391/// @param Name The name of the entity that name lookup will
1392/// search for.
1393///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001394/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001395/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001396/// C library functions (like "malloc") are implicitly declared.
1397///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001398/// @param EnteringContext Indicates whether we are going to enter the
1399/// context of the scope-specifier SS (if present).
1400///
John McCallf36e02d2009-10-09 21:13:30 +00001401/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001402bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001403 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001404 if (SS && SS->isInvalid()) {
1405 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001406 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001407 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001408 }
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Douglas Gregor495c35d2009-08-25 22:51:20 +00001410 if (SS && SS->isSet()) {
1411 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001412 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001413 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001414 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001415 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001416
John McCalla24dc2e2009-11-17 02:14:36 +00001417 R.setContextRange(SS->getRange());
1418
1419 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001420 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001421
Douglas Gregor495c35d2009-08-25 22:51:20 +00001422 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001423 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001424 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001425 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001426 }
1427
Mike Stump1eb44332009-09-09 15:08:12 +00001428 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001429 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001430}
1431
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001432
Douglas Gregor7176fff2009-01-15 00:26:24 +00001433/// @brief Produce a diagnostic describing the ambiguity that resulted
1434/// from name lookup.
1435///
1436/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001437///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001438/// @param Name The name of the entity that name lookup was
1439/// searching for.
1440///
1441/// @param NameLoc The location of the name within the source code.
1442///
1443/// @param LookupRange A source range that provides more
1444/// source-location information concerning the lookup itself. For
1445/// example, this range might highlight a nested-name-specifier that
1446/// precedes the name.
1447///
1448/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001449bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001450 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1451
John McCalla24dc2e2009-11-17 02:14:36 +00001452 DeclarationName Name = Result.getLookupName();
1453 SourceLocation NameLoc = Result.getNameLoc();
1454 SourceRange LookupRange = Result.getContextRange();
1455
John McCall6e247262009-10-10 05:48:19 +00001456 switch (Result.getAmbiguityKind()) {
1457 case LookupResult::AmbiguousBaseSubobjects: {
1458 CXXBasePaths *Paths = Result.getBasePaths();
1459 QualType SubobjectType = Paths->front().back().Base->getType();
1460 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1461 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1462 << LookupRange;
1463
1464 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1465 while (isa<CXXMethodDecl>(*Found) &&
1466 cast<CXXMethodDecl>(*Found)->isStatic())
1467 ++Found;
1468
1469 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1470
1471 return true;
1472 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001473
John McCall6e247262009-10-10 05:48:19 +00001474 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001475 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1476 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001477
1478 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001479 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001480 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1481 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001482 Path != PathEnd; ++Path) {
1483 Decl *D = *Path->Decls.first;
1484 if (DeclsPrinted.insert(D).second)
1485 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1486 }
1487
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001488 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001489 }
1490
John McCall6e247262009-10-10 05:48:19 +00001491 case LookupResult::AmbiguousTagHiding: {
1492 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001493
John McCall6e247262009-10-10 05:48:19 +00001494 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1495
1496 LookupResult::iterator DI, DE = Result.end();
1497 for (DI = Result.begin(); DI != DE; ++DI)
1498 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1499 TagDecls.insert(TD);
1500 Diag(TD->getLocation(), diag::note_hidden_tag);
1501 }
1502
1503 for (DI = Result.begin(); DI != DE; ++DI)
1504 if (!isa<TagDecl>(*DI))
1505 Diag((*DI)->getLocation(), diag::note_hiding_object);
1506
1507 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001508 LookupResult::Filter F = Result.makeFilter();
1509 while (F.hasNext()) {
1510 if (TagDecls.count(F.next()))
1511 F.erase();
1512 }
1513 F.done();
John McCall6e247262009-10-10 05:48:19 +00001514
1515 return true;
1516 }
1517
1518 case LookupResult::AmbiguousReference: {
1519 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001520
John McCall6e247262009-10-10 05:48:19 +00001521 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1522 for (; DI != DE; ++DI)
1523 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001524
John McCall6e247262009-10-10 05:48:19 +00001525 return true;
1526 }
1527 }
1528
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001529 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001530 return true;
1531}
Douglas Gregorfa047642009-02-04 00:32:51 +00001532
John McCallc7e04da2010-05-28 18:45:08 +00001533namespace {
1534 struct AssociatedLookup {
1535 AssociatedLookup(Sema &S,
1536 Sema::AssociatedNamespaceSet &Namespaces,
1537 Sema::AssociatedClassSet &Classes)
1538 : S(S), Namespaces(Namespaces), Classes(Classes) {
1539 }
1540
1541 Sema &S;
1542 Sema::AssociatedNamespaceSet &Namespaces;
1543 Sema::AssociatedClassSet &Classes;
1544 };
1545}
1546
Mike Stump1eb44332009-09-09 15:08:12 +00001547static void
John McCallc7e04da2010-05-28 18:45:08 +00001548addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001549
Douglas Gregor54022952010-04-30 07:08:38 +00001550static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1551 DeclContext *Ctx) {
1552 // Add the associated namespace for this class.
1553
1554 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1555 // be a locally scoped record.
1556
1557 while (Ctx->isRecord() || Ctx->isTransparentContext())
1558 Ctx = Ctx->getParent();
1559
John McCall6ff07852009-08-07 22:18:02 +00001560 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001561 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001562}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001563
Mike Stump1eb44332009-09-09 15:08:12 +00001564// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001565// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001566static void
John McCallc7e04da2010-05-28 18:45:08 +00001567addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1568 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001569 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001570 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001571 switch (Arg.getKind()) {
1572 case TemplateArgument::Null:
1573 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Douglas Gregor69be8d62009-07-08 07:51:57 +00001575 case TemplateArgument::Type:
1576 // [...] the namespaces and classes associated with the types of the
1577 // template arguments provided for template type parameters (excluding
1578 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001579 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001580 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Douglas Gregor788cd062009-11-11 01:00:40 +00001582 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001583 // [...] the namespaces in which any template template arguments are
1584 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001585 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001586 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001587 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001588 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001589 DeclContext *Ctx = ClassTemplate->getDeclContext();
1590 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001591 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001592 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001593 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001594 }
1595 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001596 }
1597
1598 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001599 case TemplateArgument::Integral:
1600 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001601 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001602 // associated namespaces. ]
1603 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Douglas Gregor69be8d62009-07-08 07:51:57 +00001605 case TemplateArgument::Pack:
1606 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1607 PEnd = Arg.pack_end();
1608 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001609 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001610 break;
1611 }
1612}
1613
Douglas Gregorfa047642009-02-04 00:32:51 +00001614// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001615// argument-dependent lookup with an argument of class type
1616// (C++ [basic.lookup.koenig]p2).
1617static void
John McCallc7e04da2010-05-28 18:45:08 +00001618addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1619 CXXRecordDecl *Class) {
1620
1621 // Just silently ignore anything whose name is __va_list_tag.
1622 if (Class->getDeclName() == Result.S.VAListTagName)
1623 return;
1624
Douglas Gregorfa047642009-02-04 00:32:51 +00001625 // C++ [basic.lookup.koenig]p2:
1626 // [...]
1627 // -- If T is a class type (including unions), its associated
1628 // classes are: the class itself; the class of which it is a
1629 // member, if any; and its direct and indirect base
1630 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001631 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001632
1633 // Add the class of which it is a member, if any.
1634 DeclContext *Ctx = Class->getDeclContext();
1635 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001636 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001637 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001638 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Douglas Gregorfa047642009-02-04 00:32:51 +00001640 // Add the class itself. If we've already seen this class, we don't
1641 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001642 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001643 return;
1644
Mike Stump1eb44332009-09-09 15:08:12 +00001645 // -- If T is a template-id, its associated namespaces and classes are
1646 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001647 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001648 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001649 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001650 // namespaces in which any template template arguments are defined; and
1651 // the classes in which any member templates used as template template
1652 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001653 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001654 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001655 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1656 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1657 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001658 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001659 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001660 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Douglas Gregor69be8d62009-07-08 07:51:57 +00001662 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1663 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001664 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001665 }
Mike Stump1eb44332009-09-09 15:08:12 +00001666
John McCall86ff3082010-02-04 22:26:26 +00001667 // Only recurse into base classes for complete types.
1668 if (!Class->hasDefinition()) {
1669 // FIXME: we might need to instantiate templates here
1670 return;
1671 }
1672
Douglas Gregorfa047642009-02-04 00:32:51 +00001673 // Add direct and indirect base classes along with their associated
1674 // namespaces.
1675 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1676 Bases.push_back(Class);
1677 while (!Bases.empty()) {
1678 // Pop this class off the stack.
1679 Class = Bases.back();
1680 Bases.pop_back();
1681
1682 // Visit the base classes.
1683 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1684 BaseEnd = Class->bases_end();
1685 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001686 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001687 // In dependent contexts, we do ADL twice, and the first time around,
1688 // the base type might be a dependent TemplateSpecializationType, or a
1689 // TemplateTypeParmType. If that happens, simply ignore it.
1690 // FIXME: If we want to support export, we probably need to add the
1691 // namespace of the template in a TemplateSpecializationType, or even
1692 // the classes and namespaces of known non-dependent arguments.
1693 if (!BaseType)
1694 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001695 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001696 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001697 // Find the associated namespace for this base class.
1698 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001699 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001700
1701 // Make sure we visit the bases of this base class.
1702 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1703 Bases.push_back(BaseDecl);
1704 }
1705 }
1706 }
1707}
1708
1709// \brief Add the associated classes and namespaces for
1710// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001711// (C++ [basic.lookup.koenig]p2).
1712static void
John McCallc7e04da2010-05-28 18:45:08 +00001713addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001714 // C++ [basic.lookup.koenig]p2:
1715 //
1716 // For each argument type T in the function call, there is a set
1717 // of zero or more associated namespaces and a set of zero or more
1718 // associated classes to be considered. The sets of namespaces and
1719 // classes is determined entirely by the types of the function
1720 // arguments (and the namespace of any template template
1721 // argument). Typedef names and using-declarations used to specify
1722 // the types do not contribute to this set. The sets of namespaces
1723 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001724
John McCallfa4edcf2010-05-28 06:08:54 +00001725 llvm::SmallVector<const Type *, 16> Queue;
1726 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1727
Douglas Gregorfa047642009-02-04 00:32:51 +00001728 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001729 switch (T->getTypeClass()) {
1730
1731#define TYPE(Class, Base)
1732#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1733#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1734#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1735#define ABSTRACT_TYPE(Class, Base)
1736#include "clang/AST/TypeNodes.def"
1737 // T is canonical. We can also ignore dependent types because
1738 // we don't need to do ADL at the definition point, but if we
1739 // wanted to implement template export (or if we find some other
1740 // use for associated classes and namespaces...) this would be
1741 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001742 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001743
John McCallfa4edcf2010-05-28 06:08:54 +00001744 // -- If T is a pointer to U or an array of U, its associated
1745 // namespaces and classes are those associated with U.
1746 case Type::Pointer:
1747 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1748 continue;
1749 case Type::ConstantArray:
1750 case Type::IncompleteArray:
1751 case Type::VariableArray:
1752 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1753 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001754
John McCallfa4edcf2010-05-28 06:08:54 +00001755 // -- If T is a fundamental type, its associated sets of
1756 // namespaces and classes are both empty.
1757 case Type::Builtin:
1758 break;
1759
1760 // -- If T is a class type (including unions), its associated
1761 // classes are: the class itself; the class of which it is a
1762 // member, if any; and its direct and indirect base
1763 // classes. Its associated namespaces are the namespaces in
1764 // which its associated classes are defined.
1765 case Type::Record: {
1766 CXXRecordDecl *Class
1767 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001768 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001769 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001770 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001771
John McCallfa4edcf2010-05-28 06:08:54 +00001772 // -- If T is an enumeration type, its associated namespace is
1773 // the namespace in which it is defined. If it is class
1774 // member, its associated class is the member’s class; else
1775 // it has no associated class.
1776 case Type::Enum: {
1777 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001778
John McCallfa4edcf2010-05-28 06:08:54 +00001779 DeclContext *Ctx = Enum->getDeclContext();
1780 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001781 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001782
John McCallfa4edcf2010-05-28 06:08:54 +00001783 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001784 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001785
John McCallfa4edcf2010-05-28 06:08:54 +00001786 break;
1787 }
1788
1789 // -- If T is a function type, its associated namespaces and
1790 // classes are those associated with the function parameter
1791 // types and those associated with the return type.
1792 case Type::FunctionProto: {
1793 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1794 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1795 ArgEnd = Proto->arg_type_end();
1796 Arg != ArgEnd; ++Arg)
1797 Queue.push_back(Arg->getTypePtr());
1798 // fallthrough
1799 }
1800 case Type::FunctionNoProto: {
1801 const FunctionType *FnType = cast<FunctionType>(T);
1802 T = FnType->getResultType().getTypePtr();
1803 continue;
1804 }
1805
1806 // -- If T is a pointer to a member function of a class X, its
1807 // associated namespaces and classes are those associated
1808 // with the function parameter types and return type,
1809 // together with those associated with X.
1810 //
1811 // -- If T is a pointer to a data member of class X, its
1812 // associated namespaces and classes are those associated
1813 // with the member type together with those associated with
1814 // X.
1815 case Type::MemberPointer: {
1816 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1817
1818 // Queue up the class type into which this points.
1819 Queue.push_back(MemberPtr->getClass());
1820
1821 // And directly continue with the pointee type.
1822 T = MemberPtr->getPointeeType().getTypePtr();
1823 continue;
1824 }
1825
1826 // As an extension, treat this like a normal pointer.
1827 case Type::BlockPointer:
1828 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1829 continue;
1830
1831 // References aren't covered by the standard, but that's such an
1832 // obvious defect that we cover them anyway.
1833 case Type::LValueReference:
1834 case Type::RValueReference:
1835 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1836 continue;
1837
1838 // These are fundamental types.
1839 case Type::Vector:
1840 case Type::ExtVector:
1841 case Type::Complex:
1842 break;
1843
1844 // These are ignored by ADL.
1845 case Type::ObjCObject:
1846 case Type::ObjCInterface:
1847 case Type::ObjCObjectPointer:
1848 break;
1849 }
1850
1851 if (Queue.empty()) break;
1852 T = Queue.back();
1853 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001854 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001855}
1856
1857/// \brief Find the associated classes and namespaces for
1858/// argument-dependent lookup for a call with the given set of
1859/// arguments.
1860///
1861/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001862/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001863/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001864void
Douglas Gregorfa047642009-02-04 00:32:51 +00001865Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1866 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001867 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001868 AssociatedNamespaces.clear();
1869 AssociatedClasses.clear();
1870
John McCallc7e04da2010-05-28 18:45:08 +00001871 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1872
Douglas Gregorfa047642009-02-04 00:32:51 +00001873 // C++ [basic.lookup.koenig]p2:
1874 // For each argument type T in the function call, there is a set
1875 // of zero or more associated namespaces and a set of zero or more
1876 // associated classes to be considered. The sets of namespaces and
1877 // classes is determined entirely by the types of the function
1878 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001879 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001880 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1881 Expr *Arg = Args[ArgIdx];
1882
1883 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00001884 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001885 continue;
1886 }
1887
1888 // [...] In addition, if the argument is the name or address of a
1889 // set of overloaded functions and/or function templates, its
1890 // associated classes and namespaces are the union of those
1891 // associated with each of the members of the set: the namespace
1892 // in which the function or function template is defined and the
1893 // classes and namespaces associated with its (non-dependent)
1894 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001895 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001896 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1897 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1898 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001899
John McCallc7e04da2010-05-28 18:45:08 +00001900 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1901 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00001902
John McCallc7e04da2010-05-28 18:45:08 +00001903 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1904 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001905 // Look through any using declarations to find the underlying function.
1906 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001907
Chandler Carruthbd647292009-12-29 06:17:27 +00001908 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1909 if (!FDecl)
1910 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001911
1912 // Add the classes and namespaces associated with the parameter
1913 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00001914 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001915 }
1916 }
1917}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001918
1919/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1920/// an acceptable non-member overloaded operator for a call whose
1921/// arguments have types T1 (and, if non-empty, T2). This routine
1922/// implements the check in C++ [over.match.oper]p3b2 concerning
1923/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001924static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001925IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1926 QualType T1, QualType T2,
1927 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001928 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1929 return true;
1930
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001931 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1932 return true;
1933
John McCall183700f2009-09-21 23:43:11 +00001934 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001935 if (Proto->getNumArgs() < 1)
1936 return false;
1937
1938 if (T1->isEnumeralType()) {
1939 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001940 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001941 return true;
1942 }
1943
1944 if (Proto->getNumArgs() < 2)
1945 return false;
1946
1947 if (!T2.isNull() && T2->isEnumeralType()) {
1948 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001949 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001950 return true;
1951 }
1952
1953 return false;
1954}
1955
John McCall7d384dd2009-11-18 07:57:50 +00001956NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00001957 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00001958 LookupNameKind NameKind,
1959 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00001960 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00001961 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00001962 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00001963}
1964
Douglas Gregor6e378de2009-04-23 23:18:26 +00001965/// \brief Find the protocol with the given name, if any.
Douglas Gregorc83c6872010-04-15 22:33:43 +00001966ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
1967 SourceLocation IdLoc) {
1968 Decl *D = LookupSingleName(TUScope, II, IdLoc,
1969 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001970 return cast_or_null<ObjCProtocolDecl>(D);
1971}
1972
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001973void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001974 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00001975 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001976 // C++ [over.match.oper]p3:
1977 // -- The set of non-member candidates is the result of the
1978 // unqualified lookup of operator@ in the context of the
1979 // expression according to the usual rules for name lookup in
1980 // unqualified function calls (3.4.2) except that all member
1981 // functions are ignored. However, if no operand has a class
1982 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00001983 // that have a first parameter of type T1 or "reference to
1984 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001985 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00001986 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001987 // when T2 is an enumeration type, are candidate functions.
1988 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00001989 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1990 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001992 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1993
John McCallf36e02d2009-10-09 21:13:30 +00001994 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001995 return;
1996
1997 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1998 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001999 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2000 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002001 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002002 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002003 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002004 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002005 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002006 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002007 // later?
2008 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002009 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002010 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002011 }
2012}
2013
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002014/// \brief Look up the constructors for the given class.
2015DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +00002016 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002017 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2018 if (!Class->hasDeclaredDefaultConstructor())
2019 DeclareImplicitDefaultConstructor(Class);
2020 if (!Class->hasDeclaredCopyConstructor())
2021 DeclareImplicitCopyConstructor(Class);
2022 }
Douglas Gregor22584312010-07-02 23:41:54 +00002023
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002024 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2025 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2026 return Class->lookup(Name);
2027}
2028
Douglas Gregordb89f282010-07-01 22:47:18 +00002029/// \brief Look for the destructor of the given class.
2030///
2031/// During semantic analysis, this routine should be used in lieu of
2032/// CXXRecordDecl::getDestructor().
2033///
2034/// \returns The destructor for this class.
2035CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +00002036 // If the destructor has not yet been declared, do so now.
2037 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2038 !Class->hasDeclaredDestructor())
2039 DeclareImplicitDestructor(Class);
2040
Douglas Gregordb89f282010-07-01 22:47:18 +00002041 return Class->getDestructor();
2042}
2043
John McCall7edb5fd2010-01-26 07:16:45 +00002044void ADLResult::insert(NamedDecl *New) {
2045 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2046
2047 // If we haven't yet seen a decl for this key, or the last decl
2048 // was exactly this one, we're done.
2049 if (Old == 0 || Old == New) {
2050 Old = New;
2051 return;
2052 }
2053
2054 // Otherwise, decide which is a more recent redeclaration.
2055 FunctionDecl *OldFD, *NewFD;
2056 if (isa<FunctionTemplateDecl>(New)) {
2057 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2058 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2059 } else {
2060 OldFD = cast<FunctionDecl>(Old);
2061 NewFD = cast<FunctionDecl>(New);
2062 }
2063
2064 FunctionDecl *Cursor = NewFD;
2065 while (true) {
2066 Cursor = Cursor->getPreviousDeclaration();
2067
2068 // If we got to the end without finding OldFD, OldFD is the newer
2069 // declaration; leave things as they are.
2070 if (!Cursor) return;
2071
2072 // If we do find OldFD, then NewFD is newer.
2073 if (Cursor == OldFD) break;
2074
2075 // Otherwise, keep looking.
2076 }
2077
2078 Old = New;
2079}
2080
Sebastian Redl644be852009-10-23 19:23:15 +00002081void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002082 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00002083 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002084 // Find all of the associated namespaces and classes based on the
2085 // arguments we have.
2086 AssociatedNamespaceSet AssociatedNamespaces;
2087 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002088 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002089 AssociatedNamespaces,
2090 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002091
Sebastian Redl644be852009-10-23 19:23:15 +00002092 QualType T1, T2;
2093 if (Operator) {
2094 T1 = Args[0]->getType();
2095 if (NumArgs >= 2)
2096 T2 = Args[1]->getType();
2097 }
2098
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002099 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002100 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2101 // and let Y be the lookup set produced by argument dependent
2102 // lookup (defined as follows). If X contains [...] then Y is
2103 // empty. Otherwise Y is the set of declarations found in the
2104 // namespaces associated with the argument types as described
2105 // below. The set of declarations found by the lookup of the name
2106 // is the union of X and Y.
2107 //
2108 // Here, we compute Y and add its members to the overloaded
2109 // candidate set.
2110 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002111 NSEnd = AssociatedNamespaces.end();
2112 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002113 // When considering an associated namespace, the lookup is the
2114 // same as the lookup performed when the associated namespace is
2115 // used as a qualifier (3.4.3.2) except that:
2116 //
2117 // -- Any using-directives in the associated namespace are
2118 // ignored.
2119 //
John McCall6ff07852009-08-07 22:18:02 +00002120 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002121 // associated classes are visible within their respective
2122 // namespaces even if they are not visible during an ordinary
2123 // lookup (11.4).
2124 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002125 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002126 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002127 // If the only declaration here is an ordinary friend, consider
2128 // it only if it was declared in an associated classes.
2129 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002130 DeclContext *LexDC = D->getLexicalDeclContext();
2131 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2132 continue;
2133 }
Mike Stump1eb44332009-09-09 15:08:12 +00002134
John McCalla113e722010-01-26 06:04:06 +00002135 if (isa<UsingShadowDecl>(D))
2136 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002137
John McCalla113e722010-01-26 06:04:06 +00002138 if (isa<FunctionDecl>(D)) {
2139 if (Operator &&
2140 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2141 T1, T2, Context))
2142 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002143 } else if (!isa<FunctionTemplateDecl>(D))
2144 continue;
2145
2146 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002147 }
2148 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002149}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002150
2151//----------------------------------------------------------------------------
2152// Search for all visible declarations.
2153//----------------------------------------------------------------------------
2154VisibleDeclConsumer::~VisibleDeclConsumer() { }
2155
2156namespace {
2157
2158class ShadowContextRAII;
2159
2160class VisibleDeclsRecord {
2161public:
2162 /// \brief An entry in the shadow map, which is optimized to store a
2163 /// single declaration (the common case) but can also store a list
2164 /// of declarations.
2165 class ShadowMapEntry {
2166 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2167
2168 /// \brief Contains either the solitary NamedDecl * or a vector
2169 /// of declarations.
2170 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2171
2172 public:
2173 ShadowMapEntry() : DeclOrVector() { }
2174
2175 void Add(NamedDecl *ND);
2176 void Destroy();
2177
2178 // Iteration.
2179 typedef NamedDecl **iterator;
2180 iterator begin();
2181 iterator end();
2182 };
2183
2184private:
2185 /// \brief A mapping from declaration names to the declarations that have
2186 /// this name within a particular scope.
2187 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2188
2189 /// \brief A list of shadow maps, which is used to model name hiding.
2190 std::list<ShadowMap> ShadowMaps;
2191
2192 /// \brief The declaration contexts we have already visited.
2193 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2194
2195 friend class ShadowContextRAII;
2196
2197public:
2198 /// \brief Determine whether we have already visited this context
2199 /// (and, if not, note that we are going to visit that context now).
2200 bool visitedContext(DeclContext *Ctx) {
2201 return !VisitedContexts.insert(Ctx);
2202 }
2203
2204 /// \brief Determine whether the given declaration is hidden in the
2205 /// current scope.
2206 ///
2207 /// \returns the declaration that hides the given declaration, or
2208 /// NULL if no such declaration exists.
2209 NamedDecl *checkHidden(NamedDecl *ND);
2210
2211 /// \brief Add a declaration to the current shadow map.
2212 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2213};
2214
2215/// \brief RAII object that records when we've entered a shadow context.
2216class ShadowContextRAII {
2217 VisibleDeclsRecord &Visible;
2218
2219 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2220
2221public:
2222 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2223 Visible.ShadowMaps.push_back(ShadowMap());
2224 }
2225
2226 ~ShadowContextRAII() {
2227 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2228 EEnd = Visible.ShadowMaps.back().end();
2229 E != EEnd;
2230 ++E)
2231 E->second.Destroy();
2232
2233 Visible.ShadowMaps.pop_back();
2234 }
2235};
2236
2237} // end anonymous namespace
2238
2239void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2240 if (DeclOrVector.isNull()) {
2241 // 0 - > 1 elements: just set the single element information.
2242 DeclOrVector = ND;
2243 return;
2244 }
2245
2246 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2247 // 1 -> 2 elements: create the vector of results and push in the
2248 // existing declaration.
2249 DeclVector *Vec = new DeclVector;
2250 Vec->push_back(PrevND);
2251 DeclOrVector = Vec;
2252 }
2253
2254 // Add the new element to the end of the vector.
2255 DeclOrVector.get<DeclVector*>()->push_back(ND);
2256}
2257
2258void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2259 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2260 delete Vec;
2261 DeclOrVector = ((NamedDecl *)0);
2262 }
2263}
2264
2265VisibleDeclsRecord::ShadowMapEntry::iterator
2266VisibleDeclsRecord::ShadowMapEntry::begin() {
2267 if (DeclOrVector.isNull())
2268 return 0;
2269
2270 if (DeclOrVector.dyn_cast<NamedDecl *>())
2271 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2272
2273 return DeclOrVector.get<DeclVector *>()->begin();
2274}
2275
2276VisibleDeclsRecord::ShadowMapEntry::iterator
2277VisibleDeclsRecord::ShadowMapEntry::end() {
2278 if (DeclOrVector.isNull())
2279 return 0;
2280
2281 if (DeclOrVector.dyn_cast<NamedDecl *>())
2282 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2283
2284 return DeclOrVector.get<DeclVector *>()->end();
2285}
2286
2287NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002288 // Look through using declarations.
2289 ND = ND->getUnderlyingDecl();
2290
Douglas Gregor546be3c2009-12-30 17:04:44 +00002291 unsigned IDNS = ND->getIdentifierNamespace();
2292 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2293 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2294 SM != SMEnd; ++SM) {
2295 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2296 if (Pos == SM->end())
2297 continue;
2298
2299 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2300 IEnd = Pos->second.end();
2301 I != IEnd; ++I) {
2302 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002303 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor546be3c2009-12-30 17:04:44 +00002304 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2305 Decl::IDNS_ObjCProtocol)))
2306 continue;
2307
2308 // Protocols are in distinct namespaces from everything else.
2309 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2310 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2311 (*I)->getIdentifierNamespace() != IDNS)
2312 continue;
2313
Douglas Gregor0cc84042010-01-14 15:47:35 +00002314 // Functions and function templates in the same scope overload
2315 // rather than hide. FIXME: Look for hiding based on function
2316 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002317 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002318 ND->isFunctionOrFunctionTemplate() &&
2319 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002320 continue;
2321
Douglas Gregor546be3c2009-12-30 17:04:44 +00002322 // We've found a declaration that hides this one.
2323 return *I;
2324 }
2325 }
2326
2327 return 0;
2328}
2329
2330static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2331 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002332 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002333 VisibleDeclConsumer &Consumer,
2334 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002335 if (!Ctx)
2336 return;
2337
Douglas Gregor546be3c2009-12-30 17:04:44 +00002338 // Make sure we don't visit the same context twice.
2339 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2340 return;
2341
Douglas Gregor4923aa22010-07-02 20:37:36 +00002342 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2343 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2344
Douglas Gregor546be3c2009-12-30 17:04:44 +00002345 // Enumerate all of the results in this context.
2346 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2347 CurCtx = CurCtx->getNextContext()) {
2348 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2349 DEnd = CurCtx->decls_end();
2350 D != DEnd; ++D) {
2351 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2352 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002353 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002354 Visited.add(ND);
2355 }
2356
2357 // Visit transparent contexts inside this context.
2358 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2359 if (InnerCtx->isTransparentContext())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002360 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002361 Consumer, Visited);
2362 }
2363 }
2364 }
2365
2366 // Traverse using directives for qualified name lookup.
2367 if (QualifiedNameLookup) {
2368 ShadowContextRAII Shadow(Visited);
2369 DeclContext::udir_iterator I, E;
2370 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2371 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002372 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002373 }
2374 }
2375
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002376 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002377 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002378 if (!Record->hasDefinition())
2379 return;
2380
Douglas Gregor546be3c2009-12-30 17:04:44 +00002381 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2382 BEnd = Record->bases_end();
2383 B != BEnd; ++B) {
2384 QualType BaseType = B->getType();
2385
2386 // Don't look into dependent bases, because name lookup can't look
2387 // there anyway.
2388 if (BaseType->isDependentType())
2389 continue;
2390
2391 const RecordType *Record = BaseType->getAs<RecordType>();
2392 if (!Record)
2393 continue;
2394
2395 // FIXME: It would be nice to be able to determine whether referencing
2396 // a particular member would be ambiguous. For example, given
2397 //
2398 // struct A { int member; };
2399 // struct B { int member; };
2400 // struct C : A, B { };
2401 //
2402 // void f(C *c) { c->### }
2403 //
2404 // accessing 'member' would result in an ambiguity. However, we
2405 // could be smart enough to qualify the member with the base
2406 // class, e.g.,
2407 //
2408 // c->B::member
2409 //
2410 // or
2411 //
2412 // c->A::member
2413
2414 // Find results in this base class (and its bases).
2415 ShadowContextRAII Shadow(Visited);
2416 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002417 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002418 }
2419 }
2420
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002421 // Traverse the contexts of Objective-C classes.
2422 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2423 // Traverse categories.
2424 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2425 Category; Category = Category->getNextClassCategory()) {
2426 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002427 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2428 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002429 }
2430
2431 // Traverse protocols.
2432 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2433 E = IFace->protocol_end(); I != E; ++I) {
2434 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002435 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2436 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002437 }
2438
2439 // Traverse the superclass.
2440 if (IFace->getSuperClass()) {
2441 ShadowContextRAII Shadow(Visited);
2442 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002443 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002444 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002445
2446 // If there is an implementation, traverse it. We do this to find
2447 // synthesized ivars.
2448 if (IFace->getImplementation()) {
2449 ShadowContextRAII Shadow(Visited);
2450 LookupVisibleDecls(IFace->getImplementation(), Result,
2451 QualifiedNameLookup, true, Consumer, Visited);
2452 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002453 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2454 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2455 E = Protocol->protocol_end(); I != E; ++I) {
2456 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002457 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2458 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002459 }
2460 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2461 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2462 E = Category->protocol_end(); I != E; ++I) {
2463 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002464 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2465 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002466 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002467
2468 // If there is an implementation, traverse it.
2469 if (Category->getImplementation()) {
2470 ShadowContextRAII Shadow(Visited);
2471 LookupVisibleDecls(Category->getImplementation(), Result,
2472 QualifiedNameLookup, true, Consumer, Visited);
2473 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002474 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002475}
2476
2477static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2478 UnqualUsingDirectiveSet &UDirs,
2479 VisibleDeclConsumer &Consumer,
2480 VisibleDeclsRecord &Visited) {
2481 if (!S)
2482 return;
2483
Douglas Gregor539c5c32010-01-07 00:31:29 +00002484 if (!S->getEntity() || !S->getParent() ||
2485 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2486 // Walk through the declarations in this Scope.
2487 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2488 D != DEnd; ++D) {
2489 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2490 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002491 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002492 Visited.add(ND);
2493 }
2494 }
2495 }
2496
Douglas Gregor711be1e2010-03-15 14:33:29 +00002497 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002498 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002499 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002500 // Look into this scope's declaration context, along with any of its
2501 // parent lookup contexts (e.g., enclosing classes), up to the point
2502 // where we hit the context stored in the next outer scope.
2503 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002504 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor546be3c2009-12-30 17:04:44 +00002505
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002506 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002507 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002508 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2509 if (Method->isInstanceMethod()) {
2510 // For instance methods, look for ivars in the method's interface.
2511 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2512 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor62021192010-02-04 23:42:48 +00002513 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2514 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2515 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002516 }
2517
2518 // We've already performed all of the name lookup that we need
2519 // to for Objective-C methods; the next context will be the
2520 // outer scope.
2521 break;
2522 }
2523
Douglas Gregor546be3c2009-12-30 17:04:44 +00002524 if (Ctx->isFunctionOrMethod())
2525 continue;
2526
2527 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002528 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002529 }
2530 } else if (!S->getParent()) {
2531 // Look into the translation unit scope. We walk through the translation
2532 // unit's declaration context, because the Scope itself won't have all of
2533 // the declarations if we loaded a precompiled header.
2534 // FIXME: We would like the translation unit's Scope object to point to the
2535 // translation unit, so we don't need this special "if" branch. However,
2536 // doing so would force the normal C++ name-lookup code to look into the
2537 // translation unit decl when the IdentifierInfo chains would suffice.
2538 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002539 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002540 Entity = Result.getSema().Context.getTranslationUnitDecl();
2541 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002542 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002543 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002544
2545 if (Entity) {
2546 // Lookup visible declarations in any namespaces found by using
2547 // directives.
2548 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2549 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2550 for (; UI != UEnd; ++UI)
2551 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002552 Result, /*QualifiedNameLookup=*/false,
2553 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002554 }
2555
2556 // Lookup names in the parent scope.
2557 ShadowContextRAII Shadow(Visited);
2558 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2559}
2560
2561void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2562 VisibleDeclConsumer &Consumer) {
2563 // Determine the set of using directives available during
2564 // unqualified name lookup.
2565 Scope *Initial = S;
2566 UnqualUsingDirectiveSet UDirs;
2567 if (getLangOptions().CPlusPlus) {
2568 // Find the first namespace or translation-unit scope.
2569 while (S && !isNamespaceOrTranslationUnitScope(S))
2570 S = S->getParent();
2571
2572 UDirs.visitScopeChain(Initial, S);
2573 }
2574 UDirs.done();
2575
2576 // Look for visible declarations.
2577 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2578 VisibleDeclsRecord Visited;
2579 ShadowContextRAII Shadow(Visited);
2580 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2581}
2582
2583void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2584 VisibleDeclConsumer &Consumer) {
2585 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2586 VisibleDeclsRecord Visited;
2587 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002588 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2589 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002590}
2591
2592//----------------------------------------------------------------------------
2593// Typo correction
2594//----------------------------------------------------------------------------
2595
2596namespace {
2597class TypoCorrectionConsumer : public VisibleDeclConsumer {
2598 /// \brief The name written that is a typo in the source.
2599 llvm::StringRef Typo;
2600
2601 /// \brief The results found that have the smallest edit distance
2602 /// found (so far) with the typo name.
2603 llvm::SmallVector<NamedDecl *, 4> BestResults;
2604
Douglas Gregoraaf87162010-04-14 20:04:41 +00002605 /// \brief The keywords that have the smallest edit distance.
2606 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2607
Douglas Gregor546be3c2009-12-30 17:04:44 +00002608 /// \brief The best edit distance found so far.
2609 unsigned BestEditDistance;
2610
2611public:
2612 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2613 : Typo(Typo->getName()) { }
2614
Douglas Gregor0cc84042010-01-14 15:47:35 +00002615 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002616 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002617
2618 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2619 iterator begin() const { return BestResults.begin(); }
2620 iterator end() const { return BestResults.end(); }
Douglas Gregoraaf87162010-04-14 20:04:41 +00002621 void clear_decls() { BestResults.clear(); }
2622
2623 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002624
Douglas Gregoraaf87162010-04-14 20:04:41 +00002625 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2626 keyword_iterator;
2627 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2628 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2629 bool keyword_empty() const { return BestKeywords.empty(); }
2630 unsigned keyword_size() const { return BestKeywords.size(); }
2631
2632 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002633};
2634
2635}
2636
Douglas Gregor0cc84042010-01-14 15:47:35 +00002637void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2638 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002639 // Don't consider hidden names for typo correction.
2640 if (Hiding)
2641 return;
2642
2643 // Only consider entities with identifiers for names, ignoring
2644 // special names (constructors, overloaded operators, selectors,
2645 // etc.).
2646 IdentifierInfo *Name = ND->getIdentifier();
2647 if (!Name)
2648 return;
2649
2650 // Compute the edit distance between the typo and the name of this
2651 // entity. If this edit distance is not worse than the best edit
2652 // distance we've seen so far, add it to the list of results.
2653 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregoraaf87162010-04-14 20:04:41 +00002654 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002655 if (ED < BestEditDistance) {
2656 // This result is better than any we've seen before; clear out
2657 // the previous results.
2658 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002659 BestKeywords.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002660 BestEditDistance = ED;
2661 } else if (ED > BestEditDistance) {
2662 // This result is worse than the best results we've seen so far;
2663 // ignore it.
2664 return;
2665 }
2666 } else
2667 BestEditDistance = ED;
2668
2669 BestResults.push_back(ND);
2670}
2671
Douglas Gregoraaf87162010-04-14 20:04:41 +00002672void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2673 llvm::StringRef Keyword) {
2674 // Compute the edit distance between the typo and this keyword.
2675 // If this edit distance is not worse than the best edit
2676 // distance we've seen so far, add it to the list of results.
2677 unsigned ED = Typo.edit_distance(Keyword);
2678 if (!BestResults.empty() || !BestKeywords.empty()) {
2679 if (ED < BestEditDistance) {
2680 BestResults.clear();
2681 BestKeywords.clear();
2682 BestEditDistance = ED;
2683 } else if (ED > BestEditDistance) {
2684 // This result is worse than the best results we've seen so far;
2685 // ignore it.
2686 return;
2687 }
2688 } else
2689 BestEditDistance = ED;
2690
2691 BestKeywords.push_back(&Context.Idents.get(Keyword));
2692}
2693
Douglas Gregor546be3c2009-12-30 17:04:44 +00002694/// \brief Try to "correct" a typo in the source code by finding
2695/// visible declarations whose names are similar to the name that was
2696/// present in the source code.
2697///
2698/// \param Res the \c LookupResult structure that contains the name
2699/// that was present in the source code along with the name-lookup
2700/// criteria used to search for the name. On success, this structure
2701/// will contain the results of name lookup.
2702///
2703/// \param S the scope in which name lookup occurs.
2704///
2705/// \param SS the nested-name-specifier that precedes the name we're
2706/// looking for, if present.
2707///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002708/// \param MemberContext if non-NULL, the context in which to look for
2709/// a member access expression.
2710///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002711/// \param EnteringContext whether we're entering the context described by
2712/// the nested-name-specifier SS.
2713///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002714/// \param CTC The context in which typo correction occurs, which impacts the
2715/// set of keywords permitted.
2716///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002717/// \param OPT when non-NULL, the search for visible declarations will
2718/// also walk the protocols in the qualified interfaces of \p OPT.
2719///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002720/// \returns the corrected name if the typo was corrected, otherwise returns an
2721/// empty \c DeclarationName. When a typo was corrected, the result structure
2722/// may contain the results of name lookup for the correct name or it may be
2723/// empty.
2724DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002725 DeclContext *MemberContext,
2726 bool EnteringContext,
2727 CorrectTypoContext CTC,
2728 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00002729 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002730 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002731
2732 // Provide a stop gap for files that are just seriously broken. Trying
2733 // to correct all typos can turn into a HUGE performance penalty, causing
2734 // some files to take minutes to get rejected by the parser.
2735 // FIXME: Is this the right solution?
2736 if (TyposCorrected == 20)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002737 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002738 ++TyposCorrected;
Ted Kremenek1dac3412010-01-06 00:23:04 +00002739
Douglas Gregor546be3c2009-12-30 17:04:44 +00002740 // We only attempt to correct typos for identifiers.
2741 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2742 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002743 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002744
2745 // If the scope specifier itself was invalid, don't try to correct
2746 // typos.
2747 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002748 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002749
2750 // Never try to correct typos during template deduction or
2751 // instantiation.
2752 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002753 return DeclarationName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002754
Douglas Gregor546be3c2009-12-30 17:04:44 +00002755 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002756
2757 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002758 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002759 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002760
2761 // Look in qualified interfaces.
2762 if (OPT) {
2763 for (ObjCObjectPointerType::qual_iterator
2764 I = OPT->qual_begin(), E = OPT->qual_end();
2765 I != E; ++I)
2766 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2767 }
2768 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002769 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2770 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002771 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002772
2773 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2774 } else {
2775 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2776 }
2777
Douglas Gregoraaf87162010-04-14 20:04:41 +00002778 // Add context-dependent keywords.
2779 bool WantTypeSpecifiers = false;
2780 bool WantExpressionKeywords = false;
2781 bool WantCXXNamedCasts = false;
2782 bool WantRemainingKeywords = false;
2783 switch (CTC) {
2784 case CTC_Unknown:
2785 WantTypeSpecifiers = true;
2786 WantExpressionKeywords = true;
2787 WantCXXNamedCasts = true;
2788 WantRemainingKeywords = true;
Douglas Gregor91f7ac72010-05-18 16:14:23 +00002789
2790 if (ObjCMethodDecl *Method = getCurMethodDecl())
2791 if (Method->getClassInterface() &&
2792 Method->getClassInterface()->getSuperClass())
2793 Consumer.addKeywordResult(Context, "super");
2794
Douglas Gregoraaf87162010-04-14 20:04:41 +00002795 break;
2796
2797 case CTC_NoKeywords:
2798 break;
2799
2800 case CTC_Type:
2801 WantTypeSpecifiers = true;
2802 break;
2803
2804 case CTC_ObjCMessageReceiver:
2805 Consumer.addKeywordResult(Context, "super");
2806 // Fall through to handle message receivers like expressions.
2807
2808 case CTC_Expression:
2809 if (getLangOptions().CPlusPlus)
2810 WantTypeSpecifiers = true;
2811 WantExpressionKeywords = true;
2812 // Fall through to get C++ named casts.
2813
2814 case CTC_CXXCasts:
2815 WantCXXNamedCasts = true;
2816 break;
2817
2818 case CTC_MemberLookup:
2819 if (getLangOptions().CPlusPlus)
2820 Consumer.addKeywordResult(Context, "template");
2821 break;
2822 }
2823
2824 if (WantTypeSpecifiers) {
2825 // Add type-specifier keywords to the set of results.
2826 const char *CTypeSpecs[] = {
2827 "char", "const", "double", "enum", "float", "int", "long", "short",
2828 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2829 "_Complex", "_Imaginary",
2830 // storage-specifiers as well
2831 "extern", "inline", "static", "typedef"
2832 };
2833
2834 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2835 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2836 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2837
2838 if (getLangOptions().C99)
2839 Consumer.addKeywordResult(Context, "restrict");
2840 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2841 Consumer.addKeywordResult(Context, "bool");
2842
2843 if (getLangOptions().CPlusPlus) {
2844 Consumer.addKeywordResult(Context, "class");
2845 Consumer.addKeywordResult(Context, "typename");
2846 Consumer.addKeywordResult(Context, "wchar_t");
2847
2848 if (getLangOptions().CPlusPlus0x) {
2849 Consumer.addKeywordResult(Context, "char16_t");
2850 Consumer.addKeywordResult(Context, "char32_t");
2851 Consumer.addKeywordResult(Context, "constexpr");
2852 Consumer.addKeywordResult(Context, "decltype");
2853 Consumer.addKeywordResult(Context, "thread_local");
2854 }
2855 }
2856
2857 if (getLangOptions().GNUMode)
2858 Consumer.addKeywordResult(Context, "typeof");
2859 }
2860
Douglas Gregord0785ea2010-05-18 16:30:22 +00002861 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00002862 Consumer.addKeywordResult(Context, "const_cast");
2863 Consumer.addKeywordResult(Context, "dynamic_cast");
2864 Consumer.addKeywordResult(Context, "reinterpret_cast");
2865 Consumer.addKeywordResult(Context, "static_cast");
2866 }
2867
2868 if (WantExpressionKeywords) {
2869 Consumer.addKeywordResult(Context, "sizeof");
2870 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2871 Consumer.addKeywordResult(Context, "false");
2872 Consumer.addKeywordResult(Context, "true");
2873 }
2874
2875 if (getLangOptions().CPlusPlus) {
2876 const char *CXXExprs[] = {
2877 "delete", "new", "operator", "throw", "typeid"
2878 };
2879 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2880 for (unsigned I = 0; I != NumCXXExprs; ++I)
2881 Consumer.addKeywordResult(Context, CXXExprs[I]);
2882
2883 if (isa<CXXMethodDecl>(CurContext) &&
2884 cast<CXXMethodDecl>(CurContext)->isInstance())
2885 Consumer.addKeywordResult(Context, "this");
2886
2887 if (getLangOptions().CPlusPlus0x) {
2888 Consumer.addKeywordResult(Context, "alignof");
2889 Consumer.addKeywordResult(Context, "nullptr");
2890 }
2891 }
2892 }
2893
2894 if (WantRemainingKeywords) {
2895 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2896 // Statements.
2897 const char *CStmts[] = {
2898 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2899 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2900 for (unsigned I = 0; I != NumCStmts; ++I)
2901 Consumer.addKeywordResult(Context, CStmts[I]);
2902
2903 if (getLangOptions().CPlusPlus) {
2904 Consumer.addKeywordResult(Context, "catch");
2905 Consumer.addKeywordResult(Context, "try");
2906 }
2907
2908 if (S && S->getBreakParent())
2909 Consumer.addKeywordResult(Context, "break");
2910
2911 if (S && S->getContinueParent())
2912 Consumer.addKeywordResult(Context, "continue");
2913
2914 if (!getSwitchStack().empty()) {
2915 Consumer.addKeywordResult(Context, "case");
2916 Consumer.addKeywordResult(Context, "default");
2917 }
2918 } else {
2919 if (getLangOptions().CPlusPlus) {
2920 Consumer.addKeywordResult(Context, "namespace");
2921 Consumer.addKeywordResult(Context, "template");
2922 }
2923
2924 if (S && S->isClassScope()) {
2925 Consumer.addKeywordResult(Context, "explicit");
2926 Consumer.addKeywordResult(Context, "friend");
2927 Consumer.addKeywordResult(Context, "mutable");
2928 Consumer.addKeywordResult(Context, "private");
2929 Consumer.addKeywordResult(Context, "protected");
2930 Consumer.addKeywordResult(Context, "public");
2931 Consumer.addKeywordResult(Context, "virtual");
2932 }
2933 }
2934
2935 if (getLangOptions().CPlusPlus) {
2936 Consumer.addKeywordResult(Context, "using");
2937
2938 if (getLangOptions().CPlusPlus0x)
2939 Consumer.addKeywordResult(Context, "static_assert");
2940 }
2941 }
2942
2943 // If we haven't found anything, we're done.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002944 if (Consumer.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002945 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002946
2947 // Only allow a single, closest name in the result set (it's okay to
2948 // have overloads of that name, though).
Douglas Gregoraaf87162010-04-14 20:04:41 +00002949 DeclarationName BestName;
2950 NamedDecl *BestIvarOrPropertyDecl = 0;
2951 bool FoundIvarOrPropertyDecl = false;
2952
2953 // Check all of the declaration results to find the best name so far.
2954 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2955 IEnd = Consumer.end();
2956 I != IEnd; ++I) {
2957 if (!BestName)
2958 BestName = (*I)->getDeclName();
2959 else if (BestName != (*I)->getDeclName())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002960 return DeclarationName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002961
Douglas Gregoraaf87162010-04-14 20:04:41 +00002962 // \brief Keep track of either an Objective-C ivar or a property, but not
2963 // both.
2964 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
2965 if (FoundIvarOrPropertyDecl)
2966 BestIvarOrPropertyDecl = 0;
2967 else {
2968 BestIvarOrPropertyDecl = *I;
2969 FoundIvarOrPropertyDecl = true;
2970 }
2971 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002972 }
2973
Douglas Gregoraaf87162010-04-14 20:04:41 +00002974 // Now check all of the keyword results to find the best name.
2975 switch (Consumer.keyword_size()) {
2976 case 0:
2977 // No keywords matched.
2978 break;
2979
2980 case 1:
2981 // If we already have a name
2982 if (!BestName) {
2983 // We did not have anything previously,
2984 BestName = *Consumer.keyword_begin();
2985 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
2986 // We have a declaration with the same name as a context-sensitive
2987 // keyword. The keyword takes precedence.
2988 BestIvarOrPropertyDecl = 0;
2989 FoundIvarOrPropertyDecl = false;
2990 Consumer.clear_decls();
Douglas Gregord0785ea2010-05-18 16:30:22 +00002991 } else if (CTC == CTC_ObjCMessageReceiver &&
2992 (*Consumer.keyword_begin())->isStr("super")) {
2993 // In an Objective-C message send, give the "super" keyword a slight
2994 // edge over entities not in function or method scope.
2995 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2996 IEnd = Consumer.end();
2997 I != IEnd; ++I) {
2998 if ((*I)->getDeclName() == BestName) {
2999 if ((*I)->getDeclContext()->isFunctionOrMethod())
3000 return DeclarationName();
3001 }
3002 }
3003
3004 // Everything found was outside a function or method; the 'super'
3005 // keyword takes precedence.
3006 BestIvarOrPropertyDecl = 0;
3007 FoundIvarOrPropertyDecl = false;
3008 Consumer.clear_decls();
3009 BestName = *Consumer.keyword_begin();
Douglas Gregoraaf87162010-04-14 20:04:41 +00003010 } else {
3011 // Name collision; we will not correct typos.
3012 return DeclarationName();
3013 }
3014 break;
3015
3016 default:
3017 // Name collision; we will not correct typos.
3018 return DeclarationName();
3019 }
3020
Douglas Gregor546be3c2009-12-30 17:04:44 +00003021 // BestName is the closest viable name to what the user
3022 // typed. However, to make sure that we don't pick something that's
3023 // way off, make sure that the user typed at least 3 characters for
3024 // each correction.
3025 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregoraaf87162010-04-14 20:04:41 +00003026 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
3027 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregor931f98a2010-04-14 17:09:22 +00003028 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003029
3030 // Perform name lookup again with the name we chose, and declare
3031 // success if we found something that was not ambiguous.
3032 Res.clear();
3033 Res.setLookupName(BestName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003034
3035 // If we found an ivar or property, add that result; no further
3036 // lookup is required.
Douglas Gregoraaf87162010-04-14 20:04:41 +00003037 if (BestIvarOrPropertyDecl)
3038 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003039 // If we're looking into the context of a member, perform qualified
3040 // name lookup on the best name.
Douglas Gregoraaf87162010-04-14 20:04:41 +00003041 else if (!Consumer.keyword_empty()) {
3042 // The best match was a keyword. Return it.
3043 return BestName;
3044 } else if (MemberContext)
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003045 LookupQualifiedName(Res, MemberContext);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003046 // Perform lookup as if we had just parsed the best name.
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003047 else
3048 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3049 EnteringContext);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003050
3051 if (Res.isAmbiguous()) {
3052 Res.suppressDiagnostics();
Douglas Gregor931f98a2010-04-14 17:09:22 +00003053 return DeclarationName();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003054 }
3055
Douglas Gregor931f98a2010-04-14 17:09:22 +00003056 if (Res.getResultKind() != LookupResult::NotFound)
3057 return BestName;
3058
3059 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003060}