blob: 1ffea89acdaa7b42b9ea9b3ad991a844fdff1b98 [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//===----------------------------------------------------------------------===//
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/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()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000270 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000271 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;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000314 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
315
John McCallf36e02d2009-10-09 21:13:30 +0000316 bool Ambiguous = false;
317 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000318 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000319
320 unsigned UniqueTagIndex = 0;
321
322 unsigned I = 0;
323 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000324 NamedDecl *D = Decls[I]->getUnderlyingDecl();
325 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000326
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000327 // Redeclarations of types via typedef can occur both within a scope
328 // and, through using declarations and directives, across scopes. There is
329 // no ambiguity if they all refer to the same type, so unique based on the
330 // canonical type.
331 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
332 if (!TD->getDeclContext()->isRecord()) {
333 QualType T = SemaRef.Context.getTypeDeclType(TD);
334 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
335 // The type is not unique; pull something off the back and continue
336 // at this index.
337 Decls[I] = Decls[--N];
338 continue;
339 }
340 }
341 }
342
John McCall314be4e2009-11-17 07:50:12 +0000343 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000344 // If it's not unique, pull something off the back (and
345 // continue at this index).
346 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000347 continue;
348 }
349
350 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000351
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000352 if (isa<UnresolvedUsingValueDecl>(D)) {
353 HasUnresolved = true;
354 } else if (isa<TagDecl>(D)) {
355 if (HasTag)
356 Ambiguous = true;
357 UniqueTagIndex = I;
358 HasTag = true;
359 } else if (isa<FunctionTemplateDecl>(D)) {
360 HasFunction = true;
361 HasFunctionTemplate = true;
362 } else if (isa<FunctionDecl>(D)) {
363 HasFunction = true;
364 } else {
365 if (HasNonFunction)
366 Ambiguous = true;
367 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000368 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000369 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000370 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000371
John McCallf36e02d2009-10-09 21:13:30 +0000372 // C++ [basic.scope.hiding]p2:
373 // A class name or enumeration name can be hidden by the name of
374 // an object, function, or enumerator declared in the same
375 // scope. If a class or enumeration name and an object, function,
376 // or enumerator are declared in the same scope (in any order)
377 // with the same name, the class or enumeration name is hidden
378 // wherever the object, function, or enumerator name is visible.
379 // But it's still an error if there are distinct tag types found,
380 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000381 if (HideTags && HasTag && !Ambiguous &&
382 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000383 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000384
John McCallf36e02d2009-10-09 21:13:30 +0000385 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000386
John McCallfda8e122009-12-03 00:58:24 +0000387 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000388 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000389
John McCallf36e02d2009-10-09 21:13:30 +0000390 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000391 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000392 else if (HasUnresolved)
393 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000394 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000395 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000396 else
John McCalla24dc2e2009-11-17 02:14:36 +0000397 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000398}
399
John McCall7d384dd2009-11-18 07:57:50 +0000400void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000401 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000402 DeclContext::lookup_iterator DI, DE;
403 for (I = P.begin(), E = P.end(); I != E; ++I)
404 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
405 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000406}
407
John McCall7d384dd2009-11-18 07:57:50 +0000408void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000409 Paths = new CXXBasePaths;
410 Paths->swap(P);
411 addDeclsFromBasePaths(*Paths);
412 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000413 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000414}
415
John McCall7d384dd2009-11-18 07:57:50 +0000416void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000417 Paths = new CXXBasePaths;
418 Paths->swap(P);
419 addDeclsFromBasePaths(*Paths);
420 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000421 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000422}
423
John McCall7d384dd2009-11-18 07:57:50 +0000424void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000425 Out << Decls.size() << " result(s)";
426 if (isAmbiguous()) Out << ", ambiguous";
427 if (Paths) Out << ", base paths present";
428
429 for (iterator I = begin(), E = end(); I != E; ++I) {
430 Out << "\n";
431 (*I)->print(Out, 2);
432 }
433}
434
Douglas Gregor85910982010-02-12 05:48:04 +0000435/// \brief Lookup a builtin function, when name lookup would otherwise
436/// fail.
437static bool LookupBuiltin(Sema &S, LookupResult &R) {
438 Sema::LookupNameKind NameKind = R.getLookupKind();
439
440 // If we didn't find a use of this identifier, and if the identifier
441 // corresponds to a compiler builtin, create the decl object for the builtin
442 // now, injecting it into translation unit scope, and return it.
443 if (NameKind == Sema::LookupOrdinaryName ||
444 NameKind == Sema::LookupRedeclarationWithLinkage) {
445 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
446 if (II) {
447 // If this is a builtin on this (or all) targets, create the decl.
448 if (unsigned BuiltinID = II->getBuiltinID()) {
449 // In C++, we don't have any predefined library functions like
450 // 'malloc'. Instead, we'll just error.
451 if (S.getLangOptions().CPlusPlus &&
452 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
453 return false;
454
455 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
456 S.TUScope, R.isForRedeclaration(),
457 R.getNameLoc());
458 if (D)
459 R.addDecl(D);
460 return (D != NULL);
461 }
462 }
463 }
464
465 return false;
466}
467
Douglas Gregor4923aa22010-07-02 20:37:36 +0000468/// \brief Determine whether we can declare a special member function within
469/// the class at this point.
470static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
471 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000472 // Don't do it if the class is invalid.
473 if (Class->isInvalidDecl())
474 return false;
475
Douglas Gregor4923aa22010-07-02 20:37:36 +0000476 // We need to have a definition for the class.
477 if (!Class->getDefinition() || Class->isDependentContext())
478 return false;
479
480 // We can't be in the middle of defining the class.
481 if (const RecordType *RecordTy
482 = Context.getTypeDeclType(Class)->getAs<RecordType>())
483 return !RecordTy->isBeingDefined();
484
485 return false;
486}
487
488void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000489 if (!CanDeclareSpecialMemberFunction(Context, Class))
490 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000491
492 // If the default constructor has not yet been declared, do so now.
493 if (!Class->hasDeclaredDefaultConstructor())
494 DeclareImplicitDefaultConstructor(Class);
Douglas Gregor22584312010-07-02 23:41:54 +0000495
496 // If the copy constructor has not yet been declared, do so now.
497 if (!Class->hasDeclaredCopyConstructor())
498 DeclareImplicitCopyConstructor(Class);
499
Douglas Gregora376d102010-07-02 21:50:04 +0000500 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000501 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000502 DeclareImplicitCopyAssignment(Class);
503
Douglas Gregor4923aa22010-07-02 20:37:36 +0000504 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000505 if (!Class->hasDeclaredDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +0000506 DeclareImplicitDestructor(Class);
507}
508
Douglas Gregora376d102010-07-02 21:50:04 +0000509/// \brief Determine whether this is the name of an implicitly-declared
510/// special member function.
511static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
512 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000513 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000514 case DeclarationName::CXXDestructorName:
515 return true;
516
517 case DeclarationName::CXXOperatorName:
518 return Name.getCXXOverloadedOperator() == OO_Equal;
519
520 default:
521 break;
522 }
523
524 return false;
525}
526
527/// \brief If there are any implicit member functions with the given name
528/// that need to be declared in the given declaration context, do so.
529static void DeclareImplicitMemberFunctionsWithName(Sema &S,
530 DeclarationName Name,
531 const DeclContext *DC) {
532 if (!DC)
533 return;
534
535 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000536 case DeclarationName::CXXConstructorName:
537 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000538 if (Record->getDefinition() &&
539 CanDeclareSpecialMemberFunction(S.Context, Record)) {
540 if (!Record->hasDeclaredDefaultConstructor())
541 S.DeclareImplicitDefaultConstructor(
542 const_cast<CXXRecordDecl *>(Record));
543 if (!Record->hasDeclaredCopyConstructor())
544 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
545 }
Douglas Gregor22584312010-07-02 23:41:54 +0000546 break;
547
Douglas Gregora376d102010-07-02 21:50:04 +0000548 case DeclarationName::CXXDestructorName:
549 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
550 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
551 CanDeclareSpecialMemberFunction(S.Context, Record))
552 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000553 break;
554
555 case DeclarationName::CXXOperatorName:
556 if (Name.getCXXOverloadedOperator() != OO_Equal)
557 break;
558
559 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
560 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
561 CanDeclareSpecialMemberFunction(S.Context, Record))
562 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
563 break;
564
565 default:
566 break;
567 }
568}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000569
John McCallf36e02d2009-10-09 21:13:30 +0000570// Adds all qualifying matches for a name within a decl context to the
571// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000572static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000573 bool Found = false;
574
Douglas Gregor4923aa22010-07-02 20:37:36 +0000575 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000576 if (S.getLangOptions().CPlusPlus)
577 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000578
579 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000580 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000581 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000582 NamedDecl *D = *I;
583 if (R.isAcceptableDecl(D)) {
584 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000585 Found = true;
586 }
587 }
John McCallf36e02d2009-10-09 21:13:30 +0000588
Douglas Gregor85910982010-02-12 05:48:04 +0000589 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
590 return true;
591
Douglas Gregor48026d22010-01-11 18:40:55 +0000592 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000593 != DeclarationName::CXXConversionFunctionName ||
594 R.getLookupName().getCXXNameType()->isDependentType() ||
595 !isa<CXXRecordDecl>(DC))
596 return Found;
597
598 // C++ [temp.mem]p6:
599 // A specialization of a conversion function template is not found by
600 // name lookup. Instead, any conversion function templates visible in the
601 // context of the use are considered. [...]
602 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
603 if (!Record->isDefinition())
604 return Found;
605
606 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
607 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
608 UEnd = Unresolved->end(); U != UEnd; ++U) {
609 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
610 if (!ConvTemplate)
611 continue;
612
613 // When we're performing lookup for the purposes of redeclaration, just
614 // add the conversion function template. When we deduce template
615 // arguments for specializations, we'll end up unifying the return
616 // type of the new declaration with the type of the function template.
617 if (R.isForRedeclaration()) {
618 R.addDecl(ConvTemplate);
619 Found = true;
620 continue;
621 }
622
Douglas Gregor48026d22010-01-11 18:40:55 +0000623 // C++ [temp.mem]p6:
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000624 // [...] For each such operator, if argument deduction succeeds
625 // (14.9.2.3), the resulting specialization is used as if found by
626 // name lookup.
627 //
628 // When referencing a conversion function for any purpose other than
629 // a redeclaration (such that we'll be building an expression with the
630 // result), perform template argument deduction and place the
631 // specialization into the result set. We do this to avoid forcing all
632 // callers to perform special deduction for conversion functions.
John McCall5769d612010-02-08 23:07:23 +0000633 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000634 FunctionDecl *Specialization = 0;
635
636 const FunctionProtoType *ConvProto
637 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
638 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000639
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000640 // Compute the type of the function that we would expect the conversion
641 // function to have, if it were to match the name given.
642 // FIXME: Calling convention!
Rafael Espindola264ba482010-03-30 20:24:48 +0000643 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000644 QualType ExpectedType
645 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
646 0, 0, ConvProto->isVariadic(),
647 ConvProto->getTypeQuals(),
648 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000649 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000650
651 // Perform template argument deduction against the type that we would
652 // expect the function to have.
653 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
654 Specialization, Info)
655 == Sema::TDK_Success) {
656 R.addDecl(Specialization);
657 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000658 }
659 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000660
John McCallf36e02d2009-10-09 21:13:30 +0000661 return Found;
662}
663
John McCalld7be78a2009-11-10 07:01:13 +0000664// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000665static bool
Douglas Gregor85910982010-02-12 05:48:04 +0000666CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
667 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000668
669 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
670
John McCalld7be78a2009-11-10 07:01:13 +0000671 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000672 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000673
John McCalld7be78a2009-11-10 07:01:13 +0000674 // Perform direct name lookup into the namespaces nominated by the
675 // using directives whose common ancestor is this namespace.
676 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
677 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000678
John McCalld7be78a2009-11-10 07:01:13 +0000679 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000680 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000681 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000682
683 R.resolveKind();
684
685 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000686}
687
688static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000689 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000690 return Ctx->isFileContext();
691 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000692}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000693
Douglas Gregor711be1e2010-03-15 14:33:29 +0000694// Find the next outer declaration context from this scope. This
695// routine actually returns the semantic outer context, which may
696// differ from the lexical context (encoded directly in the Scope
697// stack) when we are parsing a member of a class template. In this
698// case, the second element of the pair will be true, to indicate that
699// name lookup should continue searching in this semantic context when
700// it leaves the current template parameter scope.
701static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
702 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
703 DeclContext *Lexical = 0;
704 for (Scope *OuterS = S->getParent(); OuterS;
705 OuterS = OuterS->getParent()) {
706 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000707 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000708 break;
709 }
710 }
711
712 // C++ [temp.local]p8:
713 // In the definition of a member of a class template that appears
714 // outside of the namespace containing the class template
715 // definition, the name of a template-parameter hides the name of
716 // a member of this namespace.
717 //
718 // Example:
719 //
720 // namespace N {
721 // class C { };
722 //
723 // template<class T> class B {
724 // void f(T);
725 // };
726 // }
727 //
728 // template<class C> void N::B<C>::f(C) {
729 // C b; // C is the template parameter, not N::C
730 // }
731 //
732 // In this example, the lexical context we return is the
733 // TranslationUnit, while the semantic context is the namespace N.
734 if (!Lexical || !DC || !S->getParent() ||
735 !S->getParent()->isTemplateParamScope())
736 return std::make_pair(Lexical, false);
737
738 // Find the outermost template parameter scope.
739 // For the example, this is the scope for the template parameters of
740 // template<class C>.
741 Scope *OutermostTemplateScope = S->getParent();
742 while (OutermostTemplateScope->getParent() &&
743 OutermostTemplateScope->getParent()->isTemplateParamScope())
744 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregore942bbe2009-09-10 16:57:35 +0000745
Douglas Gregor711be1e2010-03-15 14:33:29 +0000746 // Find the namespace context in which the original scope occurs. In
747 // the example, this is namespace N.
748 DeclContext *Semantic = DC;
749 while (!Semantic->isFileContext())
750 Semantic = Semantic->getParent();
751
752 // Find the declaration context just outside of the template
753 // parameter scope. This is the context in which the template is
754 // being lexically declaration (a namespace context). In the
755 // example, this is the global scope.
756 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
757 Lexical->Encloses(Semantic))
758 return std::make_pair(Semantic, true);
759
760 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000761}
762
John McCalla24dc2e2009-11-17 02:14:36 +0000763bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000764 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000765
766 DeclarationName Name = R.getLookupName();
767
Douglas Gregora376d102010-07-02 21:50:04 +0000768 // If this is the name of an implicitly-declared special member function,
769 // go through the scope stack to implicitly declare
770 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
771 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
772 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
773 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
774 }
775
776 // Implicitly declare member functions with the name we're looking for, if in
777 // fact we are in a scope where it matters.
778
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000779 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000780 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000781 I = IdResolver.begin(Name),
782 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000783
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000784 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000785 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000786 // ...During unqualified name lookup (3.4.1), the names appear as if
787 // they were declared in the nearest enclosing namespace which contains
788 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000789 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000790 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000791 //
792 // For example:
793 // namespace A { int i; }
794 // void foo() {
795 // int i;
796 // {
797 // using namespace A;
798 // ++i; // finds local 'i', A::i appears at global scope
799 // }
800 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000801 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000802 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000803 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000804 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
805
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000806 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000807 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000808 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000809 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000810 Found = true;
811 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000812 }
813 }
John McCallf36e02d2009-10-09 21:13:30 +0000814 if (Found) {
815 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000816 if (S->isClassScope())
817 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
818 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000819 return true;
820 }
821
Douglas Gregor711be1e2010-03-15 14:33:29 +0000822 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
823 S->getParent() && !S->getParent()->isTemplateParamScope()) {
824 // We've just searched the last template parameter scope and
825 // found nothing, so look into the the contexts between the
826 // lexical and semantic declaration contexts returned by
827 // findOuterContext(). This implements the name lookup behavior
828 // of C++ [temp.local]p8.
829 Ctx = OutsideOfTemplateParamDC;
830 OutsideOfTemplateParamDC = 0;
831 }
832
833 if (Ctx) {
834 DeclContext *OuterCtx;
835 bool SearchAfterTemplateScope;
836 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
837 if (SearchAfterTemplateScope)
838 OutsideOfTemplateParamDC = OuterCtx;
839
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000840 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000841 // We do not directly look into transparent contexts, since
842 // those entities will be found in the nearest enclosing
843 // non-transparent context.
844 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000845 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000846
847 // We do not look directly into function or method contexts,
848 // since all of the local variables and parameters of the
849 // function/method are present within the Scope.
850 if (Ctx->isFunctionOrMethod()) {
851 // If we have an Objective-C instance method, look for ivars
852 // in the corresponding interface.
853 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
854 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
855 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
856 ObjCInterfaceDecl *ClassDeclared;
857 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
858 Name.getAsIdentifierInfo(),
859 ClassDeclared)) {
860 if (R.isAcceptableDecl(Ivar)) {
861 R.addDecl(Ivar);
862 R.resolveKind();
863 return true;
864 }
865 }
866 }
867 }
868
869 continue;
870 }
871
Douglas Gregore942bbe2009-09-10 16:57:35 +0000872 // Perform qualified name lookup into this context.
873 // FIXME: In some cases, we know that every name that could be found by
874 // this qualified name lookup will also be on the identifier chain. For
875 // example, inside a class without any base classes, we never need to
876 // perform qualified lookup because all of the members are on top of the
877 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000878 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000879 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000880 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000881 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000882 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000883
John McCalld7be78a2009-11-10 07:01:13 +0000884 // Stop if we ran out of scopes.
885 // FIXME: This really, really shouldn't be happening.
886 if (!S) return false;
887
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000888 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000889 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000890 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000891 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
892 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000893
John McCalld7be78a2009-11-10 07:01:13 +0000894 UnqualUsingDirectiveSet UDirs;
895 UDirs.visitScopeChain(Initial, S);
896 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000897
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000898 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000899 // Unqualified name lookup in C++ requires looking into scopes
900 // that aren't strictly lexical, and therefore we walk through the
901 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000902
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000903 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000904 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000905 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000906 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000907 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000908 // We found something. Look for anything else in our scope
909 // with this same name and in an acceptable identifier
910 // namespace, so that we can construct an overload set if we
911 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000912 Found = true;
913 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000914 }
915 }
916
Douglas Gregor00b4b032010-05-14 04:53:42 +0000917 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000918 R.resolveKind();
919 return true;
920 }
921
Douglas Gregor00b4b032010-05-14 04:53:42 +0000922 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
923 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
924 S->getParent() && !S->getParent()->isTemplateParamScope()) {
925 // We've just searched the last template parameter scope and
926 // found nothing, so look into the the contexts between the
927 // lexical and semantic declaration contexts returned by
928 // findOuterContext(). This implements the name lookup behavior
929 // of C++ [temp.local]p8.
930 Ctx = OutsideOfTemplateParamDC;
931 OutsideOfTemplateParamDC = 0;
932 }
933
934 if (Ctx) {
935 DeclContext *OuterCtx;
936 bool SearchAfterTemplateScope;
937 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
938 if (SearchAfterTemplateScope)
939 OutsideOfTemplateParamDC = OuterCtx;
940
941 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
942 // We do not directly look into transparent contexts, since
943 // those entities will be found in the nearest enclosing
944 // non-transparent context.
945 if (Ctx->isTransparentContext())
946 continue;
947
948 // If we have a context, and it's not a context stashed in the
949 // template parameter scope for an out-of-line definition, also
950 // look into that context.
951 if (!(Found && S && S->isTemplateParamScope())) {
952 assert(Ctx->isFileContext() &&
953 "We should have been looking only at file context here already.");
954
955 // Look into context considering using-directives.
956 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
957 Found = true;
958 }
959
960 if (Found) {
961 R.resolveKind();
962 return true;
963 }
964
965 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
966 return false;
967 }
968 }
969
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000970 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000971 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000972 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000973
John McCallf36e02d2009-10-09 21:13:30 +0000974 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000975}
976
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000977/// @brief Perform unqualified name lookup starting from a given
978/// scope.
979///
980/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
981/// used to find names within the current scope. For example, 'x' in
982/// @code
983/// int x;
984/// int f() {
985/// return x; // unqualified name look finds 'x' in the global scope
986/// }
987/// @endcode
988///
989/// Different lookup criteria can find different names. For example, a
990/// particular scope can have both a struct and a function of the same
991/// name, and each can be found by certain lookup criteria. For more
992/// information about lookup criteria, see the documentation for the
993/// class LookupCriteria.
994///
995/// @param S The scope from which unqualified name lookup will
996/// begin. If the lookup criteria permits, name lookup may also search
997/// in the parent scopes.
998///
999/// @param Name The name of the entity that we are searching for.
1000///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001001/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001002/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001003/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001004///
1005/// @returns The result of name lookup, which includes zero or more
1006/// declarations and possibly additional information used to diagnose
1007/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001008bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1009 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001010 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001011
John McCalla24dc2e2009-11-17 02:14:36 +00001012 LookupNameKind NameKind = R.getLookupKind();
1013
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001014 if (!getLangOptions().CPlusPlus) {
1015 // Unqualified name lookup in C/Objective-C is purely lexical, so
1016 // search in the declarations attached to the name.
1017
John McCall1d7c5282009-12-18 10:40:03 +00001018 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001019 // Find the nearest non-transparent declaration scope.
1020 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001021 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001022 static_cast<DeclContext *>(S->getEntity())
1023 ->isTransparentContext()))
1024 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001025 }
1026
John McCall1d7c5282009-12-18 10:40:03 +00001027 unsigned IDNS = R.getIdentifierNamespace();
1028
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001029 // Scan up the scope chain looking for a decl that matches this
1030 // identifier that is in the appropriate namespace. This search
1031 // should not take long, as shadowing of names is uncommon, and
1032 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001033 bool LeftStartingScope = false;
1034
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001035 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001036 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001037 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001038 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001039 if (NameKind == LookupRedeclarationWithLinkage) {
1040 // Determine whether this (or a previous) declaration is
1041 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001042 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001043 LeftStartingScope = true;
1044
1045 // If we found something outside of our starting scope that
1046 // does not have linkage, skip it.
1047 if (LeftStartingScope && !((*I)->hasLinkage()))
1048 continue;
1049 }
1050
John McCallf36e02d2009-10-09 21:13:30 +00001051 R.addDecl(*I);
1052
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001053 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001054 // If this declaration has the "overloadable" attribute, we
1055 // might have a set of overloaded functions.
1056
1057 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001058 while (!(S->getFlags() & Scope::DeclScope) ||
1059 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001060 S = S->getParent();
1061
1062 // Find the last declaration in this scope (with the same
1063 // name, naturally).
1064 IdentifierResolver::iterator LastI = I;
1065 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00001066 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001067 break;
John McCallf36e02d2009-10-09 21:13:30 +00001068 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001069 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001070 }
1071
John McCallf36e02d2009-10-09 21:13:30 +00001072 R.resolveKind();
1073
1074 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001075 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001076 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001077 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001078 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001079 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001080 }
1081
1082 // If we didn't find a use of this identifier, and if the identifier
1083 // corresponds to a compiler builtin, create the decl object for the builtin
1084 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +00001085 if (AllowBuiltinCreation)
1086 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001087
John McCallf36e02d2009-10-09 21:13:30 +00001088 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001089}
1090
John McCall6e247262009-10-10 05:48:19 +00001091/// @brief Perform qualified name lookup in the namespaces nominated by
1092/// using directives by the given context.
1093///
1094/// C++98 [namespace.qual]p2:
1095/// Given X::m (where X is a user-declared namespace), or given ::m
1096/// (where X is the global namespace), let S be the set of all
1097/// declarations of m in X and in the transitive closure of all
1098/// namespaces nominated by using-directives in X and its used
1099/// namespaces, except that using-directives are ignored in any
1100/// namespace, including X, directly containing one or more
1101/// declarations of m. No namespace is searched more than once in
1102/// the lookup of a name. If S is the empty set, the program is
1103/// ill-formed. Otherwise, if S has exactly one member, or if the
1104/// context of the reference is a using-declaration
1105/// (namespace.udecl), S is the required set of declarations of
1106/// m. Otherwise if the use of m is not one that allows a unique
1107/// declaration to be chosen from S, the program is ill-formed.
1108/// C++98 [namespace.qual]p5:
1109/// During the lookup of a qualified namespace member name, if the
1110/// lookup finds more than one declaration of the member, and if one
1111/// declaration introduces a class name or enumeration name and the
1112/// other declarations either introduce the same object, the same
1113/// enumerator or a set of functions, the non-type name hides the
1114/// class or enumeration name if and only if the declarations are
1115/// from the same namespace; otherwise (the declarations are from
1116/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001117static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001118 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001119 assert(StartDC->isFileContext() && "start context is not a file context");
1120
1121 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1122 DeclContext::udir_iterator E = StartDC->using_directives_end();
1123
1124 if (I == E) return false;
1125
1126 // We have at least added all these contexts to the queue.
1127 llvm::DenseSet<DeclContext*> Visited;
1128 Visited.insert(StartDC);
1129
1130 // We have not yet looked into these namespaces, much less added
1131 // their "using-children" to the queue.
1132 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1133
1134 // We have already looked into the initial namespace; seed the queue
1135 // with its using-children.
1136 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001137 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001138 if (Visited.insert(ND).second)
1139 Queue.push_back(ND);
1140 }
1141
1142 // The easiest way to implement the restriction in [namespace.qual]p5
1143 // is to check whether any of the individual results found a tag
1144 // and, if so, to declare an ambiguity if the final result is not
1145 // a tag.
1146 bool FoundTag = false;
1147 bool FoundNonTag = false;
1148
John McCall7d384dd2009-11-18 07:57:50 +00001149 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001150
1151 bool Found = false;
1152 while (!Queue.empty()) {
1153 NamespaceDecl *ND = Queue.back();
1154 Queue.pop_back();
1155
1156 // We go through some convolutions here to avoid copying results
1157 // between LookupResults.
1158 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001159 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001160 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001161
1162 if (FoundDirect) {
1163 // First do any local hiding.
1164 DirectR.resolveKind();
1165
1166 // If the local result is a tag, remember that.
1167 if (DirectR.isSingleTagDecl())
1168 FoundTag = true;
1169 else
1170 FoundNonTag = true;
1171
1172 // Append the local results to the total results if necessary.
1173 if (UseLocal) {
1174 R.addAllDecls(LocalR);
1175 LocalR.clear();
1176 }
1177 }
1178
1179 // If we find names in this namespace, ignore its using directives.
1180 if (FoundDirect) {
1181 Found = true;
1182 continue;
1183 }
1184
1185 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1186 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1187 if (Visited.insert(Nom).second)
1188 Queue.push_back(Nom);
1189 }
1190 }
1191
1192 if (Found) {
1193 if (FoundTag && FoundNonTag)
1194 R.setAmbiguousQualifiedTagHiding();
1195 else
1196 R.resolveKind();
1197 }
1198
1199 return Found;
1200}
1201
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001202/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001203///
1204/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1205/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001206/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001207///
1208/// Different lookup criteria can find different names. For example, a
1209/// particular scope can have both a struct and a function of the same
1210/// name, and each can be found by certain lookup criteria. For more
1211/// information about lookup criteria, see the documentation for the
1212/// class LookupCriteria.
1213///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001214/// \param R captures both the lookup criteria and any lookup results found.
1215///
1216/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001217/// search. If the lookup criteria permits, name lookup may also search
1218/// in the parent contexts or (for C++ classes) base classes.
1219///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001220/// \param InUnqualifiedLookup true if this is qualified name lookup that
1221/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001222///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001223/// \returns true if lookup succeeded, false if it failed.
1224bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1225 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001226 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001227
John McCalla24dc2e2009-11-17 02:14:36 +00001228 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001229 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001231 // Make sure that the declaration context is complete.
1232 assert((!isa<TagDecl>(LookupCtx) ||
1233 LookupCtx->isDependentContext() ||
1234 cast<TagDecl>(LookupCtx)->isDefinition() ||
1235 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1236 ->isBeingDefined()) &&
1237 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001239 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001240 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001241 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001242 if (isa<CXXRecordDecl>(LookupCtx))
1243 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001244 return true;
1245 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001246
John McCall6e247262009-10-10 05:48:19 +00001247 // Don't descend into implied contexts for redeclarations.
1248 // C++98 [namespace.qual]p6:
1249 // In a declaration for a namespace member in which the
1250 // declarator-id is a qualified-id, given that the qualified-id
1251 // for the namespace member has the form
1252 // nested-name-specifier unqualified-id
1253 // the unqualified-id shall name a member of the namespace
1254 // designated by the nested-name-specifier.
1255 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001256 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001257 return false;
1258
John McCalla24dc2e2009-11-17 02:14:36 +00001259 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001260 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001261 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001262
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001263 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001264 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001265 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001266 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001267 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001268
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001269 // If we're performing qualified name lookup into a dependent class,
1270 // then we are actually looking into a current instantiation. If we have any
1271 // dependent base classes, then we either have to delay lookup until
1272 // template instantiation time (at which point all bases will be available)
1273 // or we have to fail.
1274 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1275 LookupRec->hasAnyDependentBases()) {
1276 R.setNotFoundInCurrentInstantiation();
1277 return false;
1278 }
1279
Douglas Gregor7176fff2009-01-15 00:26:24 +00001280 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001281 CXXBasePaths Paths;
1282 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001283
1284 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001285 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001286 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001287 case LookupOrdinaryName:
1288 case LookupMemberName:
1289 case LookupRedeclarationWithLinkage:
1290 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1291 break;
1292
1293 case LookupTagName:
1294 BaseCallback = &CXXRecordDecl::FindTagMember;
1295 break;
John McCall9f54ad42009-12-10 09:41:52 +00001296
1297 case LookupUsingDeclName:
1298 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001299
1300 case LookupOperatorName:
1301 case LookupNamespaceName:
1302 case LookupObjCProtocolName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001303 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001304 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001305
1306 case LookupNestedNameSpecifierName:
1307 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1308 break;
1309 }
1310
John McCalla24dc2e2009-11-17 02:14:36 +00001311 if (!LookupRec->lookupInBases(BaseCallback,
1312 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001313 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001314
John McCall92f88312010-01-23 00:46:32 +00001315 R.setNamingClass(LookupRec);
1316
Douglas Gregor7176fff2009-01-15 00:26:24 +00001317 // C++ [class.member.lookup]p2:
1318 // [...] If the resulting set of declarations are not all from
1319 // sub-objects of the same type, or the set has a nonstatic member
1320 // and includes members from distinct sub-objects, there is an
1321 // ambiguity and the program is ill-formed. Otherwise that set is
1322 // the result of the lookup.
1323 // FIXME: support using declarations!
1324 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001325 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001326 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001327 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001328 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001329 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001330
John McCall46460a62010-01-20 21:53:11 +00001331 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1332 // across all paths.
1333 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1334
Douglas Gregor7176fff2009-01-15 00:26:24 +00001335 // Determine whether we're looking at a distinct sub-object or not.
1336 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001337 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001338 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1339 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00001340 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001341 != Context.getCanonicalType(PathElement.Base->getType())) {
1342 // We found members of the given name in two subobjects of
1343 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001344 R.setAmbiguousBaseSubobjectTypes(Paths);
1345 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001346 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1347 // We have a different subobject of the same type.
1348
1349 // C++ [class.member.lookup]p5:
1350 // A static member, a nested type or an enumerator defined in
1351 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001352 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001353 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001354 if (isa<VarDecl>(FirstDecl) ||
1355 isa<TypeDecl>(FirstDecl) ||
1356 isa<EnumConstantDecl>(FirstDecl))
1357 continue;
1358
1359 if (isa<CXXMethodDecl>(FirstDecl)) {
1360 // Determine whether all of the methods are static.
1361 bool AllMethodsAreStatic = true;
1362 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1363 Func != Path->Decls.second; ++Func) {
1364 if (!isa<CXXMethodDecl>(*Func)) {
1365 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1366 break;
1367 }
1368
1369 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1370 AllMethodsAreStatic = false;
1371 break;
1372 }
1373 }
1374
1375 if (AllMethodsAreStatic)
1376 continue;
1377 }
1378
1379 // We have found a nonstatic member name in multiple, distinct
1380 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001381 R.setAmbiguousBaseSubobjects(Paths);
1382 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001383 }
1384 }
1385
1386 // Lookup in a base class succeeded; return these results.
1387
John McCallf36e02d2009-10-09 21:13:30 +00001388 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001389 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1390 NamedDecl *D = *I;
1391 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1392 D->getAccess());
1393 R.addDecl(D, AS);
1394 }
John McCallf36e02d2009-10-09 21:13:30 +00001395 R.resolveKind();
1396 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001397}
1398
1399/// @brief Performs name lookup for a name that was parsed in the
1400/// source code, and may contain a C++ scope specifier.
1401///
1402/// This routine is a convenience routine meant to be called from
1403/// contexts that receive a name and an optional C++ scope specifier
1404/// (e.g., "N::M::x"). It will then perform either qualified or
1405/// unqualified name lookup (with LookupQualifiedName or LookupName,
1406/// respectively) on the given name and return those results.
1407///
1408/// @param S The scope from which unqualified name lookup will
1409/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001410///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001411/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001412///
1413/// @param Name The name of the entity that name lookup will
1414/// search for.
1415///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001416/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001417/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001418/// C library functions (like "malloc") are implicitly declared.
1419///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001420/// @param EnteringContext Indicates whether we are going to enter the
1421/// context of the scope-specifier SS (if present).
1422///
John McCallf36e02d2009-10-09 21:13:30 +00001423/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001424bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001425 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001426 if (SS && SS->isInvalid()) {
1427 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001428 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001429 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001430 }
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Douglas Gregor495c35d2009-08-25 22:51:20 +00001432 if (SS && SS->isSet()) {
1433 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001434 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001435 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001436 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001437 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001438
John McCalla24dc2e2009-11-17 02:14:36 +00001439 R.setContextRange(SS->getRange());
1440
1441 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001442 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001443
Douglas Gregor495c35d2009-08-25 22:51:20 +00001444 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001445 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001446 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001447 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001448 }
1449
Mike Stump1eb44332009-09-09 15:08:12 +00001450 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001451 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001452}
1453
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001454
Douglas Gregor7176fff2009-01-15 00:26:24 +00001455/// @brief Produce a diagnostic describing the ambiguity that resulted
1456/// from name lookup.
1457///
1458/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001459///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001460/// @param Name The name of the entity that name lookup was
1461/// searching for.
1462///
1463/// @param NameLoc The location of the name within the source code.
1464///
1465/// @param LookupRange A source range that provides more
1466/// source-location information concerning the lookup itself. For
1467/// example, this range might highlight a nested-name-specifier that
1468/// precedes the name.
1469///
1470/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001471bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001472 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1473
John McCalla24dc2e2009-11-17 02:14:36 +00001474 DeclarationName Name = Result.getLookupName();
1475 SourceLocation NameLoc = Result.getNameLoc();
1476 SourceRange LookupRange = Result.getContextRange();
1477
John McCall6e247262009-10-10 05:48:19 +00001478 switch (Result.getAmbiguityKind()) {
1479 case LookupResult::AmbiguousBaseSubobjects: {
1480 CXXBasePaths *Paths = Result.getBasePaths();
1481 QualType SubobjectType = Paths->front().back().Base->getType();
1482 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1483 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1484 << LookupRange;
1485
1486 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1487 while (isa<CXXMethodDecl>(*Found) &&
1488 cast<CXXMethodDecl>(*Found)->isStatic())
1489 ++Found;
1490
1491 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1492
1493 return true;
1494 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001495
John McCall6e247262009-10-10 05:48:19 +00001496 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001497 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1498 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001499
1500 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001501 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001502 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1503 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001504 Path != PathEnd; ++Path) {
1505 Decl *D = *Path->Decls.first;
1506 if (DeclsPrinted.insert(D).second)
1507 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1508 }
1509
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001510 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001511 }
1512
John McCall6e247262009-10-10 05:48:19 +00001513 case LookupResult::AmbiguousTagHiding: {
1514 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001515
John McCall6e247262009-10-10 05:48:19 +00001516 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1517
1518 LookupResult::iterator DI, DE = Result.end();
1519 for (DI = Result.begin(); DI != DE; ++DI)
1520 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1521 TagDecls.insert(TD);
1522 Diag(TD->getLocation(), diag::note_hidden_tag);
1523 }
1524
1525 for (DI = Result.begin(); DI != DE; ++DI)
1526 if (!isa<TagDecl>(*DI))
1527 Diag((*DI)->getLocation(), diag::note_hiding_object);
1528
1529 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001530 LookupResult::Filter F = Result.makeFilter();
1531 while (F.hasNext()) {
1532 if (TagDecls.count(F.next()))
1533 F.erase();
1534 }
1535 F.done();
John McCall6e247262009-10-10 05:48:19 +00001536
1537 return true;
1538 }
1539
1540 case LookupResult::AmbiguousReference: {
1541 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001542
John McCall6e247262009-10-10 05:48:19 +00001543 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1544 for (; DI != DE; ++DI)
1545 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001546
John McCall6e247262009-10-10 05:48:19 +00001547 return true;
1548 }
1549 }
1550
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001551 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001552 return true;
1553}
Douglas Gregorfa047642009-02-04 00:32:51 +00001554
John McCallc7e04da2010-05-28 18:45:08 +00001555namespace {
1556 struct AssociatedLookup {
1557 AssociatedLookup(Sema &S,
1558 Sema::AssociatedNamespaceSet &Namespaces,
1559 Sema::AssociatedClassSet &Classes)
1560 : S(S), Namespaces(Namespaces), Classes(Classes) {
1561 }
1562
1563 Sema &S;
1564 Sema::AssociatedNamespaceSet &Namespaces;
1565 Sema::AssociatedClassSet &Classes;
1566 };
1567}
1568
Mike Stump1eb44332009-09-09 15:08:12 +00001569static void
John McCallc7e04da2010-05-28 18:45:08 +00001570addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001571
Douglas Gregor54022952010-04-30 07:08:38 +00001572static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1573 DeclContext *Ctx) {
1574 // Add the associated namespace for this class.
1575
1576 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1577 // be a locally scoped record.
1578
1579 while (Ctx->isRecord() || Ctx->isTransparentContext())
1580 Ctx = Ctx->getParent();
1581
John McCall6ff07852009-08-07 22:18:02 +00001582 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001583 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001584}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001585
Mike Stump1eb44332009-09-09 15:08:12 +00001586// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001587// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001588static void
John McCallc7e04da2010-05-28 18:45:08 +00001589addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1590 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001591 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001592 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001593 switch (Arg.getKind()) {
1594 case TemplateArgument::Null:
1595 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Douglas Gregor69be8d62009-07-08 07:51:57 +00001597 case TemplateArgument::Type:
1598 // [...] the namespaces and classes associated with the types of the
1599 // template arguments provided for template type parameters (excluding
1600 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001601 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001602 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Douglas Gregor788cd062009-11-11 01:00:40 +00001604 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001605 // [...] the namespaces in which any template template arguments are
1606 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001607 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001608 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001609 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001610 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001611 DeclContext *Ctx = ClassTemplate->getDeclContext();
1612 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001613 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001614 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001615 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001616 }
1617 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001618 }
1619
1620 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001621 case TemplateArgument::Integral:
1622 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001623 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001624 // associated namespaces. ]
1625 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Douglas Gregor69be8d62009-07-08 07:51:57 +00001627 case TemplateArgument::Pack:
1628 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1629 PEnd = Arg.pack_end();
1630 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001631 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001632 break;
1633 }
1634}
1635
Douglas Gregorfa047642009-02-04 00:32:51 +00001636// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001637// argument-dependent lookup with an argument of class type
1638// (C++ [basic.lookup.koenig]p2).
1639static void
John McCallc7e04da2010-05-28 18:45:08 +00001640addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1641 CXXRecordDecl *Class) {
1642
1643 // Just silently ignore anything whose name is __va_list_tag.
1644 if (Class->getDeclName() == Result.S.VAListTagName)
1645 return;
1646
Douglas Gregorfa047642009-02-04 00:32:51 +00001647 // C++ [basic.lookup.koenig]p2:
1648 // [...]
1649 // -- If T is a class type (including unions), its associated
1650 // classes are: the class itself; the class of which it is a
1651 // member, if any; and its direct and indirect base
1652 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001653 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001654
1655 // Add the class of which it is a member, if any.
1656 DeclContext *Ctx = Class->getDeclContext();
1657 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001658 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +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 Gregorfa047642009-02-04 00:32:51 +00001662 // Add the class itself. If we've already seen this class, we don't
1663 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001664 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001665 return;
1666
Mike Stump1eb44332009-09-09 15:08:12 +00001667 // -- If T is a template-id, its associated namespaces and classes are
1668 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001669 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001670 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001671 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001672 // namespaces in which any template template arguments are defined; and
1673 // the classes in which any member templates used as template template
1674 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001675 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001676 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001677 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1678 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1679 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001680 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001681 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001682 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Douglas Gregor69be8d62009-07-08 07:51:57 +00001684 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1685 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001686 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688
John McCall86ff3082010-02-04 22:26:26 +00001689 // Only recurse into base classes for complete types.
1690 if (!Class->hasDefinition()) {
1691 // FIXME: we might need to instantiate templates here
1692 return;
1693 }
1694
Douglas Gregorfa047642009-02-04 00:32:51 +00001695 // Add direct and indirect base classes along with their associated
1696 // namespaces.
1697 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1698 Bases.push_back(Class);
1699 while (!Bases.empty()) {
1700 // Pop this class off the stack.
1701 Class = Bases.back();
1702 Bases.pop_back();
1703
1704 // Visit the base classes.
1705 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1706 BaseEnd = Class->bases_end();
1707 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001708 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001709 // In dependent contexts, we do ADL twice, and the first time around,
1710 // the base type might be a dependent TemplateSpecializationType, or a
1711 // TemplateTypeParmType. If that happens, simply ignore it.
1712 // FIXME: If we want to support export, we probably need to add the
1713 // namespace of the template in a TemplateSpecializationType, or even
1714 // the classes and namespaces of known non-dependent arguments.
1715 if (!BaseType)
1716 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001717 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001718 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001719 // Find the associated namespace for this base class.
1720 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001721 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001722
1723 // Make sure we visit the bases of this base class.
1724 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1725 Bases.push_back(BaseDecl);
1726 }
1727 }
1728 }
1729}
1730
1731// \brief Add the associated classes and namespaces for
1732// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001733// (C++ [basic.lookup.koenig]p2).
1734static void
John McCallc7e04da2010-05-28 18:45:08 +00001735addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001736 // C++ [basic.lookup.koenig]p2:
1737 //
1738 // For each argument type T in the function call, there is a set
1739 // of zero or more associated namespaces and a set of zero or more
1740 // associated classes to be considered. The sets of namespaces and
1741 // classes is determined entirely by the types of the function
1742 // arguments (and the namespace of any template template
1743 // argument). Typedef names and using-declarations used to specify
1744 // the types do not contribute to this set. The sets of namespaces
1745 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001746
John McCallfa4edcf2010-05-28 06:08:54 +00001747 llvm::SmallVector<const Type *, 16> Queue;
1748 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1749
Douglas Gregorfa047642009-02-04 00:32:51 +00001750 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001751 switch (T->getTypeClass()) {
1752
1753#define TYPE(Class, Base)
1754#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1755#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1756#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1757#define ABSTRACT_TYPE(Class, Base)
1758#include "clang/AST/TypeNodes.def"
1759 // T is canonical. We can also ignore dependent types because
1760 // we don't need to do ADL at the definition point, but if we
1761 // wanted to implement template export (or if we find some other
1762 // use for associated classes and namespaces...) this would be
1763 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001764 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001765
John McCallfa4edcf2010-05-28 06:08:54 +00001766 // -- If T is a pointer to U or an array of U, its associated
1767 // namespaces and classes are those associated with U.
1768 case Type::Pointer:
1769 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1770 continue;
1771 case Type::ConstantArray:
1772 case Type::IncompleteArray:
1773 case Type::VariableArray:
1774 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1775 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001776
John McCallfa4edcf2010-05-28 06:08:54 +00001777 // -- If T is a fundamental type, its associated sets of
1778 // namespaces and classes are both empty.
1779 case Type::Builtin:
1780 break;
1781
1782 // -- If T is a class type (including unions), its associated
1783 // classes are: the class itself; the class of which it is a
1784 // member, if any; and its direct and indirect base
1785 // classes. Its associated namespaces are the namespaces in
1786 // which its associated classes are defined.
1787 case Type::Record: {
1788 CXXRecordDecl *Class
1789 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001790 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001791 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001792 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001793
John McCallfa4edcf2010-05-28 06:08:54 +00001794 // -- If T is an enumeration type, its associated namespace is
1795 // the namespace in which it is defined. If it is class
1796 // member, its associated class is the member’s class; else
1797 // it has no associated class.
1798 case Type::Enum: {
1799 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001800
John McCallfa4edcf2010-05-28 06:08:54 +00001801 DeclContext *Ctx = Enum->getDeclContext();
1802 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001803 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001804
John McCallfa4edcf2010-05-28 06:08:54 +00001805 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001806 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001807
John McCallfa4edcf2010-05-28 06:08:54 +00001808 break;
1809 }
1810
1811 // -- If T is a function type, its associated namespaces and
1812 // classes are those associated with the function parameter
1813 // types and those associated with the return type.
1814 case Type::FunctionProto: {
1815 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1816 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1817 ArgEnd = Proto->arg_type_end();
1818 Arg != ArgEnd; ++Arg)
1819 Queue.push_back(Arg->getTypePtr());
1820 // fallthrough
1821 }
1822 case Type::FunctionNoProto: {
1823 const FunctionType *FnType = cast<FunctionType>(T);
1824 T = FnType->getResultType().getTypePtr();
1825 continue;
1826 }
1827
1828 // -- If T is a pointer to a member function of a class X, its
1829 // associated namespaces and classes are those associated
1830 // with the function parameter types and return type,
1831 // together with those associated with X.
1832 //
1833 // -- If T is a pointer to a data member of class X, its
1834 // associated namespaces and classes are those associated
1835 // with the member type together with those associated with
1836 // X.
1837 case Type::MemberPointer: {
1838 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1839
1840 // Queue up the class type into which this points.
1841 Queue.push_back(MemberPtr->getClass());
1842
1843 // And directly continue with the pointee type.
1844 T = MemberPtr->getPointeeType().getTypePtr();
1845 continue;
1846 }
1847
1848 // As an extension, treat this like a normal pointer.
1849 case Type::BlockPointer:
1850 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1851 continue;
1852
1853 // References aren't covered by the standard, but that's such an
1854 // obvious defect that we cover them anyway.
1855 case Type::LValueReference:
1856 case Type::RValueReference:
1857 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1858 continue;
1859
1860 // These are fundamental types.
1861 case Type::Vector:
1862 case Type::ExtVector:
1863 case Type::Complex:
1864 break;
1865
1866 // These are ignored by ADL.
1867 case Type::ObjCObject:
1868 case Type::ObjCInterface:
1869 case Type::ObjCObjectPointer:
1870 break;
1871 }
1872
1873 if (Queue.empty()) break;
1874 T = Queue.back();
1875 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001876 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001877}
1878
1879/// \brief Find the associated classes and namespaces for
1880/// argument-dependent lookup for a call with the given set of
1881/// arguments.
1882///
1883/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001884/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001885/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001886void
Douglas Gregorfa047642009-02-04 00:32:51 +00001887Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1888 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001889 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001890 AssociatedNamespaces.clear();
1891 AssociatedClasses.clear();
1892
John McCallc7e04da2010-05-28 18:45:08 +00001893 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1894
Douglas Gregorfa047642009-02-04 00:32:51 +00001895 // C++ [basic.lookup.koenig]p2:
1896 // For each argument type T in the function call, there is a set
1897 // of zero or more associated namespaces and a set of zero or more
1898 // associated classes to be considered. The sets of namespaces and
1899 // classes is determined entirely by the types of the function
1900 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001901 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001902 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1903 Expr *Arg = Args[ArgIdx];
1904
1905 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00001906 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001907 continue;
1908 }
1909
1910 // [...] In addition, if the argument is the name or address of a
1911 // set of overloaded functions and/or function templates, its
1912 // associated classes and namespaces are the union of those
1913 // associated with each of the members of the set: the namespace
1914 // in which the function or function template is defined and the
1915 // classes and namespaces associated with its (non-dependent)
1916 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001917 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001918 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1919 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1920 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001921
John McCallc7e04da2010-05-28 18:45:08 +00001922 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1923 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00001924
John McCallc7e04da2010-05-28 18:45:08 +00001925 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1926 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001927 // Look through any using declarations to find the underlying function.
1928 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001929
Chandler Carruthbd647292009-12-29 06:17:27 +00001930 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1931 if (!FDecl)
1932 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001933
1934 // Add the classes and namespaces associated with the parameter
1935 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00001936 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001937 }
1938 }
1939}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001940
1941/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1942/// an acceptable non-member overloaded operator for a call whose
1943/// arguments have types T1 (and, if non-empty, T2). This routine
1944/// implements the check in C++ [over.match.oper]p3b2 concerning
1945/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001946static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001947IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1948 QualType T1, QualType T2,
1949 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001950 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1951 return true;
1952
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001953 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1954 return true;
1955
John McCall183700f2009-09-21 23:43:11 +00001956 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001957 if (Proto->getNumArgs() < 1)
1958 return false;
1959
1960 if (T1->isEnumeralType()) {
1961 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001962 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001963 return true;
1964 }
1965
1966 if (Proto->getNumArgs() < 2)
1967 return false;
1968
1969 if (!T2.isNull() && T2->isEnumeralType()) {
1970 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001971 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001972 return true;
1973 }
1974
1975 return false;
1976}
1977
John McCall7d384dd2009-11-18 07:57:50 +00001978NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00001979 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00001980 LookupNameKind NameKind,
1981 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00001982 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00001983 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00001984 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00001985}
1986
Douglas Gregor6e378de2009-04-23 23:18:26 +00001987/// \brief Find the protocol with the given name, if any.
Douglas Gregorc83c6872010-04-15 22:33:43 +00001988ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
1989 SourceLocation IdLoc) {
1990 Decl *D = LookupSingleName(TUScope, II, IdLoc,
1991 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001992 return cast_or_null<ObjCProtocolDecl>(D);
1993}
1994
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001995void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001996 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00001997 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001998 // C++ [over.match.oper]p3:
1999 // -- The set of non-member candidates is the result of the
2000 // unqualified lookup of operator@ in the context of the
2001 // expression according to the usual rules for name lookup in
2002 // unqualified function calls (3.4.2) except that all member
2003 // functions are ignored. However, if no operand has a class
2004 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002005 // that have a first parameter of type T1 or "reference to
2006 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002007 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002008 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002009 // when T2 is an enumeration type, are candidate functions.
2010 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002011 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2012 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002014 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2015
John McCallf36e02d2009-10-09 21:13:30 +00002016 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002017 return;
2018
2019 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2020 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002021 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2022 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002023 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002024 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002025 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002026 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002027 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002028 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002029 // later?
2030 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002031 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002032 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002033 }
2034}
2035
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002036/// \brief Look up the constructors for the given class.
2037DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +00002038 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002039 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2040 if (!Class->hasDeclaredDefaultConstructor())
2041 DeclareImplicitDefaultConstructor(Class);
2042 if (!Class->hasDeclaredCopyConstructor())
2043 DeclareImplicitCopyConstructor(Class);
2044 }
Douglas Gregor22584312010-07-02 23:41:54 +00002045
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002046 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2047 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2048 return Class->lookup(Name);
2049}
2050
Douglas Gregordb89f282010-07-01 22:47:18 +00002051/// \brief Look for the destructor of the given class.
2052///
2053/// During semantic analysis, this routine should be used in lieu of
2054/// CXXRecordDecl::getDestructor().
2055///
2056/// \returns The destructor for this class.
2057CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +00002058 // If the destructor has not yet been declared, do so now.
2059 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2060 !Class->hasDeclaredDestructor())
2061 DeclareImplicitDestructor(Class);
2062
Douglas Gregordb89f282010-07-01 22:47:18 +00002063 return Class->getDestructor();
2064}
2065
John McCall7edb5fd2010-01-26 07:16:45 +00002066void ADLResult::insert(NamedDecl *New) {
2067 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2068
2069 // If we haven't yet seen a decl for this key, or the last decl
2070 // was exactly this one, we're done.
2071 if (Old == 0 || Old == New) {
2072 Old = New;
2073 return;
2074 }
2075
2076 // Otherwise, decide which is a more recent redeclaration.
2077 FunctionDecl *OldFD, *NewFD;
2078 if (isa<FunctionTemplateDecl>(New)) {
2079 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2080 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2081 } else {
2082 OldFD = cast<FunctionDecl>(Old);
2083 NewFD = cast<FunctionDecl>(New);
2084 }
2085
2086 FunctionDecl *Cursor = NewFD;
2087 while (true) {
2088 Cursor = Cursor->getPreviousDeclaration();
2089
2090 // If we got to the end without finding OldFD, OldFD is the newer
2091 // declaration; leave things as they are.
2092 if (!Cursor) return;
2093
2094 // If we do find OldFD, then NewFD is newer.
2095 if (Cursor == OldFD) break;
2096
2097 // Otherwise, keep looking.
2098 }
2099
2100 Old = New;
2101}
2102
Sebastian Redl644be852009-10-23 19:23:15 +00002103void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002104 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00002105 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002106 // Find all of the associated namespaces and classes based on the
2107 // arguments we have.
2108 AssociatedNamespaceSet AssociatedNamespaces;
2109 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002110 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002111 AssociatedNamespaces,
2112 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002113
Sebastian Redl644be852009-10-23 19:23:15 +00002114 QualType T1, T2;
2115 if (Operator) {
2116 T1 = Args[0]->getType();
2117 if (NumArgs >= 2)
2118 T2 = Args[1]->getType();
2119 }
2120
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002121 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002122 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2123 // and let Y be the lookup set produced by argument dependent
2124 // lookup (defined as follows). If X contains [...] then Y is
2125 // empty. Otherwise Y is the set of declarations found in the
2126 // namespaces associated with the argument types as described
2127 // below. The set of declarations found by the lookup of the name
2128 // is the union of X and Y.
2129 //
2130 // Here, we compute Y and add its members to the overloaded
2131 // candidate set.
2132 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002133 NSEnd = AssociatedNamespaces.end();
2134 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002135 // When considering an associated namespace, the lookup is the
2136 // same as the lookup performed when the associated namespace is
2137 // used as a qualifier (3.4.3.2) except that:
2138 //
2139 // -- Any using-directives in the associated namespace are
2140 // ignored.
2141 //
John McCall6ff07852009-08-07 22:18:02 +00002142 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002143 // associated classes are visible within their respective
2144 // namespaces even if they are not visible during an ordinary
2145 // lookup (11.4).
2146 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002147 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002148 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002149 // If the only declaration here is an ordinary friend, consider
2150 // it only if it was declared in an associated classes.
2151 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002152 DeclContext *LexDC = D->getLexicalDeclContext();
2153 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2154 continue;
2155 }
Mike Stump1eb44332009-09-09 15:08:12 +00002156
John McCalla113e722010-01-26 06:04:06 +00002157 if (isa<UsingShadowDecl>(D))
2158 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002159
John McCalla113e722010-01-26 06:04:06 +00002160 if (isa<FunctionDecl>(D)) {
2161 if (Operator &&
2162 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2163 T1, T2, Context))
2164 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002165 } else if (!isa<FunctionTemplateDecl>(D))
2166 continue;
2167
2168 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002169 }
2170 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002171}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002172
2173//----------------------------------------------------------------------------
2174// Search for all visible declarations.
2175//----------------------------------------------------------------------------
2176VisibleDeclConsumer::~VisibleDeclConsumer() { }
2177
2178namespace {
2179
2180class ShadowContextRAII;
2181
2182class VisibleDeclsRecord {
2183public:
2184 /// \brief An entry in the shadow map, which is optimized to store a
2185 /// single declaration (the common case) but can also store a list
2186 /// of declarations.
2187 class ShadowMapEntry {
2188 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2189
2190 /// \brief Contains either the solitary NamedDecl * or a vector
2191 /// of declarations.
2192 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2193
2194 public:
2195 ShadowMapEntry() : DeclOrVector() { }
2196
2197 void Add(NamedDecl *ND);
2198 void Destroy();
2199
2200 // Iteration.
2201 typedef NamedDecl **iterator;
2202 iterator begin();
2203 iterator end();
2204 };
2205
2206private:
2207 /// \brief A mapping from declaration names to the declarations that have
2208 /// this name within a particular scope.
2209 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2210
2211 /// \brief A list of shadow maps, which is used to model name hiding.
2212 std::list<ShadowMap> ShadowMaps;
2213
2214 /// \brief The declaration contexts we have already visited.
2215 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2216
2217 friend class ShadowContextRAII;
2218
2219public:
2220 /// \brief Determine whether we have already visited this context
2221 /// (and, if not, note that we are going to visit that context now).
2222 bool visitedContext(DeclContext *Ctx) {
2223 return !VisitedContexts.insert(Ctx);
2224 }
2225
2226 /// \brief Determine whether the given declaration is hidden in the
2227 /// current scope.
2228 ///
2229 /// \returns the declaration that hides the given declaration, or
2230 /// NULL if no such declaration exists.
2231 NamedDecl *checkHidden(NamedDecl *ND);
2232
2233 /// \brief Add a declaration to the current shadow map.
2234 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2235};
2236
2237/// \brief RAII object that records when we've entered a shadow context.
2238class ShadowContextRAII {
2239 VisibleDeclsRecord &Visible;
2240
2241 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2242
2243public:
2244 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2245 Visible.ShadowMaps.push_back(ShadowMap());
2246 }
2247
2248 ~ShadowContextRAII() {
2249 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2250 EEnd = Visible.ShadowMaps.back().end();
2251 E != EEnd;
2252 ++E)
2253 E->second.Destroy();
2254
2255 Visible.ShadowMaps.pop_back();
2256 }
2257};
2258
2259} // end anonymous namespace
2260
2261void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2262 if (DeclOrVector.isNull()) {
2263 // 0 - > 1 elements: just set the single element information.
2264 DeclOrVector = ND;
2265 return;
2266 }
2267
2268 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2269 // 1 -> 2 elements: create the vector of results and push in the
2270 // existing declaration.
2271 DeclVector *Vec = new DeclVector;
2272 Vec->push_back(PrevND);
2273 DeclOrVector = Vec;
2274 }
2275
2276 // Add the new element to the end of the vector.
2277 DeclOrVector.get<DeclVector*>()->push_back(ND);
2278}
2279
2280void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2281 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2282 delete Vec;
2283 DeclOrVector = ((NamedDecl *)0);
2284 }
2285}
2286
2287VisibleDeclsRecord::ShadowMapEntry::iterator
2288VisibleDeclsRecord::ShadowMapEntry::begin() {
2289 if (DeclOrVector.isNull())
2290 return 0;
2291
2292 if (DeclOrVector.dyn_cast<NamedDecl *>())
2293 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2294
2295 return DeclOrVector.get<DeclVector *>()->begin();
2296}
2297
2298VisibleDeclsRecord::ShadowMapEntry::iterator
2299VisibleDeclsRecord::ShadowMapEntry::end() {
2300 if (DeclOrVector.isNull())
2301 return 0;
2302
2303 if (DeclOrVector.dyn_cast<NamedDecl *>())
2304 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2305
2306 return DeclOrVector.get<DeclVector *>()->end();
2307}
2308
2309NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002310 // Look through using declarations.
2311 ND = ND->getUnderlyingDecl();
2312
Douglas Gregor546be3c2009-12-30 17:04:44 +00002313 unsigned IDNS = ND->getIdentifierNamespace();
2314 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2315 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2316 SM != SMEnd; ++SM) {
2317 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2318 if (Pos == SM->end())
2319 continue;
2320
2321 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2322 IEnd = Pos->second.end();
2323 I != IEnd; ++I) {
2324 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002325 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor546be3c2009-12-30 17:04:44 +00002326 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2327 Decl::IDNS_ObjCProtocol)))
2328 continue;
2329
2330 // Protocols are in distinct namespaces from everything else.
2331 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2332 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2333 (*I)->getIdentifierNamespace() != IDNS)
2334 continue;
2335
Douglas Gregor0cc84042010-01-14 15:47:35 +00002336 // Functions and function templates in the same scope overload
2337 // rather than hide. FIXME: Look for hiding based on function
2338 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002339 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002340 ND->isFunctionOrFunctionTemplate() &&
2341 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002342 continue;
2343
Douglas Gregor546be3c2009-12-30 17:04:44 +00002344 // We've found a declaration that hides this one.
2345 return *I;
2346 }
2347 }
2348
2349 return 0;
2350}
2351
2352static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2353 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002354 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002355 VisibleDeclConsumer &Consumer,
2356 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002357 if (!Ctx)
2358 return;
2359
Douglas Gregor546be3c2009-12-30 17:04:44 +00002360 // Make sure we don't visit the same context twice.
2361 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2362 return;
2363
Douglas Gregor4923aa22010-07-02 20:37:36 +00002364 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2365 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2366
Douglas Gregor546be3c2009-12-30 17:04:44 +00002367 // Enumerate all of the results in this context.
2368 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2369 CurCtx = CurCtx->getNextContext()) {
2370 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2371 DEnd = CurCtx->decls_end();
2372 D != DEnd; ++D) {
2373 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2374 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002375 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002376 Visited.add(ND);
2377 }
2378
2379 // Visit transparent contexts inside this context.
2380 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2381 if (InnerCtx->isTransparentContext())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002382 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002383 Consumer, Visited);
2384 }
2385 }
2386 }
2387
2388 // Traverse using directives for qualified name lookup.
2389 if (QualifiedNameLookup) {
2390 ShadowContextRAII Shadow(Visited);
2391 DeclContext::udir_iterator I, E;
2392 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2393 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002394 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002395 }
2396 }
2397
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002398 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002399 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002400 if (!Record->hasDefinition())
2401 return;
2402
Douglas Gregor546be3c2009-12-30 17:04:44 +00002403 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2404 BEnd = Record->bases_end();
2405 B != BEnd; ++B) {
2406 QualType BaseType = B->getType();
2407
2408 // Don't look into dependent bases, because name lookup can't look
2409 // there anyway.
2410 if (BaseType->isDependentType())
2411 continue;
2412
2413 const RecordType *Record = BaseType->getAs<RecordType>();
2414 if (!Record)
2415 continue;
2416
2417 // FIXME: It would be nice to be able to determine whether referencing
2418 // a particular member would be ambiguous. For example, given
2419 //
2420 // struct A { int member; };
2421 // struct B { int member; };
2422 // struct C : A, B { };
2423 //
2424 // void f(C *c) { c->### }
2425 //
2426 // accessing 'member' would result in an ambiguity. However, we
2427 // could be smart enough to qualify the member with the base
2428 // class, e.g.,
2429 //
2430 // c->B::member
2431 //
2432 // or
2433 //
2434 // c->A::member
2435
2436 // Find results in this base class (and its bases).
2437 ShadowContextRAII Shadow(Visited);
2438 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002439 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002440 }
2441 }
2442
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002443 // Traverse the contexts of Objective-C classes.
2444 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2445 // Traverse categories.
2446 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2447 Category; Category = Category->getNextClassCategory()) {
2448 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002449 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2450 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002451 }
2452
2453 // Traverse protocols.
2454 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2455 E = IFace->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
2461 // Traverse the superclass.
2462 if (IFace->getSuperClass()) {
2463 ShadowContextRAII Shadow(Visited);
2464 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002465 true, Consumer, 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. We do this to find
2469 // synthesized ivars.
2470 if (IFace->getImplementation()) {
2471 ShadowContextRAII Shadow(Visited);
2472 LookupVisibleDecls(IFace->getImplementation(), Result,
2473 QualifiedNameLookup, true, Consumer, Visited);
2474 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002475 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2476 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2477 E = Protocol->protocol_end(); I != E; ++I) {
2478 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002479 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2480 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002481 }
2482 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2483 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2484 E = Category->protocol_end(); I != E; ++I) {
2485 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002486 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2487 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002488 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002489
2490 // If there is an implementation, traverse it.
2491 if (Category->getImplementation()) {
2492 ShadowContextRAII Shadow(Visited);
2493 LookupVisibleDecls(Category->getImplementation(), Result,
2494 QualifiedNameLookup, true, Consumer, Visited);
2495 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002496 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002497}
2498
2499static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2500 UnqualUsingDirectiveSet &UDirs,
2501 VisibleDeclConsumer &Consumer,
2502 VisibleDeclsRecord &Visited) {
2503 if (!S)
2504 return;
2505
Douglas Gregor539c5c32010-01-07 00:31:29 +00002506 if (!S->getEntity() || !S->getParent() ||
2507 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2508 // Walk through the declarations in this Scope.
2509 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2510 D != DEnd; ++D) {
2511 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2512 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002513 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002514 Visited.add(ND);
2515 }
2516 }
2517 }
2518
Douglas Gregor711be1e2010-03-15 14:33:29 +00002519 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002520 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002521 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002522 // Look into this scope's declaration context, along with any of its
2523 // parent lookup contexts (e.g., enclosing classes), up to the point
2524 // where we hit the context stored in the next outer scope.
2525 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002526 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor546be3c2009-12-30 17:04:44 +00002527
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002528 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002529 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002530 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2531 if (Method->isInstanceMethod()) {
2532 // For instance methods, look for ivars in the method's interface.
2533 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2534 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor62021192010-02-04 23:42:48 +00002535 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2536 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2537 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002538 }
2539
2540 // We've already performed all of the name lookup that we need
2541 // to for Objective-C methods; the next context will be the
2542 // outer scope.
2543 break;
2544 }
2545
Douglas Gregor546be3c2009-12-30 17:04:44 +00002546 if (Ctx->isFunctionOrMethod())
2547 continue;
2548
2549 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002550 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002551 }
2552 } else if (!S->getParent()) {
2553 // Look into the translation unit scope. We walk through the translation
2554 // unit's declaration context, because the Scope itself won't have all of
2555 // the declarations if we loaded a precompiled header.
2556 // FIXME: We would like the translation unit's Scope object to point to the
2557 // translation unit, so we don't need this special "if" branch. However,
2558 // doing so would force the normal C++ name-lookup code to look into the
2559 // translation unit decl when the IdentifierInfo chains would suffice.
2560 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002561 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002562 Entity = Result.getSema().Context.getTranslationUnitDecl();
2563 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002564 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002565 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002566
2567 if (Entity) {
2568 // Lookup visible declarations in any namespaces found by using
2569 // directives.
2570 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2571 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2572 for (; UI != UEnd; ++UI)
2573 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002574 Result, /*QualifiedNameLookup=*/false,
2575 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002576 }
2577
2578 // Lookup names in the parent scope.
2579 ShadowContextRAII Shadow(Visited);
2580 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2581}
2582
2583void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2584 VisibleDeclConsumer &Consumer) {
2585 // Determine the set of using directives available during
2586 // unqualified name lookup.
2587 Scope *Initial = S;
2588 UnqualUsingDirectiveSet UDirs;
2589 if (getLangOptions().CPlusPlus) {
2590 // Find the first namespace or translation-unit scope.
2591 while (S && !isNamespaceOrTranslationUnitScope(S))
2592 S = S->getParent();
2593
2594 UDirs.visitScopeChain(Initial, S);
2595 }
2596 UDirs.done();
2597
2598 // Look for visible declarations.
2599 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2600 VisibleDeclsRecord Visited;
2601 ShadowContextRAII Shadow(Visited);
2602 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2603}
2604
2605void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2606 VisibleDeclConsumer &Consumer) {
2607 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2608 VisibleDeclsRecord Visited;
2609 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002610 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2611 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002612}
2613
2614//----------------------------------------------------------------------------
2615// Typo correction
2616//----------------------------------------------------------------------------
2617
2618namespace {
2619class TypoCorrectionConsumer : public VisibleDeclConsumer {
2620 /// \brief The name written that is a typo in the source.
2621 llvm::StringRef Typo;
2622
2623 /// \brief The results found that have the smallest edit distance
2624 /// found (so far) with the typo name.
2625 llvm::SmallVector<NamedDecl *, 4> BestResults;
2626
Douglas Gregoraaf87162010-04-14 20:04:41 +00002627 /// \brief The keywords that have the smallest edit distance.
2628 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2629
Douglas Gregor546be3c2009-12-30 17:04:44 +00002630 /// \brief The best edit distance found so far.
2631 unsigned BestEditDistance;
2632
2633public:
2634 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2635 : Typo(Typo->getName()) { }
2636
Douglas Gregor0cc84042010-01-14 15:47:35 +00002637 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002638 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002639
2640 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2641 iterator begin() const { return BestResults.begin(); }
2642 iterator end() const { return BestResults.end(); }
Douglas Gregoraaf87162010-04-14 20:04:41 +00002643 void clear_decls() { BestResults.clear(); }
2644
2645 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002646
Douglas Gregoraaf87162010-04-14 20:04:41 +00002647 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2648 keyword_iterator;
2649 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2650 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2651 bool keyword_empty() const { return BestKeywords.empty(); }
2652 unsigned keyword_size() const { return BestKeywords.size(); }
2653
2654 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002655};
2656
2657}
2658
Douglas Gregor0cc84042010-01-14 15:47:35 +00002659void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2660 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002661 // Don't consider hidden names for typo correction.
2662 if (Hiding)
2663 return;
2664
2665 // Only consider entities with identifiers for names, ignoring
2666 // special names (constructors, overloaded operators, selectors,
2667 // etc.).
2668 IdentifierInfo *Name = ND->getIdentifier();
2669 if (!Name)
2670 return;
2671
2672 // Compute the edit distance between the typo and the name of this
2673 // entity. If this edit distance is not worse than the best edit
2674 // distance we've seen so far, add it to the list of results.
2675 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregoraaf87162010-04-14 20:04:41 +00002676 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002677 if (ED < BestEditDistance) {
2678 // This result is better than any we've seen before; clear out
2679 // the previous results.
2680 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002681 BestKeywords.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002682 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 BestResults.push_back(ND);
2692}
2693
Douglas Gregoraaf87162010-04-14 20:04:41 +00002694void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2695 llvm::StringRef Keyword) {
2696 // Compute the edit distance between the typo and this keyword.
2697 // If this edit distance is not worse than the best edit
2698 // distance we've seen so far, add it to the list of results.
2699 unsigned ED = Typo.edit_distance(Keyword);
2700 if (!BestResults.empty() || !BestKeywords.empty()) {
2701 if (ED < BestEditDistance) {
2702 BestResults.clear();
2703 BestKeywords.clear();
2704 BestEditDistance = ED;
2705 } else if (ED > BestEditDistance) {
2706 // This result is worse than the best results we've seen so far;
2707 // ignore it.
2708 return;
2709 }
2710 } else
2711 BestEditDistance = ED;
2712
2713 BestKeywords.push_back(&Context.Idents.get(Keyword));
2714}
2715
Douglas Gregor546be3c2009-12-30 17:04:44 +00002716/// \brief Try to "correct" a typo in the source code by finding
2717/// visible declarations whose names are similar to the name that was
2718/// present in the source code.
2719///
2720/// \param Res the \c LookupResult structure that contains the name
2721/// that was present in the source code along with the name-lookup
2722/// criteria used to search for the name. On success, this structure
2723/// will contain the results of name lookup.
2724///
2725/// \param S the scope in which name lookup occurs.
2726///
2727/// \param SS the nested-name-specifier that precedes the name we're
2728/// looking for, if present.
2729///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002730/// \param MemberContext if non-NULL, the context in which to look for
2731/// a member access expression.
2732///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002733/// \param EnteringContext whether we're entering the context described by
2734/// the nested-name-specifier SS.
2735///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002736/// \param CTC The context in which typo correction occurs, which impacts the
2737/// set of keywords permitted.
2738///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002739/// \param OPT when non-NULL, the search for visible declarations will
2740/// also walk the protocols in the qualified interfaces of \p OPT.
2741///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002742/// \returns the corrected name if the typo was corrected, otherwise returns an
2743/// empty \c DeclarationName. When a typo was corrected, the result structure
2744/// may contain the results of name lookup for the correct name or it may be
2745/// empty.
2746DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002747 DeclContext *MemberContext,
2748 bool EnteringContext,
2749 CorrectTypoContext CTC,
2750 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00002751 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002752 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002753
2754 // Provide a stop gap for files that are just seriously broken. Trying
2755 // to correct all typos can turn into a HUGE performance penalty, causing
2756 // some files to take minutes to get rejected by the parser.
2757 // FIXME: Is this the right solution?
2758 if (TyposCorrected == 20)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002759 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002760 ++TyposCorrected;
Ted Kremenek1dac3412010-01-06 00:23:04 +00002761
Douglas Gregor546be3c2009-12-30 17:04:44 +00002762 // We only attempt to correct typos for identifiers.
2763 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2764 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002765 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002766
2767 // If the scope specifier itself was invalid, don't try to correct
2768 // typos.
2769 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002770 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002771
2772 // Never try to correct typos during template deduction or
2773 // instantiation.
2774 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002775 return DeclarationName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002776
Douglas Gregor546be3c2009-12-30 17:04:44 +00002777 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002778
2779 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002780 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002781 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002782
2783 // Look in qualified interfaces.
2784 if (OPT) {
2785 for (ObjCObjectPointerType::qual_iterator
2786 I = OPT->qual_begin(), E = OPT->qual_end();
2787 I != E; ++I)
2788 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2789 }
2790 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002791 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2792 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002793 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002794
2795 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2796 } else {
2797 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2798 }
2799
Douglas Gregoraaf87162010-04-14 20:04:41 +00002800 // Add context-dependent keywords.
2801 bool WantTypeSpecifiers = false;
2802 bool WantExpressionKeywords = false;
2803 bool WantCXXNamedCasts = false;
2804 bool WantRemainingKeywords = false;
2805 switch (CTC) {
2806 case CTC_Unknown:
2807 WantTypeSpecifiers = true;
2808 WantExpressionKeywords = true;
2809 WantCXXNamedCasts = true;
2810 WantRemainingKeywords = true;
Douglas Gregor91f7ac72010-05-18 16:14:23 +00002811
2812 if (ObjCMethodDecl *Method = getCurMethodDecl())
2813 if (Method->getClassInterface() &&
2814 Method->getClassInterface()->getSuperClass())
2815 Consumer.addKeywordResult(Context, "super");
2816
Douglas Gregoraaf87162010-04-14 20:04:41 +00002817 break;
2818
2819 case CTC_NoKeywords:
2820 break;
2821
2822 case CTC_Type:
2823 WantTypeSpecifiers = true;
2824 break;
2825
2826 case CTC_ObjCMessageReceiver:
2827 Consumer.addKeywordResult(Context, "super");
2828 // Fall through to handle message receivers like expressions.
2829
2830 case CTC_Expression:
2831 if (getLangOptions().CPlusPlus)
2832 WantTypeSpecifiers = true;
2833 WantExpressionKeywords = true;
2834 // Fall through to get C++ named casts.
2835
2836 case CTC_CXXCasts:
2837 WantCXXNamedCasts = true;
2838 break;
2839
2840 case CTC_MemberLookup:
2841 if (getLangOptions().CPlusPlus)
2842 Consumer.addKeywordResult(Context, "template");
2843 break;
2844 }
2845
2846 if (WantTypeSpecifiers) {
2847 // Add type-specifier keywords to the set of results.
2848 const char *CTypeSpecs[] = {
2849 "char", "const", "double", "enum", "float", "int", "long", "short",
2850 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2851 "_Complex", "_Imaginary",
2852 // storage-specifiers as well
2853 "extern", "inline", "static", "typedef"
2854 };
2855
2856 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2857 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2858 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2859
2860 if (getLangOptions().C99)
2861 Consumer.addKeywordResult(Context, "restrict");
2862 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2863 Consumer.addKeywordResult(Context, "bool");
2864
2865 if (getLangOptions().CPlusPlus) {
2866 Consumer.addKeywordResult(Context, "class");
2867 Consumer.addKeywordResult(Context, "typename");
2868 Consumer.addKeywordResult(Context, "wchar_t");
2869
2870 if (getLangOptions().CPlusPlus0x) {
2871 Consumer.addKeywordResult(Context, "char16_t");
2872 Consumer.addKeywordResult(Context, "char32_t");
2873 Consumer.addKeywordResult(Context, "constexpr");
2874 Consumer.addKeywordResult(Context, "decltype");
2875 Consumer.addKeywordResult(Context, "thread_local");
2876 }
2877 }
2878
2879 if (getLangOptions().GNUMode)
2880 Consumer.addKeywordResult(Context, "typeof");
2881 }
2882
Douglas Gregord0785ea2010-05-18 16:30:22 +00002883 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00002884 Consumer.addKeywordResult(Context, "const_cast");
2885 Consumer.addKeywordResult(Context, "dynamic_cast");
2886 Consumer.addKeywordResult(Context, "reinterpret_cast");
2887 Consumer.addKeywordResult(Context, "static_cast");
2888 }
2889
2890 if (WantExpressionKeywords) {
2891 Consumer.addKeywordResult(Context, "sizeof");
2892 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2893 Consumer.addKeywordResult(Context, "false");
2894 Consumer.addKeywordResult(Context, "true");
2895 }
2896
2897 if (getLangOptions().CPlusPlus) {
2898 const char *CXXExprs[] = {
2899 "delete", "new", "operator", "throw", "typeid"
2900 };
2901 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2902 for (unsigned I = 0; I != NumCXXExprs; ++I)
2903 Consumer.addKeywordResult(Context, CXXExprs[I]);
2904
2905 if (isa<CXXMethodDecl>(CurContext) &&
2906 cast<CXXMethodDecl>(CurContext)->isInstance())
2907 Consumer.addKeywordResult(Context, "this");
2908
2909 if (getLangOptions().CPlusPlus0x) {
2910 Consumer.addKeywordResult(Context, "alignof");
2911 Consumer.addKeywordResult(Context, "nullptr");
2912 }
2913 }
2914 }
2915
2916 if (WantRemainingKeywords) {
2917 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2918 // Statements.
2919 const char *CStmts[] = {
2920 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2921 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2922 for (unsigned I = 0; I != NumCStmts; ++I)
2923 Consumer.addKeywordResult(Context, CStmts[I]);
2924
2925 if (getLangOptions().CPlusPlus) {
2926 Consumer.addKeywordResult(Context, "catch");
2927 Consumer.addKeywordResult(Context, "try");
2928 }
2929
2930 if (S && S->getBreakParent())
2931 Consumer.addKeywordResult(Context, "break");
2932
2933 if (S && S->getContinueParent())
2934 Consumer.addKeywordResult(Context, "continue");
2935
2936 if (!getSwitchStack().empty()) {
2937 Consumer.addKeywordResult(Context, "case");
2938 Consumer.addKeywordResult(Context, "default");
2939 }
2940 } else {
2941 if (getLangOptions().CPlusPlus) {
2942 Consumer.addKeywordResult(Context, "namespace");
2943 Consumer.addKeywordResult(Context, "template");
2944 }
2945
2946 if (S && S->isClassScope()) {
2947 Consumer.addKeywordResult(Context, "explicit");
2948 Consumer.addKeywordResult(Context, "friend");
2949 Consumer.addKeywordResult(Context, "mutable");
2950 Consumer.addKeywordResult(Context, "private");
2951 Consumer.addKeywordResult(Context, "protected");
2952 Consumer.addKeywordResult(Context, "public");
2953 Consumer.addKeywordResult(Context, "virtual");
2954 }
2955 }
2956
2957 if (getLangOptions().CPlusPlus) {
2958 Consumer.addKeywordResult(Context, "using");
2959
2960 if (getLangOptions().CPlusPlus0x)
2961 Consumer.addKeywordResult(Context, "static_assert");
2962 }
2963 }
2964
2965 // If we haven't found anything, we're done.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002966 if (Consumer.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002967 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002968
2969 // Only allow a single, closest name in the result set (it's okay to
2970 // have overloads of that name, though).
Douglas Gregoraaf87162010-04-14 20:04:41 +00002971 DeclarationName BestName;
2972 NamedDecl *BestIvarOrPropertyDecl = 0;
2973 bool FoundIvarOrPropertyDecl = false;
2974
2975 // Check all of the declaration results to find the best name so far.
2976 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2977 IEnd = Consumer.end();
2978 I != IEnd; ++I) {
2979 if (!BestName)
2980 BestName = (*I)->getDeclName();
2981 else if (BestName != (*I)->getDeclName())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002982 return DeclarationName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002983
Douglas Gregoraaf87162010-04-14 20:04:41 +00002984 // \brief Keep track of either an Objective-C ivar or a property, but not
2985 // both.
2986 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
2987 if (FoundIvarOrPropertyDecl)
2988 BestIvarOrPropertyDecl = 0;
2989 else {
2990 BestIvarOrPropertyDecl = *I;
2991 FoundIvarOrPropertyDecl = true;
2992 }
2993 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002994 }
2995
Douglas Gregoraaf87162010-04-14 20:04:41 +00002996 // Now check all of the keyword results to find the best name.
2997 switch (Consumer.keyword_size()) {
2998 case 0:
2999 // No keywords matched.
3000 break;
3001
3002 case 1:
3003 // If we already have a name
3004 if (!BestName) {
3005 // We did not have anything previously,
3006 BestName = *Consumer.keyword_begin();
3007 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
3008 // We have a declaration with the same name as a context-sensitive
3009 // keyword. The keyword takes precedence.
3010 BestIvarOrPropertyDecl = 0;
3011 FoundIvarOrPropertyDecl = false;
3012 Consumer.clear_decls();
Douglas Gregord0785ea2010-05-18 16:30:22 +00003013 } else if (CTC == CTC_ObjCMessageReceiver &&
3014 (*Consumer.keyword_begin())->isStr("super")) {
3015 // In an Objective-C message send, give the "super" keyword a slight
3016 // edge over entities not in function or method scope.
3017 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3018 IEnd = Consumer.end();
3019 I != IEnd; ++I) {
3020 if ((*I)->getDeclName() == BestName) {
3021 if ((*I)->getDeclContext()->isFunctionOrMethod())
3022 return DeclarationName();
3023 }
3024 }
3025
3026 // Everything found was outside a function or method; the 'super'
3027 // keyword takes precedence.
3028 BestIvarOrPropertyDecl = 0;
3029 FoundIvarOrPropertyDecl = false;
3030 Consumer.clear_decls();
3031 BestName = *Consumer.keyword_begin();
Douglas Gregoraaf87162010-04-14 20:04:41 +00003032 } else {
3033 // Name collision; we will not correct typos.
3034 return DeclarationName();
3035 }
3036 break;
3037
3038 default:
3039 // Name collision; we will not correct typos.
3040 return DeclarationName();
3041 }
3042
Douglas Gregor546be3c2009-12-30 17:04:44 +00003043 // BestName is the closest viable name to what the user
3044 // typed. However, to make sure that we don't pick something that's
3045 // way off, make sure that the user typed at least 3 characters for
3046 // each correction.
3047 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregoraaf87162010-04-14 20:04:41 +00003048 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
3049 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregor931f98a2010-04-14 17:09:22 +00003050 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003051
3052 // Perform name lookup again with the name we chose, and declare
3053 // success if we found something that was not ambiguous.
3054 Res.clear();
3055 Res.setLookupName(BestName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003056
3057 // If we found an ivar or property, add that result; no further
3058 // lookup is required.
Douglas Gregoraaf87162010-04-14 20:04:41 +00003059 if (BestIvarOrPropertyDecl)
3060 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003061 // If we're looking into the context of a member, perform qualified
3062 // name lookup on the best name.
Douglas Gregoraaf87162010-04-14 20:04:41 +00003063 else if (!Consumer.keyword_empty()) {
3064 // The best match was a keyword. Return it.
3065 return BestName;
3066 } else if (MemberContext)
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003067 LookupQualifiedName(Res, MemberContext);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003068 // Perform lookup as if we had just parsed the best name.
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003069 else
3070 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3071 EnteringContext);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003072
3073 if (Res.isAmbiguous()) {
3074 Res.suppressDiagnostics();
Douglas Gregor931f98a2010-04-14 17:09:22 +00003075 return DeclarationName();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003076 }
3077
Douglas Gregor931f98a2010-04-14 17:09:22 +00003078 if (Res.getResultKind() != LookupResult::NotFound)
3079 return BestName;
3080
3081 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003082}