blob: 994b633db8edd540266a09cc4ada32602dd06622 [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor34074322009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6538c932009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2d435302009-12-30 17:04:44 +000030#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000031#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000032#include <vector>
33#include <iterator>
34#include <utility>
35#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000036
37using namespace clang;
38
John McCallf6c8a4e2009-11-10 07:01:13 +000039namespace {
40 class UnqualUsingEntry {
41 const DeclContext *Nominated;
42 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000043
John McCallf6c8a4e2009-11-10 07:01:13 +000044 public:
45 UnqualUsingEntry(const DeclContext *Nominated,
46 const DeclContext *CommonAncestor)
47 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
48 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000049
John McCallf6c8a4e2009-11-10 07:01:13 +000050 const DeclContext *getCommonAncestor() const {
51 return CommonAncestor;
52 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000053
John McCallf6c8a4e2009-11-10 07:01:13 +000054 const DeclContext *getNominatedNamespace() const {
55 return Nominated;
56 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 // Sort by the pointer value of the common ancestor.
59 struct Comparator {
60 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
61 return L.getCommonAncestor() < R.getCommonAncestor();
62 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
65 return E.getCommonAncestor() < DC;
66 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000067
John McCallf6c8a4e2009-11-10 07:01:13 +000068 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
69 return DC < E.getCommonAncestor();
70 }
71 };
72 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 /// A collection of using directives, as used by C++ unqualified
75 /// lookup.
76 class UnqualUsingDirectiveSet {
77 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000078
John McCallf6c8a4e2009-11-10 07:01:13 +000079 ListTy list;
80 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 public:
83 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000084
John McCallf6c8a4e2009-11-10 07:01:13 +000085 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
86 // C++ [namespace.udir]p1:
87 // During unqualified name lookup, the names appear as if they
88 // were declared in the nearest enclosing namespace which contains
89 // both the using-directive and the nominated namespace.
90 DeclContext *InnermostFileDC
91 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
92 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +000095 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
96 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
97 visit(Ctx, EffectiveDC);
98 } else {
99 Scope::udir_iterator I = S->using_directives_begin(),
100 End = S->using_directives_end();
101
102 for (; I != End; ++I)
103 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
104 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000105 }
106 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000107
108 // Visits a context and collect all of its using directives
109 // recursively. Treats all using directives as if they were
110 // declared in the context.
111 //
112 // A given context is only every visited once, so it is important
113 // that contexts be visited from the inside out in order to get
114 // the effective DCs right.
115 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
116 if (!visited.insert(DC))
117 return;
118
119 addUsingDirectives(DC, EffectiveDC);
120 }
121
122 // Visits a using directive and collects all of its using
123 // directives recursively. Treats all using directives as if they
124 // were declared in the effective DC.
125 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
126 DeclContext *NS = UD->getNominatedNamespace();
127 if (!visited.insert(NS))
128 return;
129
130 addUsingDirective(UD, EffectiveDC);
131 addUsingDirectives(NS, EffectiveDC);
132 }
133
134 // Adds all the using directives in a context (and those nominated
135 // by its using directives, transitively) as if they appeared in
136 // the given effective context.
137 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
138 llvm::SmallVector<DeclContext*,4> queue;
139 while (true) {
140 DeclContext::udir_iterator I, End;
141 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
142 UsingDirectiveDecl *UD = *I;
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (visited.insert(NS)) {
145 addUsingDirective(UD, EffectiveDC);
146 queue.push_back(NS);
147 }
148 }
149
150 if (queue.empty())
151 return;
152
153 DC = queue.back();
154 queue.pop_back();
155 }
156 }
157
158 // Add a using directive as if it had been declared in the given
159 // context. This helps implement C++ [namespace.udir]p3:
160 // The using-directive is transitive: if a scope contains a
161 // using-directive that nominates a second namespace that itself
162 // contains using-directives, the effect is as if the
163 // using-directives from the second namespace also appeared in
164 // the first.
165 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
166 // Find the common ancestor between the effective context and
167 // the nominated namespace.
168 DeclContext *Common = UD->getNominatedNamespace();
169 while (!Common->Encloses(EffectiveDC))
170 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000171 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000172
173 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
174 }
175
176 void done() {
177 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
178 }
179
180 typedef ListTy::iterator iterator;
181 typedef ListTy::const_iterator const_iterator;
182
183 iterator begin() { return list.begin(); }
184 iterator end() { return list.end(); }
185 const_iterator begin() const { return list.begin(); }
186 const_iterator end() const { return list.end(); }
187
188 std::pair<const_iterator,const_iterator>
189 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000190 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000191 UnqualUsingEntry::Comparator());
192 }
193 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000194}
195
Douglas Gregor889ceb72009-02-03 19:21:40 +0000196// Retrieve the set of identifier namespaces that correspond to a
197// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000198static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
199 bool CPlusPlus,
200 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000201 unsigned IDNS = 0;
202 switch (NameKind) {
203 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000204 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000206 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCallea305ed2009-12-18 10:40:03 +0000208 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
209 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210 break;
211
John McCallb9467b62010-04-24 01:30:58 +0000212 case Sema::LookupOperatorName:
213 // Operator lookup is its own crazy thing; it is not the same
214 // as (e.g.) looking up an operator name for redeclaration.
215 assert(!Redeclaration && "cannot do redeclaration operator lookup");
216 IDNS = Decl::IDNS_NonMemberOperator;
217 break;
218
Douglas Gregor889ceb72009-02-03 19:21:40 +0000219 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000220 if (CPlusPlus) {
221 IDNS = Decl::IDNS_Type;
222
223 // When looking for a redeclaration of a tag name, we add:
224 // 1) TagFriend to find undeclared friend decls
225 // 2) Namespace because they can't "overload" with tag decls.
226 // 3) Tag because it includes class templates, which can't
227 // "overload" with tag decls.
228 if (Redeclaration)
229 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
230 } else {
231 IDNS = Decl::IDNS_Tag;
232 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000233 break;
234
235 case Sema::LookupMemberName:
236 IDNS = Decl::IDNS_Member;
237 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000238 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000239 break;
240
241 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000242 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
243 break;
244
Douglas Gregor889ceb72009-02-03 19:21:40 +0000245 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000246 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000247 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000248
John McCall84d87672009-12-10 09:41:52 +0000249 case Sema::LookupUsingDeclName:
250 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
251 | Decl::IDNS_Member | Decl::IDNS_Using;
252 break;
253
Douglas Gregor79947a22009-04-24 00:11:27 +0000254 case Sema::LookupObjCProtocolName:
255 IDNS = Decl::IDNS_ObjCProtocol;
256 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000257
258 case Sema::LookupAnyName:
259 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
260 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
261 | Decl::IDNS_Type;
262 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000263 }
264 return IDNS;
265}
266
John McCallea305ed2009-12-18 10:40:03 +0000267void LookupResult::configure() {
268 IDNS = getIDNS(LookupKind,
269 SemaRef.getLangOptions().CPlusPlus,
270 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000271
272 // If we're looking for one of the allocation or deallocation
273 // operators, make sure that the implicitly-declared new and delete
274 // operators can be found.
275 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000276 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000277 case OO_New:
278 case OO_Delete:
279 case OO_Array_New:
280 case OO_Array_Delete:
281 SemaRef.DeclareGlobalNewDelete();
282 break;
283
284 default:
285 break;
286 }
287 }
John McCallea305ed2009-12-18 10:40:03 +0000288}
289
John McCall9f3059a2009-10-09 21:13:30 +0000290// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000291void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000292 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000293}
294
John McCall283b9012009-11-22 00:44:51 +0000295/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000296void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000297 unsigned N = Decls.size();
John McCall84d87672009-12-10 09:41:52 +0000298
John McCall9f3059a2009-10-09 21:13:30 +0000299 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000300 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000301 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000302 return;
303 }
304
John McCall283b9012009-11-22 00:44:51 +0000305 // If there's a single decl, we need to examine it to decide what
306 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000307 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000308 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
309 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000310 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000311 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000312 ResultKind = FoundUnresolvedValue;
313 return;
314 }
John McCall9f3059a2009-10-09 21:13:30 +0000315
John McCall6538c932009-10-10 05:48:19 +0000316 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000317 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000318
John McCall9f3059a2009-10-09 21:13:30 +0000319 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000320 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
321
John McCall9f3059a2009-10-09 21:13:30 +0000322 bool Ambiguous = false;
323 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000324 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000325
326 unsigned UniqueTagIndex = 0;
327
328 unsigned I = 0;
329 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000330 NamedDecl *D = Decls[I]->getUnderlyingDecl();
331 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000332
Douglas Gregor13e65872010-08-11 14:45:53 +0000333 // Redeclarations of types via typedef can occur both within a scope
334 // and, through using declarations and directives, across scopes. There is
335 // no ambiguity if they all refer to the same type, so unique based on the
336 // canonical type.
337 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
338 if (!TD->getDeclContext()->isRecord()) {
339 QualType T = SemaRef.Context.getTypeDeclType(TD);
340 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
341 // The type is not unique; pull something off the back and continue
342 // at this index.
343 Decls[I] = Decls[--N];
344 continue;
345 }
346 }
347 }
348
John McCallf0f1cf02009-11-17 07:50:12 +0000349 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000350 // If it's not unique, pull something off the back (and
351 // continue at this index).
352 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000353 continue;
354 }
355
356 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000357
Douglas Gregor13e65872010-08-11 14:45:53 +0000358 if (isa<UnresolvedUsingValueDecl>(D)) {
359 HasUnresolved = true;
360 } else if (isa<TagDecl>(D)) {
361 if (HasTag)
362 Ambiguous = true;
363 UniqueTagIndex = I;
364 HasTag = true;
365 } else if (isa<FunctionTemplateDecl>(D)) {
366 HasFunction = true;
367 HasFunctionTemplate = true;
368 } else if (isa<FunctionDecl>(D)) {
369 HasFunction = true;
370 } else {
371 if (HasNonFunction)
372 Ambiguous = true;
373 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000374 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000375 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000376 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000377
John McCall9f3059a2009-10-09 21:13:30 +0000378 // C++ [basic.scope.hiding]p2:
379 // A class name or enumeration name can be hidden by the name of
380 // an object, function, or enumerator declared in the same
381 // scope. If a class or enumeration name and an object, function,
382 // or enumerator are declared in the same scope (in any order)
383 // with the same name, the class or enumeration name is hidden
384 // wherever the object, function, or enumerator name is visible.
385 // But it's still an error if there are distinct tag types found,
386 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000387 if (HideTags && HasTag && !Ambiguous &&
388 (HasFunction || HasNonFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000389 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000390
John McCall9f3059a2009-10-09 21:13:30 +0000391 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000392
John McCall80053822009-12-03 00:58:24 +0000393 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000394 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000395
John McCall9f3059a2009-10-09 21:13:30 +0000396 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000397 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000398 else if (HasUnresolved)
399 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000400 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000401 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000402 else
John McCall27b18f82009-11-17 02:14:36 +0000403 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000404}
405
John McCall5cebab12009-11-18 07:57:50 +0000406void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000407 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000408 DeclContext::lookup_iterator DI, DE;
409 for (I = P.begin(), E = P.end(); I != E; ++I)
410 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
411 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000412}
413
John McCall5cebab12009-11-18 07:57:50 +0000414void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000415 Paths = new CXXBasePaths;
416 Paths->swap(P);
417 addDeclsFromBasePaths(*Paths);
418 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000419 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000420}
421
John McCall5cebab12009-11-18 07:57:50 +0000422void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000423 Paths = new CXXBasePaths;
424 Paths->swap(P);
425 addDeclsFromBasePaths(*Paths);
426 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000427 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000428}
429
John McCall5cebab12009-11-18 07:57:50 +0000430void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000431 Out << Decls.size() << " result(s)";
432 if (isAmbiguous()) Out << ", ambiguous";
433 if (Paths) Out << ", base paths present";
434
435 for (iterator I = begin(), E = end(); I != E; ++I) {
436 Out << "\n";
437 (*I)->print(Out, 2);
438 }
439}
440
Douglas Gregord3a59182010-02-12 05:48:04 +0000441/// \brief Lookup a builtin function, when name lookup would otherwise
442/// fail.
443static bool LookupBuiltin(Sema &S, LookupResult &R) {
444 Sema::LookupNameKind NameKind = R.getLookupKind();
445
446 // If we didn't find a use of this identifier, and if the identifier
447 // corresponds to a compiler builtin, create the decl object for the builtin
448 // now, injecting it into translation unit scope, and return it.
449 if (NameKind == Sema::LookupOrdinaryName ||
450 NameKind == Sema::LookupRedeclarationWithLinkage) {
451 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
452 if (II) {
453 // If this is a builtin on this (or all) targets, create the decl.
454 if (unsigned BuiltinID = II->getBuiltinID()) {
455 // In C++, we don't have any predefined library functions like
456 // 'malloc'. Instead, we'll just error.
457 if (S.getLangOptions().CPlusPlus &&
458 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
459 return false;
460
461 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
462 S.TUScope, R.isForRedeclaration(),
463 R.getNameLoc());
464 if (D)
465 R.addDecl(D);
466 return (D != NULL);
467 }
468 }
469 }
470
471 return false;
472}
473
Douglas Gregor7454c562010-07-02 20:37:36 +0000474/// \brief Determine whether we can declare a special member function within
475/// the class at this point.
476static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
477 const CXXRecordDecl *Class) {
John McCall2ded5d22010-08-11 23:52:36 +0000478 // Don't do it if the class is invalid.
479 if (Class->isInvalidDecl())
480 return false;
481
Douglas Gregor7454c562010-07-02 20:37:36 +0000482 // We need to have a definition for the class.
483 if (!Class->getDefinition() || Class->isDependentContext())
484 return false;
485
486 // We can't be in the middle of defining the class.
487 if (const RecordType *RecordTy
488 = Context.getTypeDeclType(Class)->getAs<RecordType>())
489 return !RecordTy->isBeingDefined();
490
491 return false;
492}
493
494void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000495 if (!CanDeclareSpecialMemberFunction(Context, Class))
496 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000497
498 // If the default constructor has not yet been declared, do so now.
499 if (!Class->hasDeclaredDefaultConstructor())
500 DeclareImplicitDefaultConstructor(Class);
Douglas Gregora6d69502010-07-02 23:41:54 +0000501
502 // If the copy constructor has not yet been declared, do so now.
503 if (!Class->hasDeclaredCopyConstructor())
504 DeclareImplicitCopyConstructor(Class);
505
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000506 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000507 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000508 DeclareImplicitCopyAssignment(Class);
509
Douglas Gregor7454c562010-07-02 20:37:36 +0000510 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000511 if (!Class->hasDeclaredDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +0000512 DeclareImplicitDestructor(Class);
513}
514
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000515/// \brief Determine whether this is the name of an implicitly-declared
516/// special member function.
517static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
518 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000519 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000520 case DeclarationName::CXXDestructorName:
521 return true;
522
523 case DeclarationName::CXXOperatorName:
524 return Name.getCXXOverloadedOperator() == OO_Equal;
525
526 default:
527 break;
528 }
529
530 return false;
531}
532
533/// \brief If there are any implicit member functions with the given name
534/// that need to be declared in the given declaration context, do so.
535static void DeclareImplicitMemberFunctionsWithName(Sema &S,
536 DeclarationName Name,
537 const DeclContext *DC) {
538 if (!DC)
539 return;
540
541 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000542 case DeclarationName::CXXConstructorName:
543 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000544 if (Record->getDefinition() &&
545 CanDeclareSpecialMemberFunction(S.Context, Record)) {
546 if (!Record->hasDeclaredDefaultConstructor())
547 S.DeclareImplicitDefaultConstructor(
548 const_cast<CXXRecordDecl *>(Record));
549 if (!Record->hasDeclaredCopyConstructor())
550 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
551 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000552 break;
553
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000554 case DeclarationName::CXXDestructorName:
555 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
556 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
557 CanDeclareSpecialMemberFunction(S.Context, Record))
558 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000559 break;
560
561 case DeclarationName::CXXOperatorName:
562 if (Name.getCXXOverloadedOperator() != OO_Equal)
563 break;
564
565 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
566 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
567 CanDeclareSpecialMemberFunction(S.Context, Record))
568 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
569 break;
570
571 default:
572 break;
573 }
574}
Douglas Gregor7454c562010-07-02 20:37:36 +0000575
John McCall9f3059a2009-10-09 21:13:30 +0000576// Adds all qualifying matches for a name within a decl context to the
577// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000578static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000579 bool Found = false;
580
Douglas Gregor7454c562010-07-02 20:37:36 +0000581 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000582 if (S.getLangOptions().CPlusPlus)
583 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor7454c562010-07-02 20:37:36 +0000584
585 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000586 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000587 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000588 NamedDecl *D = *I;
589 if (R.isAcceptableDecl(D)) {
590 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000591 Found = true;
592 }
593 }
John McCall9f3059a2009-10-09 21:13:30 +0000594
Douglas Gregord3a59182010-02-12 05:48:04 +0000595 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
596 return true;
597
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000598 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000599 != DeclarationName::CXXConversionFunctionName ||
600 R.getLookupName().getCXXNameType()->isDependentType() ||
601 !isa<CXXRecordDecl>(DC))
602 return Found;
603
604 // C++ [temp.mem]p6:
605 // A specialization of a conversion function template is not found by
606 // name lookup. Instead, any conversion function templates visible in the
607 // context of the use are considered. [...]
608 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
609 if (!Record->isDefinition())
610 return Found;
611
612 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
613 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
614 UEnd = Unresolved->end(); U != UEnd; ++U) {
615 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
616 if (!ConvTemplate)
617 continue;
618
619 // When we're performing lookup for the purposes of redeclaration, just
620 // add the conversion function template. When we deduce template
621 // arguments for specializations, we'll end up unifying the return
622 // type of the new declaration with the type of the function template.
623 if (R.isForRedeclaration()) {
624 R.addDecl(ConvTemplate);
625 Found = true;
626 continue;
627 }
628
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000629 // C++ [temp.mem]p6:
Chandler Carruth3a693b72010-01-31 11:44:02 +0000630 // [...] For each such operator, if argument deduction succeeds
631 // (14.9.2.3), the resulting specialization is used as if found by
632 // name lookup.
633 //
634 // When referencing a conversion function for any purpose other than
635 // a redeclaration (such that we'll be building an expression with the
636 // result), perform template argument deduction and place the
637 // specialization into the result set. We do this to avoid forcing all
638 // callers to perform special deduction for conversion functions.
John McCallbc077cf2010-02-08 23:07:23 +0000639 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000640 FunctionDecl *Specialization = 0;
641
642 const FunctionProtoType *ConvProto
643 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
644 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000645
Chandler Carruth3a693b72010-01-31 11:44:02 +0000646 // Compute the type of the function that we would expect the conversion
647 // function to have, if it were to match the name given.
648 // FIXME: Calling convention!
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000649 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruth3a693b72010-01-31 11:44:02 +0000650 QualType ExpectedType
651 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
652 0, 0, ConvProto->isVariadic(),
653 ConvProto->getTypeQuals(),
654 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000655 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruth3a693b72010-01-31 11:44:02 +0000656
657 // Perform template argument deduction against the type that we would
658 // expect the function to have.
659 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
660 Specialization, Info)
661 == Sema::TDK_Success) {
662 R.addDecl(Specialization);
663 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000664 }
665 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000666
John McCall9f3059a2009-10-09 21:13:30 +0000667 return Found;
668}
669
John McCallf6c8a4e2009-11-10 07:01:13 +0000670// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000671static bool
Douglas Gregord3a59182010-02-12 05:48:04 +0000672CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
673 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000674
675 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
676
John McCallf6c8a4e2009-11-10 07:01:13 +0000677 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000678 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000679
John McCallf6c8a4e2009-11-10 07:01:13 +0000680 // Perform direct name lookup into the namespaces nominated by the
681 // using directives whose common ancestor is this namespace.
682 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
683 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000684
John McCallf6c8a4e2009-11-10 07:01:13 +0000685 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000686 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000687 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000688
689 R.resolveKind();
690
691 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000692}
693
694static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000695 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000696 return Ctx->isFileContext();
697 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000698}
Douglas Gregored8f2882009-01-30 01:04:22 +0000699
Douglas Gregor66230062010-03-15 14:33:29 +0000700// Find the next outer declaration context from this scope. This
701// routine actually returns the semantic outer context, which may
702// differ from the lexical context (encoded directly in the Scope
703// stack) when we are parsing a member of a class template. In this
704// case, the second element of the pair will be true, to indicate that
705// name lookup should continue searching in this semantic context when
706// it leaves the current template parameter scope.
707static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
708 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
709 DeclContext *Lexical = 0;
710 for (Scope *OuterS = S->getParent(); OuterS;
711 OuterS = OuterS->getParent()) {
712 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000713 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000714 break;
715 }
716 }
717
718 // C++ [temp.local]p8:
719 // In the definition of a member of a class template that appears
720 // outside of the namespace containing the class template
721 // definition, the name of a template-parameter hides the name of
722 // a member of this namespace.
723 //
724 // Example:
725 //
726 // namespace N {
727 // class C { };
728 //
729 // template<class T> class B {
730 // void f(T);
731 // };
732 // }
733 //
734 // template<class C> void N::B<C>::f(C) {
735 // C b; // C is the template parameter, not N::C
736 // }
737 //
738 // In this example, the lexical context we return is the
739 // TranslationUnit, while the semantic context is the namespace N.
740 if (!Lexical || !DC || !S->getParent() ||
741 !S->getParent()->isTemplateParamScope())
742 return std::make_pair(Lexical, false);
743
744 // Find the outermost template parameter scope.
745 // For the example, this is the scope for the template parameters of
746 // template<class C>.
747 Scope *OutermostTemplateScope = S->getParent();
748 while (OutermostTemplateScope->getParent() &&
749 OutermostTemplateScope->getParent()->isTemplateParamScope())
750 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregor7f737c02009-09-10 16:57:35 +0000751
Douglas Gregor66230062010-03-15 14:33:29 +0000752 // Find the namespace context in which the original scope occurs. In
753 // the example, this is namespace N.
754 DeclContext *Semantic = DC;
755 while (!Semantic->isFileContext())
756 Semantic = Semantic->getParent();
757
758 // Find the declaration context just outside of the template
759 // parameter scope. This is the context in which the template is
760 // being lexically declaration (a namespace context). In the
761 // example, this is the global scope.
762 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
763 Lexical->Encloses(Semantic))
764 return std::make_pair(Semantic, true);
765
766 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000767}
768
John McCall27b18f82009-11-17 02:14:36 +0000769bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000770 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000771
772 DeclarationName Name = R.getLookupName();
773
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000774 // If this is the name of an implicitly-declared special member function,
775 // go through the scope stack to implicitly declare
776 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
777 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
778 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
779 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
780 }
781
782 // Implicitly declare member functions with the name we're looking for, if in
783 // fact we are in a scope where it matters.
784
Douglas Gregor889ceb72009-02-03 19:21:40 +0000785 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000786 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000787 I = IdResolver.begin(Name),
788 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000789
Douglas Gregor889ceb72009-02-03 19:21:40 +0000790 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000791 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000792 // ...During unqualified name lookup (3.4.1), the names appear as if
793 // they were declared in the nearest enclosing namespace which contains
794 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000795 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000796 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000797 //
798 // For example:
799 // namespace A { int i; }
800 // void foo() {
801 // int i;
802 // {
803 // using namespace A;
804 // ++i; // finds local 'i', A::i appears at global scope
805 // }
806 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000807 //
Douglas Gregor66230062010-03-15 14:33:29 +0000808 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000809 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000810 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
811
Douglas Gregor889ceb72009-02-03 19:21:40 +0000812 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000813 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000814 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000815 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000816 Found = true;
817 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000818 }
819 }
John McCall9f3059a2009-10-09 21:13:30 +0000820 if (Found) {
821 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000822 if (S->isClassScope())
823 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
824 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000825 return true;
826 }
827
Douglas Gregor66230062010-03-15 14:33:29 +0000828 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
829 S->getParent() && !S->getParent()->isTemplateParamScope()) {
830 // We've just searched the last template parameter scope and
831 // found nothing, so look into the the contexts between the
832 // lexical and semantic declaration contexts returned by
833 // findOuterContext(). This implements the name lookup behavior
834 // of C++ [temp.local]p8.
835 Ctx = OutsideOfTemplateParamDC;
836 OutsideOfTemplateParamDC = 0;
837 }
838
839 if (Ctx) {
840 DeclContext *OuterCtx;
841 bool SearchAfterTemplateScope;
842 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
843 if (SearchAfterTemplateScope)
844 OutsideOfTemplateParamDC = OuterCtx;
845
Douglas Gregorea166062010-03-15 15:26:48 +0000846 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000847 // We do not directly look into transparent contexts, since
848 // those entities will be found in the nearest enclosing
849 // non-transparent context.
850 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000851 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000852
853 // We do not look directly into function or method contexts,
854 // since all of the local variables and parameters of the
855 // function/method are present within the Scope.
856 if (Ctx->isFunctionOrMethod()) {
857 // If we have an Objective-C instance method, look for ivars
858 // in the corresponding interface.
859 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
860 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
861 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
862 ObjCInterfaceDecl *ClassDeclared;
863 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
864 Name.getAsIdentifierInfo(),
865 ClassDeclared)) {
866 if (R.isAcceptableDecl(Ivar)) {
867 R.addDecl(Ivar);
868 R.resolveKind();
869 return true;
870 }
871 }
872 }
873 }
874
875 continue;
876 }
877
Douglas Gregor7f737c02009-09-10 16:57:35 +0000878 // Perform qualified name lookup into this context.
879 // FIXME: In some cases, we know that every name that could be found by
880 // this qualified name lookup will also be on the identifier chain. For
881 // example, inside a class without any base classes, we never need to
882 // perform qualified lookup because all of the members are on top of the
883 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000884 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000885 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000886 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000887 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000888 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000889
John McCallf6c8a4e2009-11-10 07:01:13 +0000890 // Stop if we ran out of scopes.
891 // FIXME: This really, really shouldn't be happening.
892 if (!S) return false;
893
Douglas Gregor700792c2009-02-05 19:25:20 +0000894 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000895 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000896 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000897 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
898 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000899
John McCallf6c8a4e2009-11-10 07:01:13 +0000900 UnqualUsingDirectiveSet UDirs;
901 UDirs.visitScopeChain(Initial, S);
902 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000903
Douglas Gregor700792c2009-02-05 19:25:20 +0000904 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000905 // Unqualified name lookup in C++ requires looking into scopes
906 // that aren't strictly lexical, and therefore we walk through the
907 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000908
Douglas Gregor889ceb72009-02-03 19:21:40 +0000909 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000910 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000911 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000912 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000913 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000914 // We found something. Look for anything else in our scope
915 // with this same name and in an acceptable identifier
916 // namespace, so that we can construct an overload set if we
917 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000918 Found = true;
919 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000920 }
921 }
922
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000923 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000924 R.resolveKind();
925 return true;
926 }
927
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000928 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
929 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
930 S->getParent() && !S->getParent()->isTemplateParamScope()) {
931 // We've just searched the last template parameter scope and
932 // found nothing, so look into the the contexts between the
933 // lexical and semantic declaration contexts returned by
934 // findOuterContext(). This implements the name lookup behavior
935 // of C++ [temp.local]p8.
936 Ctx = OutsideOfTemplateParamDC;
937 OutsideOfTemplateParamDC = 0;
938 }
939
940 if (Ctx) {
941 DeclContext *OuterCtx;
942 bool SearchAfterTemplateScope;
943 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
944 if (SearchAfterTemplateScope)
945 OutsideOfTemplateParamDC = OuterCtx;
946
947 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
948 // We do not directly look into transparent contexts, since
949 // those entities will be found in the nearest enclosing
950 // non-transparent context.
951 if (Ctx->isTransparentContext())
952 continue;
953
954 // If we have a context, and it's not a context stashed in the
955 // template parameter scope for an out-of-line definition, also
956 // look into that context.
957 if (!(Found && S && S->isTemplateParamScope())) {
958 assert(Ctx->isFileContext() &&
959 "We should have been looking only at file context here already.");
960
961 // Look into context considering using-directives.
962 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
963 Found = true;
964 }
965
966 if (Found) {
967 R.resolveKind();
968 return true;
969 }
970
971 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
972 return false;
973 }
974 }
975
Douglas Gregor3ce74932010-02-05 07:07:10 +0000976 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000977 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000978 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000979
John McCall9f3059a2009-10-09 21:13:30 +0000980 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000981}
982
Douglas Gregor34074322009-01-14 22:20:51 +0000983/// @brief Perform unqualified name lookup starting from a given
984/// scope.
985///
986/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
987/// used to find names within the current scope. For example, 'x' in
988/// @code
989/// int x;
990/// int f() {
991/// return x; // unqualified name look finds 'x' in the global scope
992/// }
993/// @endcode
994///
995/// Different lookup criteria can find different names. For example, a
996/// particular scope can have both a struct and a function of the same
997/// name, and each can be found by certain lookup criteria. For more
998/// information about lookup criteria, see the documentation for the
999/// class LookupCriteria.
1000///
1001/// @param S The scope from which unqualified name lookup will
1002/// begin. If the lookup criteria permits, name lookup may also search
1003/// in the parent scopes.
1004///
1005/// @param Name The name of the entity that we are searching for.
1006///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001007/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001008/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001009/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001010///
1011/// @returns The result of name lookup, which includes zero or more
1012/// declarations and possibly additional information used to diagnose
1013/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001014bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1015 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001016 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001017
John McCall27b18f82009-11-17 02:14:36 +00001018 LookupNameKind NameKind = R.getLookupKind();
1019
Douglas Gregor34074322009-01-14 22:20:51 +00001020 if (!getLangOptions().CPlusPlus) {
1021 // Unqualified name lookup in C/Objective-C is purely lexical, so
1022 // search in the declarations attached to the name.
1023
John McCallea305ed2009-12-18 10:40:03 +00001024 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001025 // Find the nearest non-transparent declaration scope.
1026 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001027 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001028 static_cast<DeclContext *>(S->getEntity())
1029 ->isTransparentContext()))
1030 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001031 }
1032
John McCallea305ed2009-12-18 10:40:03 +00001033 unsigned IDNS = R.getIdentifierNamespace();
1034
Douglas Gregor34074322009-01-14 22:20:51 +00001035 // Scan up the scope chain looking for a decl that matches this
1036 // identifier that is in the appropriate namespace. This search
1037 // should not take long, as shadowing of names is uncommon, and
1038 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001039 bool LeftStartingScope = false;
1040
Douglas Gregored8f2882009-01-30 01:04:22 +00001041 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001042 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001043 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001044 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001045 if (NameKind == LookupRedeclarationWithLinkage) {
1046 // Determine whether this (or a previous) declaration is
1047 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00001048 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001049 LeftStartingScope = true;
1050
1051 // If we found something outside of our starting scope that
1052 // does not have linkage, skip it.
1053 if (LeftStartingScope && !((*I)->hasLinkage()))
1054 continue;
1055 }
1056
John McCall9f3059a2009-10-09 21:13:30 +00001057 R.addDecl(*I);
1058
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001059 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001060 // If this declaration has the "overloadable" attribute, we
1061 // might have a set of overloaded functions.
1062
1063 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001064 while (!(S->getFlags() & Scope::DeclScope) ||
1065 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001066 S = S->getParent();
1067
1068 // Find the last declaration in this scope (with the same
1069 // name, naturally).
1070 IdentifierResolver::iterator LastI = I;
1071 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +00001072 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001073 break;
John McCall9f3059a2009-10-09 21:13:30 +00001074 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001075 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001076 }
1077
John McCall9f3059a2009-10-09 21:13:30 +00001078 R.resolveKind();
1079
1080 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001081 }
Douglas Gregor34074322009-01-14 22:20:51 +00001082 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001083 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001084 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001085 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001086 }
1087
1088 // If we didn't find a use of this identifier, and if the identifier
1089 // corresponds to a compiler builtin, create the decl object for the builtin
1090 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +00001091 if (AllowBuiltinCreation)
1092 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001093
John McCall9f3059a2009-10-09 21:13:30 +00001094 return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001095}
1096
John McCall6538c932009-10-10 05:48:19 +00001097/// @brief Perform qualified name lookup in the namespaces nominated by
1098/// using directives by the given context.
1099///
1100/// C++98 [namespace.qual]p2:
1101/// Given X::m (where X is a user-declared namespace), or given ::m
1102/// (where X is the global namespace), let S be the set of all
1103/// declarations of m in X and in the transitive closure of all
1104/// namespaces nominated by using-directives in X and its used
1105/// namespaces, except that using-directives are ignored in any
1106/// namespace, including X, directly containing one or more
1107/// declarations of m. No namespace is searched more than once in
1108/// the lookup of a name. If S is the empty set, the program is
1109/// ill-formed. Otherwise, if S has exactly one member, or if the
1110/// context of the reference is a using-declaration
1111/// (namespace.udecl), S is the required set of declarations of
1112/// m. Otherwise if the use of m is not one that allows a unique
1113/// declaration to be chosen from S, the program is ill-formed.
1114/// C++98 [namespace.qual]p5:
1115/// During the lookup of a qualified namespace member name, if the
1116/// lookup finds more than one declaration of the member, and if one
1117/// declaration introduces a class name or enumeration name and the
1118/// other declarations either introduce the same object, the same
1119/// enumerator or a set of functions, the non-type name hides the
1120/// class or enumeration name if and only if the declarations are
1121/// from the same namespace; otherwise (the declarations are from
1122/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001123static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001124 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001125 assert(StartDC->isFileContext() && "start context is not a file context");
1126
1127 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1128 DeclContext::udir_iterator E = StartDC->using_directives_end();
1129
1130 if (I == E) return false;
1131
1132 // We have at least added all these contexts to the queue.
1133 llvm::DenseSet<DeclContext*> Visited;
1134 Visited.insert(StartDC);
1135
1136 // We have not yet looked into these namespaces, much less added
1137 // their "using-children" to the queue.
1138 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1139
1140 // We have already looked into the initial namespace; seed the queue
1141 // with its using-children.
1142 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001143 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001144 if (Visited.insert(ND).second)
1145 Queue.push_back(ND);
1146 }
1147
1148 // The easiest way to implement the restriction in [namespace.qual]p5
1149 // is to check whether any of the individual results found a tag
1150 // and, if so, to declare an ambiguity if the final result is not
1151 // a tag.
1152 bool FoundTag = false;
1153 bool FoundNonTag = false;
1154
John McCall5cebab12009-11-18 07:57:50 +00001155 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001156
1157 bool Found = false;
1158 while (!Queue.empty()) {
1159 NamespaceDecl *ND = Queue.back();
1160 Queue.pop_back();
1161
1162 // We go through some convolutions here to avoid copying results
1163 // between LookupResults.
1164 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001165 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001166 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001167
1168 if (FoundDirect) {
1169 // First do any local hiding.
1170 DirectR.resolveKind();
1171
1172 // If the local result is a tag, remember that.
1173 if (DirectR.isSingleTagDecl())
1174 FoundTag = true;
1175 else
1176 FoundNonTag = true;
1177
1178 // Append the local results to the total results if necessary.
1179 if (UseLocal) {
1180 R.addAllDecls(LocalR);
1181 LocalR.clear();
1182 }
1183 }
1184
1185 // If we find names in this namespace, ignore its using directives.
1186 if (FoundDirect) {
1187 Found = true;
1188 continue;
1189 }
1190
1191 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1192 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1193 if (Visited.insert(Nom).second)
1194 Queue.push_back(Nom);
1195 }
1196 }
1197
1198 if (Found) {
1199 if (FoundTag && FoundNonTag)
1200 R.setAmbiguousQualifiedTagHiding();
1201 else
1202 R.resolveKind();
1203 }
1204
1205 return Found;
1206}
1207
Douglas Gregor39982192010-08-15 06:18:01 +00001208/// \brief Callback that looks for any member of a class with the given name.
1209static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1210 CXXBasePath &Path,
1211 void *Name) {
1212 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1213
1214 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1215 Path.Decls = BaseRecord->lookup(N);
1216 return Path.Decls.first != Path.Decls.second;
1217}
1218
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001219/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001220///
1221/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1222/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001223/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001224///
1225/// Different lookup criteria can find different names. For example, a
1226/// particular scope can have both a struct and a function of the same
1227/// name, and each can be found by certain lookup criteria. For more
1228/// information about lookup criteria, see the documentation for the
1229/// class LookupCriteria.
1230///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001231/// \param R captures both the lookup criteria and any lookup results found.
1232///
1233/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001234/// search. If the lookup criteria permits, name lookup may also search
1235/// in the parent contexts or (for C++ classes) base classes.
1236///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001237/// \param InUnqualifiedLookup true if this is qualified name lookup that
1238/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001239///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001240/// \returns true if lookup succeeded, false if it failed.
1241bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1242 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001243 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001244
John McCall27b18f82009-11-17 02:14:36 +00001245 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001246 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001247
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001248 // Make sure that the declaration context is complete.
1249 assert((!isa<TagDecl>(LookupCtx) ||
1250 LookupCtx->isDependentContext() ||
1251 cast<TagDecl>(LookupCtx)->isDefinition() ||
1252 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1253 ->isBeingDefined()) &&
1254 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001255
Douglas Gregor34074322009-01-14 22:20:51 +00001256 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001257 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001258 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001259 if (isa<CXXRecordDecl>(LookupCtx))
1260 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001261 return true;
1262 }
Douglas Gregor34074322009-01-14 22:20:51 +00001263
John McCall6538c932009-10-10 05:48:19 +00001264 // Don't descend into implied contexts for redeclarations.
1265 // C++98 [namespace.qual]p6:
1266 // In a declaration for a namespace member in which the
1267 // declarator-id is a qualified-id, given that the qualified-id
1268 // for the namespace member has the form
1269 // nested-name-specifier unqualified-id
1270 // the unqualified-id shall name a member of the namespace
1271 // designated by the nested-name-specifier.
1272 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001273 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001274 return false;
1275
John McCall27b18f82009-11-17 02:14:36 +00001276 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001277 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001278 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001279
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001280 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001281 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001282 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001283 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001284 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001285
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001286 // If we're performing qualified name lookup into a dependent class,
1287 // then we are actually looking into a current instantiation. If we have any
1288 // dependent base classes, then we either have to delay lookup until
1289 // template instantiation time (at which point all bases will be available)
1290 // or we have to fail.
1291 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1292 LookupRec->hasAnyDependentBases()) {
1293 R.setNotFoundInCurrentInstantiation();
1294 return false;
1295 }
1296
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001297 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001298 CXXBasePaths Paths;
1299 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001300
1301 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001302 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001303 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001304 case LookupOrdinaryName:
1305 case LookupMemberName:
1306 case LookupRedeclarationWithLinkage:
1307 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1308 break;
1309
1310 case LookupTagName:
1311 BaseCallback = &CXXRecordDecl::FindTagMember;
1312 break;
John McCall84d87672009-12-10 09:41:52 +00001313
Douglas Gregor39982192010-08-15 06:18:01 +00001314 case LookupAnyName:
1315 BaseCallback = &LookupAnyMember;
1316 break;
1317
John McCall84d87672009-12-10 09:41:52 +00001318 case LookupUsingDeclName:
1319 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001320
1321 case LookupOperatorName:
1322 case LookupNamespaceName:
1323 case LookupObjCProtocolName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001324 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001325 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001326
1327 case LookupNestedNameSpecifierName:
1328 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1329 break;
1330 }
1331
John McCall27b18f82009-11-17 02:14:36 +00001332 if (!LookupRec->lookupInBases(BaseCallback,
1333 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001334 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001335
John McCall553c0792010-01-23 00:46:32 +00001336 R.setNamingClass(LookupRec);
1337
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001338 // C++ [class.member.lookup]p2:
1339 // [...] If the resulting set of declarations are not all from
1340 // sub-objects of the same type, or the set has a nonstatic member
1341 // and includes members from distinct sub-objects, there is an
1342 // ambiguity and the program is ill-formed. Otherwise that set is
1343 // the result of the lookup.
1344 // FIXME: support using declarations!
1345 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001346 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001347 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001348 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001349 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001350 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001351
John McCall401982f2010-01-20 21:53:11 +00001352 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1353 // across all paths.
1354 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1355
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001356 // Determine whether we're looking at a distinct sub-object or not.
1357 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001358 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001359 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1360 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001361 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001362 != Context.getCanonicalType(PathElement.Base->getType())) {
1363 // We found members of the given name in two subobjects of
1364 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001365 R.setAmbiguousBaseSubobjectTypes(Paths);
1366 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001367 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1368 // We have a different subobject of the same type.
1369
1370 // C++ [class.member.lookup]p5:
1371 // A static member, a nested type or an enumerator defined in
1372 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001373 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001374 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001375 if (isa<VarDecl>(FirstDecl) ||
1376 isa<TypeDecl>(FirstDecl) ||
1377 isa<EnumConstantDecl>(FirstDecl))
1378 continue;
1379
1380 if (isa<CXXMethodDecl>(FirstDecl)) {
1381 // Determine whether all of the methods are static.
1382 bool AllMethodsAreStatic = true;
1383 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1384 Func != Path->Decls.second; ++Func) {
1385 if (!isa<CXXMethodDecl>(*Func)) {
1386 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1387 break;
1388 }
1389
1390 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1391 AllMethodsAreStatic = false;
1392 break;
1393 }
1394 }
1395
1396 if (AllMethodsAreStatic)
1397 continue;
1398 }
1399
1400 // We have found a nonstatic member name in multiple, distinct
1401 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001402 R.setAmbiguousBaseSubobjects(Paths);
1403 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001404 }
1405 }
1406
1407 // Lookup in a base class succeeded; return these results.
1408
John McCall9f3059a2009-10-09 21:13:30 +00001409 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001410 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1411 NamedDecl *D = *I;
1412 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1413 D->getAccess());
1414 R.addDecl(D, AS);
1415 }
John McCall9f3059a2009-10-09 21:13:30 +00001416 R.resolveKind();
1417 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001418}
1419
1420/// @brief Performs name lookup for a name that was parsed in the
1421/// source code, and may contain a C++ scope specifier.
1422///
1423/// This routine is a convenience routine meant to be called from
1424/// contexts that receive a name and an optional C++ scope specifier
1425/// (e.g., "N::M::x"). It will then perform either qualified or
1426/// unqualified name lookup (with LookupQualifiedName or LookupName,
1427/// respectively) on the given name and return those results.
1428///
1429/// @param S The scope from which unqualified name lookup will
1430/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001431///
Douglas Gregore861bac2009-08-25 22:51:20 +00001432/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001433///
1434/// @param Name The name of the entity that name lookup will
1435/// search for.
1436///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001437/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001438/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001439/// C library functions (like "malloc") are implicitly declared.
1440///
Douglas Gregore861bac2009-08-25 22:51:20 +00001441/// @param EnteringContext Indicates whether we are going to enter the
1442/// context of the scope-specifier SS (if present).
1443///
John McCall9f3059a2009-10-09 21:13:30 +00001444/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001445bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001446 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001447 if (SS && SS->isInvalid()) {
1448 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001449 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001450 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001451 }
Mike Stump11289f42009-09-09 15:08:12 +00001452
Douglas Gregore861bac2009-08-25 22:51:20 +00001453 if (SS && SS->isSet()) {
1454 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001455 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001456 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001457 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001458 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001459
John McCall27b18f82009-11-17 02:14:36 +00001460 R.setContextRange(SS->getRange());
1461
1462 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001463 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001464
Douglas Gregore861bac2009-08-25 22:51:20 +00001465 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001466 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001467 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001468 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001469 }
1470
Mike Stump11289f42009-09-09 15:08:12 +00001471 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001472 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001473}
1474
Douglas Gregor889ceb72009-02-03 19:21:40 +00001475
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001476/// @brief Produce a diagnostic describing the ambiguity that resulted
1477/// from name lookup.
1478///
1479/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001480///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001481/// @param Name The name of the entity that name lookup was
1482/// searching for.
1483///
1484/// @param NameLoc The location of the name within the source code.
1485///
1486/// @param LookupRange A source range that provides more
1487/// source-location information concerning the lookup itself. For
1488/// example, this range might highlight a nested-name-specifier that
1489/// precedes the name.
1490///
1491/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001492bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001493 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1494
John McCall27b18f82009-11-17 02:14:36 +00001495 DeclarationName Name = Result.getLookupName();
1496 SourceLocation NameLoc = Result.getNameLoc();
1497 SourceRange LookupRange = Result.getContextRange();
1498
John McCall6538c932009-10-10 05:48:19 +00001499 switch (Result.getAmbiguityKind()) {
1500 case LookupResult::AmbiguousBaseSubobjects: {
1501 CXXBasePaths *Paths = Result.getBasePaths();
1502 QualType SubobjectType = Paths->front().back().Base->getType();
1503 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1504 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1505 << LookupRange;
1506
1507 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1508 while (isa<CXXMethodDecl>(*Found) &&
1509 cast<CXXMethodDecl>(*Found)->isStatic())
1510 ++Found;
1511
1512 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1513
1514 return true;
1515 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001516
John McCall6538c932009-10-10 05:48:19 +00001517 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001518 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1519 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001520
1521 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001522 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001523 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1524 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001525 Path != PathEnd; ++Path) {
1526 Decl *D = *Path->Decls.first;
1527 if (DeclsPrinted.insert(D).second)
1528 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1529 }
1530
Douglas Gregor1c846b02009-01-16 00:38:09 +00001531 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001532 }
1533
John McCall6538c932009-10-10 05:48:19 +00001534 case LookupResult::AmbiguousTagHiding: {
1535 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001536
John McCall6538c932009-10-10 05:48:19 +00001537 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1538
1539 LookupResult::iterator DI, DE = Result.end();
1540 for (DI = Result.begin(); DI != DE; ++DI)
1541 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1542 TagDecls.insert(TD);
1543 Diag(TD->getLocation(), diag::note_hidden_tag);
1544 }
1545
1546 for (DI = Result.begin(); DI != DE; ++DI)
1547 if (!isa<TagDecl>(*DI))
1548 Diag((*DI)->getLocation(), diag::note_hiding_object);
1549
1550 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001551 LookupResult::Filter F = Result.makeFilter();
1552 while (F.hasNext()) {
1553 if (TagDecls.count(F.next()))
1554 F.erase();
1555 }
1556 F.done();
John McCall6538c932009-10-10 05:48:19 +00001557
1558 return true;
1559 }
1560
1561 case LookupResult::AmbiguousReference: {
1562 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001563
John McCall6538c932009-10-10 05:48:19 +00001564 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1565 for (; DI != DE; ++DI)
1566 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001567
John McCall6538c932009-10-10 05:48:19 +00001568 return true;
1569 }
1570 }
1571
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001572 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001573 return true;
1574}
Douglas Gregore254f902009-02-04 00:32:51 +00001575
John McCallf24d7bb2010-05-28 18:45:08 +00001576namespace {
1577 struct AssociatedLookup {
1578 AssociatedLookup(Sema &S,
1579 Sema::AssociatedNamespaceSet &Namespaces,
1580 Sema::AssociatedClassSet &Classes)
1581 : S(S), Namespaces(Namespaces), Classes(Classes) {
1582 }
1583
1584 Sema &S;
1585 Sema::AssociatedNamespaceSet &Namespaces;
1586 Sema::AssociatedClassSet &Classes;
1587 };
1588}
1589
Mike Stump11289f42009-09-09 15:08:12 +00001590static void
John McCallf24d7bb2010-05-28 18:45:08 +00001591addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001592
Douglas Gregor8b895222010-04-30 07:08:38 +00001593static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1594 DeclContext *Ctx) {
1595 // Add the associated namespace for this class.
1596
1597 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1598 // be a locally scoped record.
1599
1600 while (Ctx->isRecord() || Ctx->isTransparentContext())
1601 Ctx = Ctx->getParent();
1602
John McCallc7e8e792009-08-07 22:18:02 +00001603 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001604 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001605}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001606
Mike Stump11289f42009-09-09 15:08:12 +00001607// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001608// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001609static void
John McCallf24d7bb2010-05-28 18:45:08 +00001610addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1611 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001612 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001613 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001614 switch (Arg.getKind()) {
1615 case TemplateArgument::Null:
1616 break;
Mike Stump11289f42009-09-09 15:08:12 +00001617
Douglas Gregor197e5f72009-07-08 07:51:57 +00001618 case TemplateArgument::Type:
1619 // [...] the namespaces and classes associated with the types of the
1620 // template arguments provided for template type parameters (excluding
1621 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001622 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001623 break;
Mike Stump11289f42009-09-09 15:08:12 +00001624
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001625 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001626 // [...] the namespaces in which any template template arguments are
1627 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001628 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001629 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001630 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001631 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001632 DeclContext *Ctx = ClassTemplate->getDeclContext();
1633 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001634 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001635 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001636 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001637 }
1638 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001639 }
1640
1641 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001642 case TemplateArgument::Integral:
1643 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001644 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001645 // associated namespaces. ]
1646 break;
Mike Stump11289f42009-09-09 15:08:12 +00001647
Douglas Gregor197e5f72009-07-08 07:51:57 +00001648 case TemplateArgument::Pack:
1649 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1650 PEnd = Arg.pack_end();
1651 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001652 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001653 break;
1654 }
1655}
1656
Douglas Gregore254f902009-02-04 00:32:51 +00001657// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001658// argument-dependent lookup with an argument of class type
1659// (C++ [basic.lookup.koenig]p2).
1660static void
John McCallf24d7bb2010-05-28 18:45:08 +00001661addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1662 CXXRecordDecl *Class) {
1663
1664 // Just silently ignore anything whose name is __va_list_tag.
1665 if (Class->getDeclName() == Result.S.VAListTagName)
1666 return;
1667
Douglas Gregore254f902009-02-04 00:32:51 +00001668 // C++ [basic.lookup.koenig]p2:
1669 // [...]
1670 // -- If T is a class type (including unions), its associated
1671 // classes are: the class itself; the class of which it is a
1672 // member, if any; and its direct and indirect base
1673 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001674 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001675
1676 // Add the class of which it is a member, if any.
1677 DeclContext *Ctx = Class->getDeclContext();
1678 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001679 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001680 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001681 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001682
Douglas Gregore254f902009-02-04 00:32:51 +00001683 // Add the class itself. If we've already seen this class, we don't
1684 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001685 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001686 return;
1687
Mike Stump11289f42009-09-09 15:08:12 +00001688 // -- If T is a template-id, its associated namespaces and classes are
1689 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001690 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001691 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001692 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001693 // namespaces in which any template template arguments are defined; and
1694 // the classes in which any member templates used as template template
1695 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001696 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001697 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001698 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1699 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1700 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001701 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001702 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001703 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001704
Douglas Gregor197e5f72009-07-08 07:51:57 +00001705 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1706 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001707 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001708 }
Mike Stump11289f42009-09-09 15:08:12 +00001709
John McCall67da35c2010-02-04 22:26:26 +00001710 // Only recurse into base classes for complete types.
1711 if (!Class->hasDefinition()) {
1712 // FIXME: we might need to instantiate templates here
1713 return;
1714 }
1715
Douglas Gregore254f902009-02-04 00:32:51 +00001716 // Add direct and indirect base classes along with their associated
1717 // namespaces.
1718 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1719 Bases.push_back(Class);
1720 while (!Bases.empty()) {
1721 // Pop this class off the stack.
1722 Class = Bases.back();
1723 Bases.pop_back();
1724
1725 // Visit the base classes.
1726 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1727 BaseEnd = Class->bases_end();
1728 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001729 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001730 // In dependent contexts, we do ADL twice, and the first time around,
1731 // the base type might be a dependent TemplateSpecializationType, or a
1732 // TemplateTypeParmType. If that happens, simply ignore it.
1733 // FIXME: If we want to support export, we probably need to add the
1734 // namespace of the template in a TemplateSpecializationType, or even
1735 // the classes and namespaces of known non-dependent arguments.
1736 if (!BaseType)
1737 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001738 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001739 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001740 // Find the associated namespace for this base class.
1741 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001742 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001743
1744 // Make sure we visit the bases of this base class.
1745 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1746 Bases.push_back(BaseDecl);
1747 }
1748 }
1749 }
1750}
1751
1752// \brief Add the associated classes and namespaces for
1753// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001754// (C++ [basic.lookup.koenig]p2).
1755static void
John McCallf24d7bb2010-05-28 18:45:08 +00001756addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001757 // C++ [basic.lookup.koenig]p2:
1758 //
1759 // For each argument type T in the function call, there is a set
1760 // of zero or more associated namespaces and a set of zero or more
1761 // associated classes to be considered. The sets of namespaces and
1762 // classes is determined entirely by the types of the function
1763 // arguments (and the namespace of any template template
1764 // argument). Typedef names and using-declarations used to specify
1765 // the types do not contribute to this set. The sets of namespaces
1766 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001767
John McCall0af3d3b2010-05-28 06:08:54 +00001768 llvm::SmallVector<const Type *, 16> Queue;
1769 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1770
Douglas Gregore254f902009-02-04 00:32:51 +00001771 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001772 switch (T->getTypeClass()) {
1773
1774#define TYPE(Class, Base)
1775#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1776#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1777#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1778#define ABSTRACT_TYPE(Class, Base)
1779#include "clang/AST/TypeNodes.def"
1780 // T is canonical. We can also ignore dependent types because
1781 // we don't need to do ADL at the definition point, but if we
1782 // wanted to implement template export (or if we find some other
1783 // use for associated classes and namespaces...) this would be
1784 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001785 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001786
John McCall0af3d3b2010-05-28 06:08:54 +00001787 // -- If T is a pointer to U or an array of U, its associated
1788 // namespaces and classes are those associated with U.
1789 case Type::Pointer:
1790 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1791 continue;
1792 case Type::ConstantArray:
1793 case Type::IncompleteArray:
1794 case Type::VariableArray:
1795 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1796 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001797
John McCall0af3d3b2010-05-28 06:08:54 +00001798 // -- If T is a fundamental type, its associated sets of
1799 // namespaces and classes are both empty.
1800 case Type::Builtin:
1801 break;
1802
1803 // -- If T is a class type (including unions), its associated
1804 // classes are: the class itself; the class of which it is a
1805 // member, if any; and its direct and indirect base
1806 // classes. Its associated namespaces are the namespaces in
1807 // which its associated classes are defined.
1808 case Type::Record: {
1809 CXXRecordDecl *Class
1810 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001811 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001812 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001813 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001814
John McCall0af3d3b2010-05-28 06:08:54 +00001815 // -- If T is an enumeration type, its associated namespace is
1816 // the namespace in which it is defined. If it is class
1817 // member, its associated class is the member’s class; else
1818 // it has no associated class.
1819 case Type::Enum: {
1820 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001821
John McCall0af3d3b2010-05-28 06:08:54 +00001822 DeclContext *Ctx = Enum->getDeclContext();
1823 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001824 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001825
John McCall0af3d3b2010-05-28 06:08:54 +00001826 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001827 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001828
John McCall0af3d3b2010-05-28 06:08:54 +00001829 break;
1830 }
1831
1832 // -- If T is a function type, its associated namespaces and
1833 // classes are those associated with the function parameter
1834 // types and those associated with the return type.
1835 case Type::FunctionProto: {
1836 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1837 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1838 ArgEnd = Proto->arg_type_end();
1839 Arg != ArgEnd; ++Arg)
1840 Queue.push_back(Arg->getTypePtr());
1841 // fallthrough
1842 }
1843 case Type::FunctionNoProto: {
1844 const FunctionType *FnType = cast<FunctionType>(T);
1845 T = FnType->getResultType().getTypePtr();
1846 continue;
1847 }
1848
1849 // -- If T is a pointer to a member function of a class X, its
1850 // associated namespaces and classes are those associated
1851 // with the function parameter types and return type,
1852 // together with those associated with X.
1853 //
1854 // -- If T is a pointer to a data member of class X, its
1855 // associated namespaces and classes are those associated
1856 // with the member type together with those associated with
1857 // X.
1858 case Type::MemberPointer: {
1859 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1860
1861 // Queue up the class type into which this points.
1862 Queue.push_back(MemberPtr->getClass());
1863
1864 // And directly continue with the pointee type.
1865 T = MemberPtr->getPointeeType().getTypePtr();
1866 continue;
1867 }
1868
1869 // As an extension, treat this like a normal pointer.
1870 case Type::BlockPointer:
1871 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1872 continue;
1873
1874 // References aren't covered by the standard, but that's such an
1875 // obvious defect that we cover them anyway.
1876 case Type::LValueReference:
1877 case Type::RValueReference:
1878 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1879 continue;
1880
1881 // These are fundamental types.
1882 case Type::Vector:
1883 case Type::ExtVector:
1884 case Type::Complex:
1885 break;
1886
1887 // These are ignored by ADL.
1888 case Type::ObjCObject:
1889 case Type::ObjCInterface:
1890 case Type::ObjCObjectPointer:
1891 break;
1892 }
1893
1894 if (Queue.empty()) break;
1895 T = Queue.back();
1896 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001897 }
Douglas Gregore254f902009-02-04 00:32:51 +00001898}
1899
1900/// \brief Find the associated classes and namespaces for
1901/// argument-dependent lookup for a call with the given set of
1902/// arguments.
1903///
1904/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001905/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001906/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001907void
Douglas Gregore254f902009-02-04 00:32:51 +00001908Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1909 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001910 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001911 AssociatedNamespaces.clear();
1912 AssociatedClasses.clear();
1913
John McCallf24d7bb2010-05-28 18:45:08 +00001914 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1915
Douglas Gregore254f902009-02-04 00:32:51 +00001916 // C++ [basic.lookup.koenig]p2:
1917 // For each argument type T in the function call, there is a set
1918 // of zero or more associated namespaces and a set of zero or more
1919 // associated classes to be considered. The sets of namespaces and
1920 // classes is determined entirely by the types of the function
1921 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001922 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001923 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1924 Expr *Arg = Args[ArgIdx];
1925
1926 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00001927 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001928 continue;
1929 }
1930
1931 // [...] In addition, if the argument is the name or address of a
1932 // set of overloaded functions and/or function templates, its
1933 // associated classes and namespaces are the union of those
1934 // associated with each of the members of the set: the namespace
1935 // in which the function or function template is defined and the
1936 // classes and namespaces associated with its (non-dependent)
1937 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001938 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001939 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1940 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1941 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001942
John McCallf24d7bb2010-05-28 18:45:08 +00001943 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1944 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00001945
John McCallf24d7bb2010-05-28 18:45:08 +00001946 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1947 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001948 // Look through any using declarations to find the underlying function.
1949 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001950
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001951 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1952 if (!FDecl)
1953 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001954
1955 // Add the classes and namespaces associated with the parameter
1956 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00001957 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001958 }
1959 }
1960}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001961
1962/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1963/// an acceptable non-member overloaded operator for a call whose
1964/// arguments have types T1 (and, if non-empty, T2). This routine
1965/// implements the check in C++ [over.match.oper]p3b2 concerning
1966/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001967static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001968IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1969 QualType T1, QualType T2,
1970 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001971 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1972 return true;
1973
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001974 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1975 return true;
1976
John McCall9dd450b2009-09-21 23:43:11 +00001977 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001978 if (Proto->getNumArgs() < 1)
1979 return false;
1980
1981 if (T1->isEnumeralType()) {
1982 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001983 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001984 return true;
1985 }
1986
1987 if (Proto->getNumArgs() < 2)
1988 return false;
1989
1990 if (!T2.isNull() && T2->isEnumeralType()) {
1991 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001992 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001993 return true;
1994 }
1995
1996 return false;
1997}
1998
John McCall5cebab12009-11-18 07:57:50 +00001999NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002000 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002001 LookupNameKind NameKind,
2002 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002003 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002004 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002005 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002006}
2007
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002008/// \brief Find the protocol with the given name, if any.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002009ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2010 SourceLocation IdLoc) {
2011 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2012 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002013 return cast_or_null<ObjCProtocolDecl>(D);
2014}
2015
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002016void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002017 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002018 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002019 // C++ [over.match.oper]p3:
2020 // -- The set of non-member candidates is the result of the
2021 // unqualified lookup of operator@ in the context of the
2022 // expression according to the usual rules for name lookup in
2023 // unqualified function calls (3.4.2) except that all member
2024 // functions are ignored. However, if no operand has a class
2025 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002026 // that have a first parameter of type T1 or "reference to
2027 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002028 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002029 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002030 // when T2 is an enumeration type, are candidate functions.
2031 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002032 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2033 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002034
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002035 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2036
John McCall9f3059a2009-10-09 21:13:30 +00002037 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002038 return;
2039
2040 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2041 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002042 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2043 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002044 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002045 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002046 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002047 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002048 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002049 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002050 // later?
2051 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002052 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002053 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002054 }
2055}
2056
Douglas Gregor52b72822010-07-02 23:12:18 +00002057/// \brief Look up the constructors for the given class.
2058DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +00002059 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002060 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2061 if (!Class->hasDeclaredDefaultConstructor())
2062 DeclareImplicitDefaultConstructor(Class);
2063 if (!Class->hasDeclaredCopyConstructor())
2064 DeclareImplicitCopyConstructor(Class);
2065 }
Douglas Gregora6d69502010-07-02 23:41:54 +00002066
Douglas Gregor52b72822010-07-02 23:12:18 +00002067 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2068 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2069 return Class->lookup(Name);
2070}
2071
Douglas Gregore71edda2010-07-01 22:47:18 +00002072/// \brief Look for the destructor of the given class.
2073///
2074/// During semantic analysis, this routine should be used in lieu of
2075/// CXXRecordDecl::getDestructor().
2076///
2077/// \returns The destructor for this class.
2078CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +00002079 // If the destructor has not yet been declared, do so now.
2080 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2081 !Class->hasDeclaredDestructor())
2082 DeclareImplicitDestructor(Class);
2083
Douglas Gregore71edda2010-07-01 22:47:18 +00002084 return Class->getDestructor();
2085}
2086
John McCall8fe68082010-01-26 07:16:45 +00002087void ADLResult::insert(NamedDecl *New) {
2088 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2089
2090 // If we haven't yet seen a decl for this key, or the last decl
2091 // was exactly this one, we're done.
2092 if (Old == 0 || Old == New) {
2093 Old = New;
2094 return;
2095 }
2096
2097 // Otherwise, decide which is a more recent redeclaration.
2098 FunctionDecl *OldFD, *NewFD;
2099 if (isa<FunctionTemplateDecl>(New)) {
2100 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2101 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2102 } else {
2103 OldFD = cast<FunctionDecl>(Old);
2104 NewFD = cast<FunctionDecl>(New);
2105 }
2106
2107 FunctionDecl *Cursor = NewFD;
2108 while (true) {
2109 Cursor = Cursor->getPreviousDeclaration();
2110
2111 // If we got to the end without finding OldFD, OldFD is the newer
2112 // declaration; leave things as they are.
2113 if (!Cursor) return;
2114
2115 // If we do find OldFD, then NewFD is newer.
2116 if (Cursor == OldFD) break;
2117
2118 // Otherwise, keep looking.
2119 }
2120
2121 Old = New;
2122}
2123
Sebastian Redlc057f422009-10-23 19:23:15 +00002124void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002125 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00002126 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002127 // Find all of the associated namespaces and classes based on the
2128 // arguments we have.
2129 AssociatedNamespaceSet AssociatedNamespaces;
2130 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002131 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002132 AssociatedNamespaces,
2133 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002134
Sebastian Redlc057f422009-10-23 19:23:15 +00002135 QualType T1, T2;
2136 if (Operator) {
2137 T1 = Args[0]->getType();
2138 if (NumArgs >= 2)
2139 T2 = Args[1]->getType();
2140 }
2141
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002142 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002143 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2144 // and let Y be the lookup set produced by argument dependent
2145 // lookup (defined as follows). If X contains [...] then Y is
2146 // empty. Otherwise Y is the set of declarations found in the
2147 // namespaces associated with the argument types as described
2148 // below. The set of declarations found by the lookup of the name
2149 // is the union of X and Y.
2150 //
2151 // Here, we compute Y and add its members to the overloaded
2152 // candidate set.
2153 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002154 NSEnd = AssociatedNamespaces.end();
2155 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002156 // When considering an associated namespace, the lookup is the
2157 // same as the lookup performed when the associated namespace is
2158 // used as a qualifier (3.4.3.2) except that:
2159 //
2160 // -- Any using-directives in the associated namespace are
2161 // ignored.
2162 //
John McCallc7e8e792009-08-07 22:18:02 +00002163 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002164 // associated classes are visible within their respective
2165 // namespaces even if they are not visible during an ordinary
2166 // lookup (11.4).
2167 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002168 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002169 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002170 // If the only declaration here is an ordinary friend, consider
2171 // it only if it was declared in an associated classes.
2172 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002173 DeclContext *LexDC = D->getLexicalDeclContext();
2174 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2175 continue;
2176 }
Mike Stump11289f42009-09-09 15:08:12 +00002177
John McCall91f61fc2010-01-26 06:04:06 +00002178 if (isa<UsingShadowDecl>(D))
2179 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002180
John McCall91f61fc2010-01-26 06:04:06 +00002181 if (isa<FunctionDecl>(D)) {
2182 if (Operator &&
2183 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2184 T1, T2, Context))
2185 continue;
John McCall8fe68082010-01-26 07:16:45 +00002186 } else if (!isa<FunctionTemplateDecl>(D))
2187 continue;
2188
2189 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002190 }
2191 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002192}
Douglas Gregor2d435302009-12-30 17:04:44 +00002193
2194//----------------------------------------------------------------------------
2195// Search for all visible declarations.
2196//----------------------------------------------------------------------------
2197VisibleDeclConsumer::~VisibleDeclConsumer() { }
2198
2199namespace {
2200
2201class ShadowContextRAII;
2202
2203class VisibleDeclsRecord {
2204public:
2205 /// \brief An entry in the shadow map, which is optimized to store a
2206 /// single declaration (the common case) but can also store a list
2207 /// of declarations.
2208 class ShadowMapEntry {
2209 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2210
2211 /// \brief Contains either the solitary NamedDecl * or a vector
2212 /// of declarations.
2213 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2214
2215 public:
2216 ShadowMapEntry() : DeclOrVector() { }
2217
2218 void Add(NamedDecl *ND);
2219 void Destroy();
2220
2221 // Iteration.
2222 typedef NamedDecl **iterator;
2223 iterator begin();
2224 iterator end();
2225 };
2226
2227private:
2228 /// \brief A mapping from declaration names to the declarations that have
2229 /// this name within a particular scope.
2230 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2231
2232 /// \brief A list of shadow maps, which is used to model name hiding.
2233 std::list<ShadowMap> ShadowMaps;
2234
2235 /// \brief The declaration contexts we have already visited.
2236 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2237
2238 friend class ShadowContextRAII;
2239
2240public:
2241 /// \brief Determine whether we have already visited this context
2242 /// (and, if not, note that we are going to visit that context now).
2243 bool visitedContext(DeclContext *Ctx) {
2244 return !VisitedContexts.insert(Ctx);
2245 }
2246
Douglas Gregor39982192010-08-15 06:18:01 +00002247 bool alreadyVisitedContext(DeclContext *Ctx) {
2248 return VisitedContexts.count(Ctx);
2249 }
2250
Douglas Gregor2d435302009-12-30 17:04:44 +00002251 /// \brief Determine whether the given declaration is hidden in the
2252 /// current scope.
2253 ///
2254 /// \returns the declaration that hides the given declaration, or
2255 /// NULL if no such declaration exists.
2256 NamedDecl *checkHidden(NamedDecl *ND);
2257
2258 /// \brief Add a declaration to the current shadow map.
2259 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2260};
2261
2262/// \brief RAII object that records when we've entered a shadow context.
2263class ShadowContextRAII {
2264 VisibleDeclsRecord &Visible;
2265
2266 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2267
2268public:
2269 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2270 Visible.ShadowMaps.push_back(ShadowMap());
2271 }
2272
2273 ~ShadowContextRAII() {
2274 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2275 EEnd = Visible.ShadowMaps.back().end();
2276 E != EEnd;
2277 ++E)
2278 E->second.Destroy();
2279
2280 Visible.ShadowMaps.pop_back();
2281 }
2282};
2283
2284} // end anonymous namespace
2285
2286void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2287 if (DeclOrVector.isNull()) {
2288 // 0 - > 1 elements: just set the single element information.
2289 DeclOrVector = ND;
2290 return;
2291 }
2292
2293 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2294 // 1 -> 2 elements: create the vector of results and push in the
2295 // existing declaration.
2296 DeclVector *Vec = new DeclVector;
2297 Vec->push_back(PrevND);
2298 DeclOrVector = Vec;
2299 }
2300
2301 // Add the new element to the end of the vector.
2302 DeclOrVector.get<DeclVector*>()->push_back(ND);
2303}
2304
2305void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2306 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2307 delete Vec;
2308 DeclOrVector = ((NamedDecl *)0);
2309 }
2310}
2311
2312VisibleDeclsRecord::ShadowMapEntry::iterator
2313VisibleDeclsRecord::ShadowMapEntry::begin() {
2314 if (DeclOrVector.isNull())
2315 return 0;
2316
2317 if (DeclOrVector.dyn_cast<NamedDecl *>())
2318 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2319
2320 return DeclOrVector.get<DeclVector *>()->begin();
2321}
2322
2323VisibleDeclsRecord::ShadowMapEntry::iterator
2324VisibleDeclsRecord::ShadowMapEntry::end() {
2325 if (DeclOrVector.isNull())
2326 return 0;
2327
2328 if (DeclOrVector.dyn_cast<NamedDecl *>())
2329 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2330
2331 return DeclOrVector.get<DeclVector *>()->end();
2332}
2333
2334NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002335 // Look through using declarations.
2336 ND = ND->getUnderlyingDecl();
2337
Douglas Gregor2d435302009-12-30 17:04:44 +00002338 unsigned IDNS = ND->getIdentifierNamespace();
2339 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2340 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2341 SM != SMEnd; ++SM) {
2342 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2343 if (Pos == SM->end())
2344 continue;
2345
2346 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2347 IEnd = Pos->second.end();
2348 I != IEnd; ++I) {
2349 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002350 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor2d435302009-12-30 17:04:44 +00002351 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2352 Decl::IDNS_ObjCProtocol)))
2353 continue;
2354
2355 // Protocols are in distinct namespaces from everything else.
2356 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2357 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2358 (*I)->getIdentifierNamespace() != IDNS)
2359 continue;
2360
Douglas Gregor09bbc652010-01-14 15:47:35 +00002361 // Functions and function templates in the same scope overload
2362 // rather than hide. FIXME: Look for hiding based on function
2363 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002364 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002365 ND->isFunctionOrFunctionTemplate() &&
2366 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002367 continue;
2368
Douglas Gregor2d435302009-12-30 17:04:44 +00002369 // We've found a declaration that hides this one.
2370 return *I;
2371 }
2372 }
2373
2374 return 0;
2375}
2376
2377static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2378 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002379 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002380 VisibleDeclConsumer &Consumer,
2381 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002382 if (!Ctx)
2383 return;
2384
Douglas Gregor2d435302009-12-30 17:04:44 +00002385 // Make sure we don't visit the same context twice.
2386 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2387 return;
2388
Douglas Gregor7454c562010-07-02 20:37:36 +00002389 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2390 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2391
Douglas Gregor2d435302009-12-30 17:04:44 +00002392 // Enumerate all of the results in this context.
2393 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2394 CurCtx = CurCtx->getNextContext()) {
2395 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2396 DEnd = CurCtx->decls_end();
2397 D != DEnd; ++D) {
2398 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2399 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002400 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002401 Visited.add(ND);
2402 }
2403
2404 // Visit transparent contexts inside this context.
2405 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2406 if (InnerCtx->isTransparentContext())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002407 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002408 Consumer, Visited);
2409 }
2410 }
2411 }
2412
2413 // Traverse using directives for qualified name lookup.
2414 if (QualifiedNameLookup) {
2415 ShadowContextRAII Shadow(Visited);
2416 DeclContext::udir_iterator I, E;
2417 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2418 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002419 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002420 }
2421 }
2422
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002423 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002424 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002425 if (!Record->hasDefinition())
2426 return;
2427
Douglas Gregor2d435302009-12-30 17:04:44 +00002428 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2429 BEnd = Record->bases_end();
2430 B != BEnd; ++B) {
2431 QualType BaseType = B->getType();
2432
2433 // Don't look into dependent bases, because name lookup can't look
2434 // there anyway.
2435 if (BaseType->isDependentType())
2436 continue;
2437
2438 const RecordType *Record = BaseType->getAs<RecordType>();
2439 if (!Record)
2440 continue;
2441
2442 // FIXME: It would be nice to be able to determine whether referencing
2443 // a particular member would be ambiguous. For example, given
2444 //
2445 // struct A { int member; };
2446 // struct B { int member; };
2447 // struct C : A, B { };
2448 //
2449 // void f(C *c) { c->### }
2450 //
2451 // accessing 'member' would result in an ambiguity. However, we
2452 // could be smart enough to qualify the member with the base
2453 // class, e.g.,
2454 //
2455 // c->B::member
2456 //
2457 // or
2458 //
2459 // c->A::member
2460
2461 // Find results in this base class (and its bases).
2462 ShadowContextRAII Shadow(Visited);
2463 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002464 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002465 }
2466 }
2467
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002468 // Traverse the contexts of Objective-C classes.
2469 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2470 // Traverse categories.
2471 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2472 Category; Category = Category->getNextClassCategory()) {
2473 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002474 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2475 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002476 }
2477
2478 // Traverse protocols.
2479 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2480 E = IFace->protocol_end(); I != E; ++I) {
2481 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002482 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2483 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002484 }
2485
2486 // Traverse the superclass.
2487 if (IFace->getSuperClass()) {
2488 ShadowContextRAII Shadow(Visited);
2489 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002490 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002491 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002492
2493 // If there is an implementation, traverse it. We do this to find
2494 // synthesized ivars.
2495 if (IFace->getImplementation()) {
2496 ShadowContextRAII Shadow(Visited);
2497 LookupVisibleDecls(IFace->getImplementation(), Result,
2498 QualifiedNameLookup, true, Consumer, Visited);
2499 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002500 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2501 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2502 E = Protocol->protocol_end(); I != E; ++I) {
2503 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002504 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2505 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002506 }
2507 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2508 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2509 E = Category->protocol_end(); I != E; ++I) {
2510 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002511 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2512 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002513 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002514
2515 // If there is an implementation, traverse it.
2516 if (Category->getImplementation()) {
2517 ShadowContextRAII Shadow(Visited);
2518 LookupVisibleDecls(Category->getImplementation(), Result,
2519 QualifiedNameLookup, true, Consumer, Visited);
2520 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002521 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002522}
2523
2524static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2525 UnqualUsingDirectiveSet &UDirs,
2526 VisibleDeclConsumer &Consumer,
2527 VisibleDeclsRecord &Visited) {
2528 if (!S)
2529 return;
2530
Douglas Gregor39982192010-08-15 06:18:01 +00002531 if (!S->getEntity() ||
2532 (!S->getParent() &&
2533 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002534 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2535 // Walk through the declarations in this Scope.
2536 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2537 D != DEnd; ++D) {
2538 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2539 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002540 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002541 Visited.add(ND);
2542 }
2543 }
2544 }
2545
Douglas Gregor66230062010-03-15 14:33:29 +00002546 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002547 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002548 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002549 // Look into this scope's declaration context, along with any of its
2550 // parent lookup contexts (e.g., enclosing classes), up to the point
2551 // where we hit the context stored in the next outer scope.
2552 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002553 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor2d435302009-12-30 17:04:44 +00002554
Douglas Gregorea166062010-03-15 15:26:48 +00002555 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002556 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002557 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2558 if (Method->isInstanceMethod()) {
2559 // For instance methods, look for ivars in the method's interface.
2560 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2561 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002562 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2563 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2564 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002565 }
2566
2567 // We've already performed all of the name lookup that we need
2568 // to for Objective-C methods; the next context will be the
2569 // outer scope.
2570 break;
2571 }
2572
Douglas Gregor2d435302009-12-30 17:04:44 +00002573 if (Ctx->isFunctionOrMethod())
2574 continue;
2575
2576 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002577 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002578 }
2579 } else if (!S->getParent()) {
2580 // Look into the translation unit scope. We walk through the translation
2581 // unit's declaration context, because the Scope itself won't have all of
2582 // the declarations if we loaded a precompiled header.
2583 // FIXME: We would like the translation unit's Scope object to point to the
2584 // translation unit, so we don't need this special "if" branch. However,
2585 // doing so would force the normal C++ name-lookup code to look into the
2586 // translation unit decl when the IdentifierInfo chains would suffice.
2587 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002588 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002589 Entity = Result.getSema().Context.getTranslationUnitDecl();
2590 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002591 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002592 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002593
2594 if (Entity) {
2595 // Lookup visible declarations in any namespaces found by using
2596 // directives.
2597 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2598 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2599 for (; UI != UEnd; ++UI)
2600 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002601 Result, /*QualifiedNameLookup=*/false,
2602 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002603 }
2604
2605 // Lookup names in the parent scope.
2606 ShadowContextRAII Shadow(Visited);
2607 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2608}
2609
2610void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002611 VisibleDeclConsumer &Consumer,
2612 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002613 // Determine the set of using directives available during
2614 // unqualified name lookup.
2615 Scope *Initial = S;
2616 UnqualUsingDirectiveSet UDirs;
2617 if (getLangOptions().CPlusPlus) {
2618 // Find the first namespace or translation-unit scope.
2619 while (S && !isNamespaceOrTranslationUnitScope(S))
2620 S = S->getParent();
2621
2622 UDirs.visitScopeChain(Initial, S);
2623 }
2624 UDirs.done();
2625
2626 // Look for visible declarations.
2627 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2628 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002629 if (!IncludeGlobalScope)
2630 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002631 ShadowContextRAII Shadow(Visited);
2632 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2633}
2634
2635void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002636 VisibleDeclConsumer &Consumer,
2637 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002638 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2639 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002640 if (!IncludeGlobalScope)
2641 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002642 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002643 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2644 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002645}
2646
2647//----------------------------------------------------------------------------
2648// Typo correction
2649//----------------------------------------------------------------------------
2650
2651namespace {
2652class TypoCorrectionConsumer : public VisibleDeclConsumer {
2653 /// \brief The name written that is a typo in the source.
2654 llvm::StringRef Typo;
2655
2656 /// \brief The results found that have the smallest edit distance
2657 /// found (so far) with the typo name.
2658 llvm::SmallVector<NamedDecl *, 4> BestResults;
2659
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002660 /// \brief The keywords that have the smallest edit distance.
2661 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2662
Douglas Gregor2d435302009-12-30 17:04:44 +00002663 /// \brief The best edit distance found so far.
2664 unsigned BestEditDistance;
2665
2666public:
2667 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2668 : Typo(Typo->getName()) { }
2669
Douglas Gregor09bbc652010-01-14 15:47:35 +00002670 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002671 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002672
2673 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2674 iterator begin() const { return BestResults.begin(); }
2675 iterator end() const { return BestResults.end(); }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002676 void clear_decls() { BestResults.clear(); }
2677
2678 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002679
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002680 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2681 keyword_iterator;
2682 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2683 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2684 bool keyword_empty() const { return BestKeywords.empty(); }
2685 unsigned keyword_size() const { return BestKeywords.size(); }
2686
2687 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002688};
2689
2690}
2691
Douglas Gregor09bbc652010-01-14 15:47:35 +00002692void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2693 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002694 // Don't consider hidden names for typo correction.
2695 if (Hiding)
2696 return;
2697
2698 // Only consider entities with identifiers for names, ignoring
2699 // special names (constructors, overloaded operators, selectors,
2700 // etc.).
2701 IdentifierInfo *Name = ND->getIdentifier();
2702 if (!Name)
2703 return;
2704
2705 // Compute the edit distance between the typo and the name of this
2706 // entity. If this edit distance is not worse than the best edit
2707 // distance we've seen so far, add it to the list of results.
2708 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002709 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002710 if (ED < BestEditDistance) {
2711 // This result is better than any we've seen before; clear out
2712 // the previous results.
2713 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002714 BestKeywords.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002715 BestEditDistance = ED;
2716 } else if (ED > BestEditDistance) {
2717 // This result is worse than the best results we've seen so far;
2718 // ignore it.
2719 return;
2720 }
2721 } else
2722 BestEditDistance = ED;
2723
2724 BestResults.push_back(ND);
2725}
2726
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002727void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2728 llvm::StringRef Keyword) {
2729 // Compute the edit distance between the typo and this keyword.
2730 // If this edit distance is not worse than the best edit
2731 // distance we've seen so far, add it to the list of results.
2732 unsigned ED = Typo.edit_distance(Keyword);
2733 if (!BestResults.empty() || !BestKeywords.empty()) {
2734 if (ED < BestEditDistance) {
2735 BestResults.clear();
2736 BestKeywords.clear();
2737 BestEditDistance = ED;
2738 } else if (ED > BestEditDistance) {
2739 // This result is worse than the best results we've seen so far;
2740 // ignore it.
2741 return;
2742 }
2743 } else
2744 BestEditDistance = ED;
2745
2746 BestKeywords.push_back(&Context.Idents.get(Keyword));
2747}
2748
Douglas Gregor2d435302009-12-30 17:04:44 +00002749/// \brief Try to "correct" a typo in the source code by finding
2750/// visible declarations whose names are similar to the name that was
2751/// present in the source code.
2752///
2753/// \param Res the \c LookupResult structure that contains the name
2754/// that was present in the source code along with the name-lookup
2755/// criteria used to search for the name. On success, this structure
2756/// will contain the results of name lookup.
2757///
2758/// \param S the scope in which name lookup occurs.
2759///
2760/// \param SS the nested-name-specifier that precedes the name we're
2761/// looking for, if present.
2762///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002763/// \param MemberContext if non-NULL, the context in which to look for
2764/// a member access expression.
2765///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002766/// \param EnteringContext whether we're entering the context described by
2767/// the nested-name-specifier SS.
2768///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002769/// \param CTC The context in which typo correction occurs, which impacts the
2770/// set of keywords permitted.
2771///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002772/// \param OPT when non-NULL, the search for visible declarations will
2773/// also walk the protocols in the qualified interfaces of \p OPT.
2774///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002775/// \returns the corrected name if the typo was corrected, otherwise returns an
2776/// empty \c DeclarationName. When a typo was corrected, the result structure
2777/// may contain the results of name lookup for the correct name or it may be
2778/// empty.
2779DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002780 DeclContext *MemberContext,
2781 bool EnteringContext,
2782 CorrectTypoContext CTC,
2783 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00002784 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002785 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002786
2787 // Provide a stop gap for files that are just seriously broken. Trying
2788 // to correct all typos can turn into a HUGE performance penalty, causing
2789 // some files to take minutes to get rejected by the parser.
2790 // FIXME: Is this the right solution?
2791 if (TyposCorrected == 20)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002792 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002793 ++TyposCorrected;
Ted Kremeneke51136e2010-01-06 00:23:04 +00002794
Douglas Gregor2d435302009-12-30 17:04:44 +00002795 // We only attempt to correct typos for identifiers.
2796 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2797 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002798 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002799
2800 // If the scope specifier itself was invalid, don't try to correct
2801 // typos.
2802 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002803 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002804
2805 // Never try to correct typos during template deduction or
2806 // instantiation.
2807 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002808 return DeclarationName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002809
Douglas Gregor2d435302009-12-30 17:04:44 +00002810 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002811
2812 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002813 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002814 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002815
2816 // Look in qualified interfaces.
2817 if (OPT) {
2818 for (ObjCObjectPointerType::qual_iterator
2819 I = OPT->qual_begin(), E = OPT->qual_end();
2820 I != E; ++I)
2821 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2822 }
2823 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002824 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2825 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002826 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002827
2828 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2829 } else {
2830 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2831 }
2832
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002833 // Add context-dependent keywords.
2834 bool WantTypeSpecifiers = false;
2835 bool WantExpressionKeywords = false;
2836 bool WantCXXNamedCasts = false;
2837 bool WantRemainingKeywords = false;
2838 switch (CTC) {
2839 case CTC_Unknown:
2840 WantTypeSpecifiers = true;
2841 WantExpressionKeywords = true;
2842 WantCXXNamedCasts = true;
2843 WantRemainingKeywords = true;
Douglas Gregor5fd04d42010-05-18 16:14:23 +00002844
2845 if (ObjCMethodDecl *Method = getCurMethodDecl())
2846 if (Method->getClassInterface() &&
2847 Method->getClassInterface()->getSuperClass())
2848 Consumer.addKeywordResult(Context, "super");
2849
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002850 break;
2851
2852 case CTC_NoKeywords:
2853 break;
2854
2855 case CTC_Type:
2856 WantTypeSpecifiers = true;
2857 break;
2858
2859 case CTC_ObjCMessageReceiver:
2860 Consumer.addKeywordResult(Context, "super");
2861 // Fall through to handle message receivers like expressions.
2862
2863 case CTC_Expression:
2864 if (getLangOptions().CPlusPlus)
2865 WantTypeSpecifiers = true;
2866 WantExpressionKeywords = true;
2867 // Fall through to get C++ named casts.
2868
2869 case CTC_CXXCasts:
2870 WantCXXNamedCasts = true;
2871 break;
2872
2873 case CTC_MemberLookup:
2874 if (getLangOptions().CPlusPlus)
2875 Consumer.addKeywordResult(Context, "template");
2876 break;
2877 }
2878
2879 if (WantTypeSpecifiers) {
2880 // Add type-specifier keywords to the set of results.
2881 const char *CTypeSpecs[] = {
2882 "char", "const", "double", "enum", "float", "int", "long", "short",
2883 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2884 "_Complex", "_Imaginary",
2885 // storage-specifiers as well
2886 "extern", "inline", "static", "typedef"
2887 };
2888
2889 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2890 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2891 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2892
2893 if (getLangOptions().C99)
2894 Consumer.addKeywordResult(Context, "restrict");
2895 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2896 Consumer.addKeywordResult(Context, "bool");
2897
2898 if (getLangOptions().CPlusPlus) {
2899 Consumer.addKeywordResult(Context, "class");
2900 Consumer.addKeywordResult(Context, "typename");
2901 Consumer.addKeywordResult(Context, "wchar_t");
2902
2903 if (getLangOptions().CPlusPlus0x) {
2904 Consumer.addKeywordResult(Context, "char16_t");
2905 Consumer.addKeywordResult(Context, "char32_t");
2906 Consumer.addKeywordResult(Context, "constexpr");
2907 Consumer.addKeywordResult(Context, "decltype");
2908 Consumer.addKeywordResult(Context, "thread_local");
2909 }
2910 }
2911
2912 if (getLangOptions().GNUMode)
2913 Consumer.addKeywordResult(Context, "typeof");
2914 }
2915
Douglas Gregor86ad0852010-05-18 16:30:22 +00002916 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002917 Consumer.addKeywordResult(Context, "const_cast");
2918 Consumer.addKeywordResult(Context, "dynamic_cast");
2919 Consumer.addKeywordResult(Context, "reinterpret_cast");
2920 Consumer.addKeywordResult(Context, "static_cast");
2921 }
2922
2923 if (WantExpressionKeywords) {
2924 Consumer.addKeywordResult(Context, "sizeof");
2925 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2926 Consumer.addKeywordResult(Context, "false");
2927 Consumer.addKeywordResult(Context, "true");
2928 }
2929
2930 if (getLangOptions().CPlusPlus) {
2931 const char *CXXExprs[] = {
2932 "delete", "new", "operator", "throw", "typeid"
2933 };
2934 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2935 for (unsigned I = 0; I != NumCXXExprs; ++I)
2936 Consumer.addKeywordResult(Context, CXXExprs[I]);
2937
2938 if (isa<CXXMethodDecl>(CurContext) &&
2939 cast<CXXMethodDecl>(CurContext)->isInstance())
2940 Consumer.addKeywordResult(Context, "this");
2941
2942 if (getLangOptions().CPlusPlus0x) {
2943 Consumer.addKeywordResult(Context, "alignof");
2944 Consumer.addKeywordResult(Context, "nullptr");
2945 }
2946 }
2947 }
2948
2949 if (WantRemainingKeywords) {
2950 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2951 // Statements.
2952 const char *CStmts[] = {
2953 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2954 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2955 for (unsigned I = 0; I != NumCStmts; ++I)
2956 Consumer.addKeywordResult(Context, CStmts[I]);
2957
2958 if (getLangOptions().CPlusPlus) {
2959 Consumer.addKeywordResult(Context, "catch");
2960 Consumer.addKeywordResult(Context, "try");
2961 }
2962
2963 if (S && S->getBreakParent())
2964 Consumer.addKeywordResult(Context, "break");
2965
2966 if (S && S->getContinueParent())
2967 Consumer.addKeywordResult(Context, "continue");
2968
2969 if (!getSwitchStack().empty()) {
2970 Consumer.addKeywordResult(Context, "case");
2971 Consumer.addKeywordResult(Context, "default");
2972 }
2973 } else {
2974 if (getLangOptions().CPlusPlus) {
2975 Consumer.addKeywordResult(Context, "namespace");
2976 Consumer.addKeywordResult(Context, "template");
2977 }
2978
2979 if (S && S->isClassScope()) {
2980 Consumer.addKeywordResult(Context, "explicit");
2981 Consumer.addKeywordResult(Context, "friend");
2982 Consumer.addKeywordResult(Context, "mutable");
2983 Consumer.addKeywordResult(Context, "private");
2984 Consumer.addKeywordResult(Context, "protected");
2985 Consumer.addKeywordResult(Context, "public");
2986 Consumer.addKeywordResult(Context, "virtual");
2987 }
2988 }
2989
2990 if (getLangOptions().CPlusPlus) {
2991 Consumer.addKeywordResult(Context, "using");
2992
2993 if (getLangOptions().CPlusPlus0x)
2994 Consumer.addKeywordResult(Context, "static_assert");
2995 }
2996 }
2997
2998 // If we haven't found anything, we're done.
Douglas Gregor2d435302009-12-30 17:04:44 +00002999 if (Consumer.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003000 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003001
3002 // Only allow a single, closest name in the result set (it's okay to
3003 // have overloads of that name, though).
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003004 DeclarationName BestName;
3005 NamedDecl *BestIvarOrPropertyDecl = 0;
3006 bool FoundIvarOrPropertyDecl = false;
3007
3008 // Check all of the declaration results to find the best name so far.
3009 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3010 IEnd = Consumer.end();
3011 I != IEnd; ++I) {
3012 if (!BestName)
3013 BestName = (*I)->getDeclName();
3014 else if (BestName != (*I)->getDeclName())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003015 return DeclarationName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003016
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003017 // \brief Keep track of either an Objective-C ivar or a property, but not
3018 // both.
3019 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
3020 if (FoundIvarOrPropertyDecl)
3021 BestIvarOrPropertyDecl = 0;
3022 else {
3023 BestIvarOrPropertyDecl = *I;
3024 FoundIvarOrPropertyDecl = true;
3025 }
3026 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003027 }
3028
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003029 // Now check all of the keyword results to find the best name.
3030 switch (Consumer.keyword_size()) {
3031 case 0:
3032 // No keywords matched.
3033 break;
3034
3035 case 1:
3036 // If we already have a name
3037 if (!BestName) {
3038 // We did not have anything previously,
3039 BestName = *Consumer.keyword_begin();
3040 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
3041 // We have a declaration with the same name as a context-sensitive
3042 // keyword. The keyword takes precedence.
3043 BestIvarOrPropertyDecl = 0;
3044 FoundIvarOrPropertyDecl = false;
3045 Consumer.clear_decls();
Douglas Gregor86ad0852010-05-18 16:30:22 +00003046 } else if (CTC == CTC_ObjCMessageReceiver &&
3047 (*Consumer.keyword_begin())->isStr("super")) {
3048 // In an Objective-C message send, give the "super" keyword a slight
3049 // edge over entities not in function or method scope.
3050 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3051 IEnd = Consumer.end();
3052 I != IEnd; ++I) {
3053 if ((*I)->getDeclName() == BestName) {
3054 if ((*I)->getDeclContext()->isFunctionOrMethod())
3055 return DeclarationName();
3056 }
3057 }
3058
3059 // Everything found was outside a function or method; the 'super'
3060 // keyword takes precedence.
3061 BestIvarOrPropertyDecl = 0;
3062 FoundIvarOrPropertyDecl = false;
3063 Consumer.clear_decls();
3064 BestName = *Consumer.keyword_begin();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003065 } else {
3066 // Name collision; we will not correct typos.
3067 return DeclarationName();
3068 }
3069 break;
3070
3071 default:
3072 // Name collision; we will not correct typos.
3073 return DeclarationName();
3074 }
3075
Douglas Gregor2d435302009-12-30 17:04:44 +00003076 // BestName is the closest viable name to what the user
3077 // typed. However, to make sure that we don't pick something that's
3078 // way off, make sure that the user typed at least 3 characters for
3079 // each correction.
3080 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003081 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
3082 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003083 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003084
3085 // Perform name lookup again with the name we chose, and declare
3086 // success if we found something that was not ambiguous.
3087 Res.clear();
3088 Res.setLookupName(BestName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003089
3090 // If we found an ivar or property, add that result; no further
3091 // lookup is required.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003092 if (BestIvarOrPropertyDecl)
3093 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003094 // If we're looking into the context of a member, perform qualified
3095 // name lookup on the best name.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003096 else if (!Consumer.keyword_empty()) {
3097 // The best match was a keyword. Return it.
3098 return BestName;
3099 } else if (MemberContext)
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003100 LookupQualifiedName(Res, MemberContext);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003101 // Perform lookup as if we had just parsed the best name.
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003102 else
3103 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3104 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00003105
3106 if (Res.isAmbiguous()) {
3107 Res.suppressDiagnostics();
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003108 return DeclarationName();
Douglas Gregor598b08f2009-12-31 05:20:13 +00003109 }
3110
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003111 if (Res.getResultKind() != LookupResult::NotFound)
3112 return BestName;
3113
3114 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003115}