blob: 8307d2f5f106a7a41ad88925b07bcfc13162980e [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"
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/DeclSpec.h"
John McCallcc14d1f2010-08-24 08:50:51 +000017#include "clang/Sema/Scope.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000020#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000023#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000024#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000025#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000027#include "clang/Basic/LangOptions.h"
28#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000029#include "llvm/ADT/SmallPtrSet.h"
John McCall6538c932009-10-10 05:48:19 +000030#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2d435302009-12-30 17:04:44 +000031#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000032#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000033#include <vector>
34#include <iterator>
35#include <utility>
36#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000037
38using namespace clang;
39
John McCallf6c8a4e2009-11-10 07:01:13 +000040namespace {
41 class UnqualUsingEntry {
42 const DeclContext *Nominated;
43 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000044
John McCallf6c8a4e2009-11-10 07:01:13 +000045 public:
46 UnqualUsingEntry(const DeclContext *Nominated,
47 const DeclContext *CommonAncestor)
48 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
49 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000050
John McCallf6c8a4e2009-11-10 07:01:13 +000051 const DeclContext *getCommonAncestor() const {
52 return CommonAncestor;
53 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000054
John McCallf6c8a4e2009-11-10 07:01:13 +000055 const DeclContext *getNominatedNamespace() const {
56 return Nominated;
57 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000058
John McCallf6c8a4e2009-11-10 07:01:13 +000059 // Sort by the pointer value of the common ancestor.
60 struct Comparator {
61 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
62 return L.getCommonAncestor() < R.getCommonAncestor();
63 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000064
John McCallf6c8a4e2009-11-10 07:01:13 +000065 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
66 return E.getCommonAncestor() < DC;
67 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000068
John McCallf6c8a4e2009-11-10 07:01:13 +000069 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
70 return DC < E.getCommonAncestor();
71 }
72 };
73 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000074
John McCallf6c8a4e2009-11-10 07:01:13 +000075 /// A collection of using directives, as used by C++ unqualified
76 /// lookup.
77 class UnqualUsingDirectiveSet {
78 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000079
John McCallf6c8a4e2009-11-10 07:01:13 +000080 ListTy list;
81 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000082
John McCallf6c8a4e2009-11-10 07:01:13 +000083 public:
84 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000085
John McCallf6c8a4e2009-11-10 07:01:13 +000086 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
87 // C++ [namespace.udir]p1:
88 // During unqualified name lookup, the names appear as if they
89 // were declared in the nearest enclosing namespace which contains
90 // both the using-directive and the nominated namespace.
91 DeclContext *InnermostFileDC
92 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
93 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000094
John McCallf6c8a4e2009-11-10 07:01:13 +000095 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +000096 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
97 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
98 visit(Ctx, EffectiveDC);
99 } else {
100 Scope::udir_iterator I = S->using_directives_begin(),
101 End = S->using_directives_end();
102
103 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000104 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000105 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000106 }
107 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000108
109 // Visits a context and collect all of its using directives
110 // recursively. Treats all using directives as if they were
111 // declared in the context.
112 //
113 // A given context is only every visited once, so it is important
114 // that contexts be visited from the inside out in order to get
115 // the effective DCs right.
116 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
117 if (!visited.insert(DC))
118 return;
119
120 addUsingDirectives(DC, EffectiveDC);
121 }
122
123 // Visits a using directive and collects all of its using
124 // directives recursively. Treats all using directives as if they
125 // were declared in the effective DC.
126 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
127 DeclContext *NS = UD->getNominatedNamespace();
128 if (!visited.insert(NS))
129 return;
130
131 addUsingDirective(UD, EffectiveDC);
132 addUsingDirectives(NS, EffectiveDC);
133 }
134
135 // Adds all the using directives in a context (and those nominated
136 // by its using directives, transitively) as if they appeared in
137 // the given effective context.
138 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
139 llvm::SmallVector<DeclContext*,4> queue;
140 while (true) {
141 DeclContext::udir_iterator I, End;
142 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
143 UsingDirectiveDecl *UD = *I;
144 DeclContext *NS = UD->getNominatedNamespace();
145 if (visited.insert(NS)) {
146 addUsingDirective(UD, EffectiveDC);
147 queue.push_back(NS);
148 }
149 }
150
151 if (queue.empty())
152 return;
153
154 DC = queue.back();
155 queue.pop_back();
156 }
157 }
158
159 // Add a using directive as if it had been declared in the given
160 // context. This helps implement C++ [namespace.udir]p3:
161 // The using-directive is transitive: if a scope contains a
162 // using-directive that nominates a second namespace that itself
163 // contains using-directives, the effect is as if the
164 // using-directives from the second namespace also appeared in
165 // the first.
166 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
167 // Find the common ancestor between the effective context and
168 // the nominated namespace.
169 DeclContext *Common = UD->getNominatedNamespace();
170 while (!Common->Encloses(EffectiveDC))
171 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000172 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000173
174 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
175 }
176
177 void done() {
178 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
179 }
180
181 typedef ListTy::iterator iterator;
182 typedef ListTy::const_iterator const_iterator;
183
184 iterator begin() { return list.begin(); }
185 iterator end() { return list.end(); }
186 const_iterator begin() const { return list.begin(); }
187 const_iterator end() const { return list.end(); }
188
189 std::pair<const_iterator,const_iterator>
190 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000191 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000192 UnqualUsingEntry::Comparator());
193 }
194 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000195}
196
Douglas Gregor889ceb72009-02-03 19:21:40 +0000197// Retrieve the set of identifier namespaces that correspond to a
198// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000199static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
200 bool CPlusPlus,
201 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000202 unsigned IDNS = 0;
203 switch (NameKind) {
204 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000205 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000207 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000208 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCallea305ed2009-12-18 10:40:03 +0000209 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
210 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000211 break;
212
John McCallb9467b62010-04-24 01:30:58 +0000213 case Sema::LookupOperatorName:
214 // Operator lookup is its own crazy thing; it is not the same
215 // as (e.g.) looking up an operator name for redeclaration.
216 assert(!Redeclaration && "cannot do redeclaration operator lookup");
217 IDNS = Decl::IDNS_NonMemberOperator;
218 break;
219
Douglas Gregor889ceb72009-02-03 19:21:40 +0000220 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000221 if (CPlusPlus) {
222 IDNS = Decl::IDNS_Type;
223
224 // When looking for a redeclaration of a tag name, we add:
225 // 1) TagFriend to find undeclared friend decls
226 // 2) Namespace because they can't "overload" with tag decls.
227 // 3) Tag because it includes class templates, which can't
228 // "overload" with tag decls.
229 if (Redeclaration)
230 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
231 } else {
232 IDNS = Decl::IDNS_Tag;
233 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000234 break;
235
236 case Sema::LookupMemberName:
237 IDNS = Decl::IDNS_Member;
238 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000239 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000240 break;
241
242 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000243 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
244 break;
245
Douglas Gregor889ceb72009-02-03 19:21:40 +0000246 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000247 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000248 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000249
John McCall84d87672009-12-10 09:41:52 +0000250 case Sema::LookupUsingDeclName:
251 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
252 | Decl::IDNS_Member | Decl::IDNS_Using;
253 break;
254
Douglas Gregor79947a22009-04-24 00:11:27 +0000255 case Sema::LookupObjCProtocolName:
256 IDNS = Decl::IDNS_ObjCProtocol;
257 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000258
259 case Sema::LookupAnyName:
260 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
261 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
262 | Decl::IDNS_Type;
263 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000264 }
265 return IDNS;
266}
267
John McCallea305ed2009-12-18 10:40:03 +0000268void LookupResult::configure() {
269 IDNS = getIDNS(LookupKind,
270 SemaRef.getLangOptions().CPlusPlus,
271 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000272
273 // If we're looking for one of the allocation or deallocation
274 // operators, make sure that the implicitly-declared new and delete
275 // operators can be found.
276 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000277 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000278 case OO_New:
279 case OO_Delete:
280 case OO_Array_New:
281 case OO_Array_Delete:
282 SemaRef.DeclareGlobalNewDelete();
283 break;
284
285 default:
286 break;
287 }
288 }
John McCallea305ed2009-12-18 10:40:03 +0000289}
290
John McCall9f3059a2009-10-09 21:13:30 +0000291// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000292void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000293 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000294}
295
John McCall283b9012009-11-22 00:44:51 +0000296/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000297void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000298 unsigned N = Decls.size();
John McCall84d87672009-12-10 09:41:52 +0000299
John McCall9f3059a2009-10-09 21:13:30 +0000300 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000301 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000302 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000303 return;
304 }
305
John McCall283b9012009-11-22 00:44:51 +0000306 // If there's a single decl, we need to examine it to decide what
307 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000308 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000309 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
310 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000311 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000312 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000313 ResultKind = FoundUnresolvedValue;
314 return;
315 }
John McCall9f3059a2009-10-09 21:13:30 +0000316
John McCall6538c932009-10-10 05:48:19 +0000317 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000318 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000319
John McCall9f3059a2009-10-09 21:13:30 +0000320 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000321 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
322
John McCall9f3059a2009-10-09 21:13:30 +0000323 bool Ambiguous = false;
324 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000325 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000326
327 unsigned UniqueTagIndex = 0;
328
329 unsigned I = 0;
330 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000331 NamedDecl *D = Decls[I]->getUnderlyingDecl();
332 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000333
Douglas Gregor13e65872010-08-11 14:45:53 +0000334 // Redeclarations of types via typedef can occur both within a scope
335 // and, through using declarations and directives, across scopes. There is
336 // no ambiguity if they all refer to the same type, so unique based on the
337 // canonical type.
338 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
339 if (!TD->getDeclContext()->isRecord()) {
340 QualType T = SemaRef.Context.getTypeDeclType(TD);
341 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
342 // The type is not unique; pull something off the back and continue
343 // at this index.
344 Decls[I] = Decls[--N];
345 continue;
346 }
347 }
348 }
349
John McCallf0f1cf02009-11-17 07:50:12 +0000350 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000351 // If it's not unique, pull something off the back (and
352 // continue at this index).
353 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000354 continue;
355 }
356
357 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000358
Douglas Gregor13e65872010-08-11 14:45:53 +0000359 if (isa<UnresolvedUsingValueDecl>(D)) {
360 HasUnresolved = true;
361 } else if (isa<TagDecl>(D)) {
362 if (HasTag)
363 Ambiguous = true;
364 UniqueTagIndex = I;
365 HasTag = true;
366 } else if (isa<FunctionTemplateDecl>(D)) {
367 HasFunction = true;
368 HasFunctionTemplate = true;
369 } else if (isa<FunctionDecl>(D)) {
370 HasFunction = true;
371 } else {
372 if (HasNonFunction)
373 Ambiguous = true;
374 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000375 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000376 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000377 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000378
John McCall9f3059a2009-10-09 21:13:30 +0000379 // C++ [basic.scope.hiding]p2:
380 // A class name or enumeration name can be hidden by the name of
381 // an object, function, or enumerator declared in the same
382 // scope. If a class or enumeration name and an object, function,
383 // or enumerator are declared in the same scope (in any order)
384 // with the same name, the class or enumeration name is hidden
385 // wherever the object, function, or enumerator name is visible.
386 // But it's still an error if there are distinct tag types found,
387 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000388 if (HideTags && HasTag && !Ambiguous &&
389 (HasFunction || HasNonFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000390 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000391
John McCall9f3059a2009-10-09 21:13:30 +0000392 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000393
John McCall80053822009-12-03 00:58:24 +0000394 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000395 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000396
John McCall9f3059a2009-10-09 21:13:30 +0000397 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000398 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000399 else if (HasUnresolved)
400 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000401 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000402 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000403 else
John McCall27b18f82009-11-17 02:14:36 +0000404 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000405}
406
John McCall5cebab12009-11-18 07:57:50 +0000407void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000408 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000409 DeclContext::lookup_iterator DI, DE;
410 for (I = P.begin(), E = P.end(); I != E; ++I)
411 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
412 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000413}
414
John McCall5cebab12009-11-18 07:57:50 +0000415void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000416 Paths = new CXXBasePaths;
417 Paths->swap(P);
418 addDeclsFromBasePaths(*Paths);
419 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000420 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000421}
422
John McCall5cebab12009-11-18 07:57:50 +0000423void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000424 Paths = new CXXBasePaths;
425 Paths->swap(P);
426 addDeclsFromBasePaths(*Paths);
427 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000428 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000429}
430
John McCall5cebab12009-11-18 07:57:50 +0000431void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000432 Out << Decls.size() << " result(s)";
433 if (isAmbiguous()) Out << ", ambiguous";
434 if (Paths) Out << ", base paths present";
435
436 for (iterator I = begin(), E = end(); I != E; ++I) {
437 Out << "\n";
438 (*I)->print(Out, 2);
439 }
440}
441
Douglas Gregord3a59182010-02-12 05:48:04 +0000442/// \brief Lookup a builtin function, when name lookup would otherwise
443/// fail.
444static bool LookupBuiltin(Sema &S, LookupResult &R) {
445 Sema::LookupNameKind NameKind = R.getLookupKind();
446
447 // If we didn't find a use of this identifier, and if the identifier
448 // corresponds to a compiler builtin, create the decl object for the builtin
449 // now, injecting it into translation unit scope, and return it.
450 if (NameKind == Sema::LookupOrdinaryName ||
451 NameKind == Sema::LookupRedeclarationWithLinkage) {
452 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
453 if (II) {
454 // If this is a builtin on this (or all) targets, create the decl.
455 if (unsigned BuiltinID = II->getBuiltinID()) {
456 // In C++, we don't have any predefined library functions like
457 // 'malloc'. Instead, we'll just error.
458 if (S.getLangOptions().CPlusPlus &&
459 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
460 return false;
461
462 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
463 S.TUScope, R.isForRedeclaration(),
464 R.getNameLoc());
465 if (D)
466 R.addDecl(D);
467 return (D != NULL);
468 }
469 }
470 }
471
472 return false;
473}
474
Douglas Gregor7454c562010-07-02 20:37:36 +0000475/// \brief Determine whether we can declare a special member function within
476/// the class at this point.
477static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
478 const CXXRecordDecl *Class) {
John McCall2ded5d22010-08-11 23:52:36 +0000479 // Don't do it if the class is invalid.
480 if (Class->isInvalidDecl())
481 return false;
482
Douglas Gregor7454c562010-07-02 20:37:36 +0000483 // We need to have a definition for the class.
484 if (!Class->getDefinition() || Class->isDependentContext())
485 return false;
486
487 // We can't be in the middle of defining the class.
488 if (const RecordType *RecordTy
489 = Context.getTypeDeclType(Class)->getAs<RecordType>())
490 return !RecordTy->isBeingDefined();
491
492 return false;
493}
494
495void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000496 if (!CanDeclareSpecialMemberFunction(Context, Class))
497 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000498
499 // If the default constructor has not yet been declared, do so now.
500 if (!Class->hasDeclaredDefaultConstructor())
501 DeclareImplicitDefaultConstructor(Class);
Douglas Gregora6d69502010-07-02 23:41:54 +0000502
503 // If the copy constructor has not yet been declared, do so now.
504 if (!Class->hasDeclaredCopyConstructor())
505 DeclareImplicitCopyConstructor(Class);
506
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000507 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000508 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000509 DeclareImplicitCopyAssignment(Class);
510
Douglas Gregor7454c562010-07-02 20:37:36 +0000511 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000512 if (!Class->hasDeclaredDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +0000513 DeclareImplicitDestructor(Class);
514}
515
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000516/// \brief Determine whether this is the name of an implicitly-declared
517/// special member function.
518static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
519 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000520 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000521 case DeclarationName::CXXDestructorName:
522 return true;
523
524 case DeclarationName::CXXOperatorName:
525 return Name.getCXXOverloadedOperator() == OO_Equal;
526
527 default:
528 break;
529 }
530
531 return false;
532}
533
534/// \brief If there are any implicit member functions with the given name
535/// that need to be declared in the given declaration context, do so.
536static void DeclareImplicitMemberFunctionsWithName(Sema &S,
537 DeclarationName Name,
538 const DeclContext *DC) {
539 if (!DC)
540 return;
541
542 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000543 case DeclarationName::CXXConstructorName:
544 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000545 if (Record->getDefinition() &&
546 CanDeclareSpecialMemberFunction(S.Context, Record)) {
547 if (!Record->hasDeclaredDefaultConstructor())
548 S.DeclareImplicitDefaultConstructor(
549 const_cast<CXXRecordDecl *>(Record));
550 if (!Record->hasDeclaredCopyConstructor())
551 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
552 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000553 break;
554
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000555 case DeclarationName::CXXDestructorName:
556 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
557 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
558 CanDeclareSpecialMemberFunction(S.Context, Record))
559 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000560 break;
561
562 case DeclarationName::CXXOperatorName:
563 if (Name.getCXXOverloadedOperator() != OO_Equal)
564 break;
565
566 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
567 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
568 CanDeclareSpecialMemberFunction(S.Context, Record))
569 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
570 break;
571
572 default:
573 break;
574 }
575}
Douglas Gregor7454c562010-07-02 20:37:36 +0000576
John McCall9f3059a2009-10-09 21:13:30 +0000577// Adds all qualifying matches for a name within a decl context to the
578// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000579static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000580 bool Found = false;
581
Douglas Gregor7454c562010-07-02 20:37:36 +0000582 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000583 if (S.getLangOptions().CPlusPlus)
584 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor7454c562010-07-02 20:37:36 +0000585
586 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000587 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000588 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000589 NamedDecl *D = *I;
590 if (R.isAcceptableDecl(D)) {
591 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000592 Found = true;
593 }
594 }
John McCall9f3059a2009-10-09 21:13:30 +0000595
Douglas Gregord3a59182010-02-12 05:48:04 +0000596 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
597 return true;
598
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000599 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000600 != DeclarationName::CXXConversionFunctionName ||
601 R.getLookupName().getCXXNameType()->isDependentType() ||
602 !isa<CXXRecordDecl>(DC))
603 return Found;
604
605 // C++ [temp.mem]p6:
606 // A specialization of a conversion function template is not found by
607 // name lookup. Instead, any conversion function templates visible in the
608 // context of the use are considered. [...]
609 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
610 if (!Record->isDefinition())
611 return Found;
612
613 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
614 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
615 UEnd = Unresolved->end(); U != UEnd; ++U) {
616 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
617 if (!ConvTemplate)
618 continue;
619
620 // When we're performing lookup for the purposes of redeclaration, just
621 // add the conversion function template. When we deduce template
622 // arguments for specializations, we'll end up unifying the return
623 // type of the new declaration with the type of the function template.
624 if (R.isForRedeclaration()) {
625 R.addDecl(ConvTemplate);
626 Found = true;
627 continue;
628 }
629
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000630 // C++ [temp.mem]p6:
Chandler Carruth3a693b72010-01-31 11:44:02 +0000631 // [...] For each such operator, if argument deduction succeeds
632 // (14.9.2.3), the resulting specialization is used as if found by
633 // name lookup.
634 //
635 // When referencing a conversion function for any purpose other than
636 // a redeclaration (such that we'll be building an expression with the
637 // result), perform template argument deduction and place the
638 // specialization into the result set. We do this to avoid forcing all
639 // callers to perform special deduction for conversion functions.
John McCallbc077cf2010-02-08 23:07:23 +0000640 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000641 FunctionDecl *Specialization = 0;
642
643 const FunctionProtoType *ConvProto
644 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
645 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000646
Chandler Carruth3a693b72010-01-31 11:44:02 +0000647 // Compute the type of the function that we would expect the conversion
648 // function to have, if it were to match the name given.
649 // FIXME: Calling convention!
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000650 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruth3a693b72010-01-31 11:44:02 +0000651 QualType ExpectedType
652 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
653 0, 0, ConvProto->isVariadic(),
654 ConvProto->getTypeQuals(),
655 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000656 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruth3a693b72010-01-31 11:44:02 +0000657
658 // Perform template argument deduction against the type that we would
659 // expect the function to have.
660 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
661 Specialization, Info)
662 == Sema::TDK_Success) {
663 R.addDecl(Specialization);
664 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000665 }
666 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000667
John McCall9f3059a2009-10-09 21:13:30 +0000668 return Found;
669}
670
John McCallf6c8a4e2009-11-10 07:01:13 +0000671// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000672static bool
Douglas Gregord3a59182010-02-12 05:48:04 +0000673CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
674 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000675
676 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
677
John McCallf6c8a4e2009-11-10 07:01:13 +0000678 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000679 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000680
John McCallf6c8a4e2009-11-10 07:01:13 +0000681 // Perform direct name lookup into the namespaces nominated by the
682 // using directives whose common ancestor is this namespace.
683 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
684 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000685
John McCallf6c8a4e2009-11-10 07:01:13 +0000686 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000687 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000688 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000689
690 R.resolveKind();
691
692 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000693}
694
695static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000696 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000697 return Ctx->isFileContext();
698 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000699}
Douglas Gregored8f2882009-01-30 01:04:22 +0000700
Douglas Gregor66230062010-03-15 14:33:29 +0000701// Find the next outer declaration context from this scope. This
702// routine actually returns the semantic outer context, which may
703// differ from the lexical context (encoded directly in the Scope
704// stack) when we are parsing a member of a class template. In this
705// case, the second element of the pair will be true, to indicate that
706// name lookup should continue searching in this semantic context when
707// it leaves the current template parameter scope.
708static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
709 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
710 DeclContext *Lexical = 0;
711 for (Scope *OuterS = S->getParent(); OuterS;
712 OuterS = OuterS->getParent()) {
713 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000714 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000715 break;
716 }
717 }
718
719 // C++ [temp.local]p8:
720 // In the definition of a member of a class template that appears
721 // outside of the namespace containing the class template
722 // definition, the name of a template-parameter hides the name of
723 // a member of this namespace.
724 //
725 // Example:
726 //
727 // namespace N {
728 // class C { };
729 //
730 // template<class T> class B {
731 // void f(T);
732 // };
733 // }
734 //
735 // template<class C> void N::B<C>::f(C) {
736 // C b; // C is the template parameter, not N::C
737 // }
738 //
739 // In this example, the lexical context we return is the
740 // TranslationUnit, while the semantic context is the namespace N.
741 if (!Lexical || !DC || !S->getParent() ||
742 !S->getParent()->isTemplateParamScope())
743 return std::make_pair(Lexical, false);
744
745 // Find the outermost template parameter scope.
746 // For the example, this is the scope for the template parameters of
747 // template<class C>.
748 Scope *OutermostTemplateScope = S->getParent();
749 while (OutermostTemplateScope->getParent() &&
750 OutermostTemplateScope->getParent()->isTemplateParamScope())
751 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregor7f737c02009-09-10 16:57:35 +0000752
Douglas Gregor66230062010-03-15 14:33:29 +0000753 // Find the namespace context in which the original scope occurs. In
754 // the example, this is namespace N.
755 DeclContext *Semantic = DC;
756 while (!Semantic->isFileContext())
757 Semantic = Semantic->getParent();
758
759 // Find the declaration context just outside of the template
760 // parameter scope. This is the context in which the template is
761 // being lexically declaration (a namespace context). In the
762 // example, this is the global scope.
763 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
764 Lexical->Encloses(Semantic))
765 return std::make_pair(Semantic, true);
766
767 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000768}
769
John McCall27b18f82009-11-17 02:14:36 +0000770bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000771 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000772
773 DeclarationName Name = R.getLookupName();
774
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000775 // If this is the name of an implicitly-declared special member function,
776 // go through the scope stack to implicitly declare
777 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
778 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
779 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
780 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
781 }
782
783 // Implicitly declare member functions with the name we're looking for, if in
784 // fact we are in a scope where it matters.
785
Douglas Gregor889ceb72009-02-03 19:21:40 +0000786 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000787 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000788 I = IdResolver.begin(Name),
789 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000790
Douglas Gregor889ceb72009-02-03 19:21:40 +0000791 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000792 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000793 // ...During unqualified name lookup (3.4.1), the names appear as if
794 // they were declared in the nearest enclosing namespace which contains
795 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000796 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000797 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000798 //
799 // For example:
800 // namespace A { int i; }
801 // void foo() {
802 // int i;
803 // {
804 // using namespace A;
805 // ++i; // finds local 'i', A::i appears at global scope
806 // }
807 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000808 //
Douglas Gregor66230062010-03-15 14:33:29 +0000809 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000810 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000811 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
812
Douglas Gregor889ceb72009-02-03 19:21:40 +0000813 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000814 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000815 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000816 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000817 Found = true;
818 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000819 }
820 }
John McCall9f3059a2009-10-09 21:13:30 +0000821 if (Found) {
822 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000823 if (S->isClassScope())
824 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
825 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000826 return true;
827 }
828
Douglas Gregor66230062010-03-15 14:33:29 +0000829 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
830 S->getParent() && !S->getParent()->isTemplateParamScope()) {
831 // We've just searched the last template parameter scope and
832 // found nothing, so look into the the contexts between the
833 // lexical and semantic declaration contexts returned by
834 // findOuterContext(). This implements the name lookup behavior
835 // of C++ [temp.local]p8.
836 Ctx = OutsideOfTemplateParamDC;
837 OutsideOfTemplateParamDC = 0;
838 }
839
840 if (Ctx) {
841 DeclContext *OuterCtx;
842 bool SearchAfterTemplateScope;
843 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
844 if (SearchAfterTemplateScope)
845 OutsideOfTemplateParamDC = OuterCtx;
846
Douglas Gregorea166062010-03-15 15:26:48 +0000847 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000848 // We do not directly look into transparent contexts, since
849 // those entities will be found in the nearest enclosing
850 // non-transparent context.
851 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000852 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000853
854 // We do not look directly into function or method contexts,
855 // since all of the local variables and parameters of the
856 // function/method are present within the Scope.
857 if (Ctx->isFunctionOrMethod()) {
858 // If we have an Objective-C instance method, look for ivars
859 // in the corresponding interface.
860 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
861 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
862 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
863 ObjCInterfaceDecl *ClassDeclared;
864 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
865 Name.getAsIdentifierInfo(),
866 ClassDeclared)) {
867 if (R.isAcceptableDecl(Ivar)) {
868 R.addDecl(Ivar);
869 R.resolveKind();
870 return true;
871 }
872 }
873 }
874 }
875
876 continue;
877 }
878
Douglas Gregor7f737c02009-09-10 16:57:35 +0000879 // Perform qualified name lookup into this context.
880 // FIXME: In some cases, we know that every name that could be found by
881 // this qualified name lookup will also be on the identifier chain. For
882 // example, inside a class without any base classes, we never need to
883 // perform qualified lookup because all of the members are on top of the
884 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000885 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000886 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000887 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000888 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000889 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000890
John McCallf6c8a4e2009-11-10 07:01:13 +0000891 // Stop if we ran out of scopes.
892 // FIXME: This really, really shouldn't be happening.
893 if (!S) return false;
894
Douglas Gregor700792c2009-02-05 19:25:20 +0000895 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000896 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000897 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000898 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
899 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000900
John McCallf6c8a4e2009-11-10 07:01:13 +0000901 UnqualUsingDirectiveSet UDirs;
902 UDirs.visitScopeChain(Initial, S);
903 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000904
Douglas Gregor700792c2009-02-05 19:25:20 +0000905 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000906 // Unqualified name lookup in C++ requires looking into scopes
907 // that aren't strictly lexical, and therefore we walk through the
908 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000909
Douglas Gregor889ceb72009-02-03 19:21:40 +0000910 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000911 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000912 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000913 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000914 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000915 // We found something. Look for anything else in our scope
916 // with this same name and in an acceptable identifier
917 // namespace, so that we can construct an overload set if we
918 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000919 Found = true;
920 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000921 }
922 }
923
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000924 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000925 R.resolveKind();
926 return true;
927 }
928
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000929 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
930 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
931 S->getParent() && !S->getParent()->isTemplateParamScope()) {
932 // We've just searched the last template parameter scope and
933 // found nothing, so look into the the contexts between the
934 // lexical and semantic declaration contexts returned by
935 // findOuterContext(). This implements the name lookup behavior
936 // of C++ [temp.local]p8.
937 Ctx = OutsideOfTemplateParamDC;
938 OutsideOfTemplateParamDC = 0;
939 }
940
941 if (Ctx) {
942 DeclContext *OuterCtx;
943 bool SearchAfterTemplateScope;
944 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
945 if (SearchAfterTemplateScope)
946 OutsideOfTemplateParamDC = OuterCtx;
947
948 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
949 // We do not directly look into transparent contexts, since
950 // those entities will be found in the nearest enclosing
951 // non-transparent context.
952 if (Ctx->isTransparentContext())
953 continue;
954
955 // If we have a context, and it's not a context stashed in the
956 // template parameter scope for an out-of-line definition, also
957 // look into that context.
958 if (!(Found && S && S->isTemplateParamScope())) {
959 assert(Ctx->isFileContext() &&
960 "We should have been looking only at file context here already.");
961
962 // Look into context considering using-directives.
963 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
964 Found = true;
965 }
966
967 if (Found) {
968 R.resolveKind();
969 return true;
970 }
971
972 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
973 return false;
974 }
975 }
976
Douglas Gregor3ce74932010-02-05 07:07:10 +0000977 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000978 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000979 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000980
John McCall9f3059a2009-10-09 21:13:30 +0000981 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000982}
983
Douglas Gregor34074322009-01-14 22:20:51 +0000984/// @brief Perform unqualified name lookup starting from a given
985/// scope.
986///
987/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
988/// used to find names within the current scope. For example, 'x' in
989/// @code
990/// int x;
991/// int f() {
992/// return x; // unqualified name look finds 'x' in the global scope
993/// }
994/// @endcode
995///
996/// Different lookup criteria can find different names. For example, a
997/// particular scope can have both a struct and a function of the same
998/// name, and each can be found by certain lookup criteria. For more
999/// information about lookup criteria, see the documentation for the
1000/// class LookupCriteria.
1001///
1002/// @param S The scope from which unqualified name lookup will
1003/// begin. If the lookup criteria permits, name lookup may also search
1004/// in the parent scopes.
1005///
1006/// @param Name The name of the entity that we are searching for.
1007///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001008/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001009/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001010/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001011///
1012/// @returns The result of name lookup, which includes zero or more
1013/// declarations and possibly additional information used to diagnose
1014/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001015bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1016 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001017 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001018
John McCall27b18f82009-11-17 02:14:36 +00001019 LookupNameKind NameKind = R.getLookupKind();
1020
Douglas Gregor34074322009-01-14 22:20:51 +00001021 if (!getLangOptions().CPlusPlus) {
1022 // Unqualified name lookup in C/Objective-C is purely lexical, so
1023 // search in the declarations attached to the name.
1024
John McCallea305ed2009-12-18 10:40:03 +00001025 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001026 // Find the nearest non-transparent declaration scope.
1027 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001028 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001029 static_cast<DeclContext *>(S->getEntity())
1030 ->isTransparentContext()))
1031 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001032 }
1033
John McCallea305ed2009-12-18 10:40:03 +00001034 unsigned IDNS = R.getIdentifierNamespace();
1035
Douglas Gregor34074322009-01-14 22:20:51 +00001036 // Scan up the scope chain looking for a decl that matches this
1037 // identifier that is in the appropriate namespace. This search
1038 // should not take long, as shadowing of names is uncommon, and
1039 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001040 bool LeftStartingScope = false;
1041
Douglas Gregored8f2882009-01-30 01:04:22 +00001042 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001043 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001044 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001045 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001046 if (NameKind == LookupRedeclarationWithLinkage) {
1047 // Determine whether this (or a previous) declaration is
1048 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001049 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001050 LeftStartingScope = true;
1051
1052 // If we found something outside of our starting scope that
1053 // does not have linkage, skip it.
1054 if (LeftStartingScope && !((*I)->hasLinkage()))
1055 continue;
1056 }
1057
John McCall9f3059a2009-10-09 21:13:30 +00001058 R.addDecl(*I);
1059
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001060 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001061 // If this declaration has the "overloadable" attribute, we
1062 // might have a set of overloaded functions.
1063
1064 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001065 while (!(S->getFlags() & Scope::DeclScope) ||
John McCall48871652010-08-21 09:40:31 +00001066 !S->isDeclScope(*I))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001067 S = S->getParent();
1068
1069 // Find the last declaration in this scope (with the same
1070 // name, naturally).
1071 IdentifierResolver::iterator LastI = I;
1072 for (++LastI; LastI != IEnd; ++LastI) {
John McCall48871652010-08-21 09:40:31 +00001073 if (!S->isDeclScope(*LastI))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001074 break;
John McCall9f3059a2009-10-09 21:13:30 +00001075 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001076 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001077 }
1078
John McCall9f3059a2009-10-09 21:13:30 +00001079 R.resolveKind();
1080
1081 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001082 }
Douglas Gregor34074322009-01-14 22:20:51 +00001083 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001084 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001085 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001086 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001087 }
1088
1089 // If we didn't find a use of this identifier, and if the identifier
1090 // corresponds to a compiler builtin, create the decl object for the builtin
1091 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +00001092 if (AllowBuiltinCreation)
1093 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001094
John McCall9f3059a2009-10-09 21:13:30 +00001095 return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001096}
1097
John McCall6538c932009-10-10 05:48:19 +00001098/// @brief Perform qualified name lookup in the namespaces nominated by
1099/// using directives by the given context.
1100///
1101/// C++98 [namespace.qual]p2:
1102/// Given X::m (where X is a user-declared namespace), or given ::m
1103/// (where X is the global namespace), let S be the set of all
1104/// declarations of m in X and in the transitive closure of all
1105/// namespaces nominated by using-directives in X and its used
1106/// namespaces, except that using-directives are ignored in any
1107/// namespace, including X, directly containing one or more
1108/// declarations of m. No namespace is searched more than once in
1109/// the lookup of a name. If S is the empty set, the program is
1110/// ill-formed. Otherwise, if S has exactly one member, or if the
1111/// context of the reference is a using-declaration
1112/// (namespace.udecl), S is the required set of declarations of
1113/// m. Otherwise if the use of m is not one that allows a unique
1114/// declaration to be chosen from S, the program is ill-formed.
1115/// C++98 [namespace.qual]p5:
1116/// During the lookup of a qualified namespace member name, if the
1117/// lookup finds more than one declaration of the member, and if one
1118/// declaration introduces a class name or enumeration name and the
1119/// other declarations either introduce the same object, the same
1120/// enumerator or a set of functions, the non-type name hides the
1121/// class or enumeration name if and only if the declarations are
1122/// from the same namespace; otherwise (the declarations are from
1123/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001124static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001125 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001126 assert(StartDC->isFileContext() && "start context is not a file context");
1127
1128 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1129 DeclContext::udir_iterator E = StartDC->using_directives_end();
1130
1131 if (I == E) return false;
1132
1133 // We have at least added all these contexts to the queue.
1134 llvm::DenseSet<DeclContext*> Visited;
1135 Visited.insert(StartDC);
1136
1137 // We have not yet looked into these namespaces, much less added
1138 // their "using-children" to the queue.
1139 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1140
1141 // We have already looked into the initial namespace; seed the queue
1142 // with its using-children.
1143 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001144 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001145 if (Visited.insert(ND).second)
1146 Queue.push_back(ND);
1147 }
1148
1149 // The easiest way to implement the restriction in [namespace.qual]p5
1150 // is to check whether any of the individual results found a tag
1151 // and, if so, to declare an ambiguity if the final result is not
1152 // a tag.
1153 bool FoundTag = false;
1154 bool FoundNonTag = false;
1155
John McCall5cebab12009-11-18 07:57:50 +00001156 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001157
1158 bool Found = false;
1159 while (!Queue.empty()) {
1160 NamespaceDecl *ND = Queue.back();
1161 Queue.pop_back();
1162
1163 // We go through some convolutions here to avoid copying results
1164 // between LookupResults.
1165 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001166 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001167 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001168
1169 if (FoundDirect) {
1170 // First do any local hiding.
1171 DirectR.resolveKind();
1172
1173 // If the local result is a tag, remember that.
1174 if (DirectR.isSingleTagDecl())
1175 FoundTag = true;
1176 else
1177 FoundNonTag = true;
1178
1179 // Append the local results to the total results if necessary.
1180 if (UseLocal) {
1181 R.addAllDecls(LocalR);
1182 LocalR.clear();
1183 }
1184 }
1185
1186 // If we find names in this namespace, ignore its using directives.
1187 if (FoundDirect) {
1188 Found = true;
1189 continue;
1190 }
1191
1192 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1193 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1194 if (Visited.insert(Nom).second)
1195 Queue.push_back(Nom);
1196 }
1197 }
1198
1199 if (Found) {
1200 if (FoundTag && FoundNonTag)
1201 R.setAmbiguousQualifiedTagHiding();
1202 else
1203 R.resolveKind();
1204 }
1205
1206 return Found;
1207}
1208
Douglas Gregor39982192010-08-15 06:18:01 +00001209/// \brief Callback that looks for any member of a class with the given name.
1210static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1211 CXXBasePath &Path,
1212 void *Name) {
1213 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1214
1215 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1216 Path.Decls = BaseRecord->lookup(N);
1217 return Path.Decls.first != Path.Decls.second;
1218}
1219
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001220/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001221///
1222/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1223/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001224/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001225///
1226/// Different lookup criteria can find different names. For example, a
1227/// particular scope can have both a struct and a function of the same
1228/// name, and each can be found by certain lookup criteria. For more
1229/// information about lookup criteria, see the documentation for the
1230/// class LookupCriteria.
1231///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001232/// \param R captures both the lookup criteria and any lookup results found.
1233///
1234/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001235/// search. If the lookup criteria permits, name lookup may also search
1236/// in the parent contexts or (for C++ classes) base classes.
1237///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001238/// \param InUnqualifiedLookup true if this is qualified name lookup that
1239/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001240///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001241/// \returns true if lookup succeeded, false if it failed.
1242bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1243 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001244 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001245
John McCall27b18f82009-11-17 02:14:36 +00001246 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001247 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001248
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001249 // Make sure that the declaration context is complete.
1250 assert((!isa<TagDecl>(LookupCtx) ||
1251 LookupCtx->isDependentContext() ||
1252 cast<TagDecl>(LookupCtx)->isDefinition() ||
1253 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1254 ->isBeingDefined()) &&
1255 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001256
Douglas Gregor34074322009-01-14 22:20:51 +00001257 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001258 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001259 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001260 if (isa<CXXRecordDecl>(LookupCtx))
1261 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001262 return true;
1263 }
Douglas Gregor34074322009-01-14 22:20:51 +00001264
John McCall6538c932009-10-10 05:48:19 +00001265 // Don't descend into implied contexts for redeclarations.
1266 // C++98 [namespace.qual]p6:
1267 // In a declaration for a namespace member in which the
1268 // declarator-id is a qualified-id, given that the qualified-id
1269 // for the namespace member has the form
1270 // nested-name-specifier unqualified-id
1271 // the unqualified-id shall name a member of the namespace
1272 // designated by the nested-name-specifier.
1273 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001274 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001275 return false;
1276
John McCall27b18f82009-11-17 02:14:36 +00001277 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001278 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001279 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001280
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001281 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001282 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001283 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001284 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001285 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001286
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001287 // If we're performing qualified name lookup into a dependent class,
1288 // then we are actually looking into a current instantiation. If we have any
1289 // dependent base classes, then we either have to delay lookup until
1290 // template instantiation time (at which point all bases will be available)
1291 // or we have to fail.
1292 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1293 LookupRec->hasAnyDependentBases()) {
1294 R.setNotFoundInCurrentInstantiation();
1295 return false;
1296 }
1297
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001298 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001299 CXXBasePaths Paths;
1300 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001301
1302 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001303 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001304 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001305 case LookupOrdinaryName:
1306 case LookupMemberName:
1307 case LookupRedeclarationWithLinkage:
1308 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1309 break;
1310
1311 case LookupTagName:
1312 BaseCallback = &CXXRecordDecl::FindTagMember;
1313 break;
John McCall84d87672009-12-10 09:41:52 +00001314
Douglas Gregor39982192010-08-15 06:18:01 +00001315 case LookupAnyName:
1316 BaseCallback = &LookupAnyMember;
1317 break;
1318
John McCall84d87672009-12-10 09:41:52 +00001319 case LookupUsingDeclName:
1320 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001321
1322 case LookupOperatorName:
1323 case LookupNamespaceName:
1324 case LookupObjCProtocolName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001325 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001326 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001327
1328 case LookupNestedNameSpecifierName:
1329 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1330 break;
1331 }
1332
John McCall27b18f82009-11-17 02:14:36 +00001333 if (!LookupRec->lookupInBases(BaseCallback,
1334 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001335 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001336
John McCall553c0792010-01-23 00:46:32 +00001337 R.setNamingClass(LookupRec);
1338
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001339 // C++ [class.member.lookup]p2:
1340 // [...] If the resulting set of declarations are not all from
1341 // sub-objects of the same type, or the set has a nonstatic member
1342 // and includes members from distinct sub-objects, there is an
1343 // ambiguity and the program is ill-formed. Otherwise that set is
1344 // the result of the lookup.
1345 // FIXME: support using declarations!
1346 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001347 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001348 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001349 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001350 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001351 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001352
John McCall401982f2010-01-20 21:53:11 +00001353 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1354 // across all paths.
1355 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1356
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001357 // Determine whether we're looking at a distinct sub-object or not.
1358 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001359 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001360 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1361 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001362 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001363 != Context.getCanonicalType(PathElement.Base->getType())) {
1364 // We found members of the given name in two subobjects of
1365 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001366 R.setAmbiguousBaseSubobjectTypes(Paths);
1367 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001368 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1369 // We have a different subobject of the same type.
1370
1371 // C++ [class.member.lookup]p5:
1372 // A static member, a nested type or an enumerator defined in
1373 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001374 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001375 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001376 if (isa<VarDecl>(FirstDecl) ||
1377 isa<TypeDecl>(FirstDecl) ||
1378 isa<EnumConstantDecl>(FirstDecl))
1379 continue;
1380
1381 if (isa<CXXMethodDecl>(FirstDecl)) {
1382 // Determine whether all of the methods are static.
1383 bool AllMethodsAreStatic = true;
1384 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1385 Func != Path->Decls.second; ++Func) {
1386 if (!isa<CXXMethodDecl>(*Func)) {
1387 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1388 break;
1389 }
1390
1391 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1392 AllMethodsAreStatic = false;
1393 break;
1394 }
1395 }
1396
1397 if (AllMethodsAreStatic)
1398 continue;
1399 }
1400
1401 // We have found a nonstatic member name in multiple, distinct
1402 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001403 R.setAmbiguousBaseSubobjects(Paths);
1404 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001405 }
1406 }
1407
1408 // Lookup in a base class succeeded; return these results.
1409
John McCall9f3059a2009-10-09 21:13:30 +00001410 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001411 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1412 NamedDecl *D = *I;
1413 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1414 D->getAccess());
1415 R.addDecl(D, AS);
1416 }
John McCall9f3059a2009-10-09 21:13:30 +00001417 R.resolveKind();
1418 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001419}
1420
1421/// @brief Performs name lookup for a name that was parsed in the
1422/// source code, and may contain a C++ scope specifier.
1423///
1424/// This routine is a convenience routine meant to be called from
1425/// contexts that receive a name and an optional C++ scope specifier
1426/// (e.g., "N::M::x"). It will then perform either qualified or
1427/// unqualified name lookup (with LookupQualifiedName or LookupName,
1428/// respectively) on the given name and return those results.
1429///
1430/// @param S The scope from which unqualified name lookup will
1431/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001432///
Douglas Gregore861bac2009-08-25 22:51:20 +00001433/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001434///
1435/// @param Name The name of the entity that name lookup will
1436/// search for.
1437///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001438/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001439/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001440/// C library functions (like "malloc") are implicitly declared.
1441///
Douglas Gregore861bac2009-08-25 22:51:20 +00001442/// @param EnteringContext Indicates whether we are going to enter the
1443/// context of the scope-specifier SS (if present).
1444///
John McCall9f3059a2009-10-09 21:13:30 +00001445/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001446bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001447 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001448 if (SS && SS->isInvalid()) {
1449 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001450 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001451 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001452 }
Mike Stump11289f42009-09-09 15:08:12 +00001453
Douglas Gregore861bac2009-08-25 22:51:20 +00001454 if (SS && SS->isSet()) {
1455 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001456 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001457 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001458 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001459 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001460
John McCall27b18f82009-11-17 02:14:36 +00001461 R.setContextRange(SS->getRange());
1462
1463 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001464 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001465
Douglas Gregore861bac2009-08-25 22:51:20 +00001466 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001467 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001468 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001469 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001470 }
1471
Mike Stump11289f42009-09-09 15:08:12 +00001472 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001473 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001474}
1475
Douglas Gregor889ceb72009-02-03 19:21:40 +00001476
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001477/// @brief Produce a diagnostic describing the ambiguity that resulted
1478/// from name lookup.
1479///
1480/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001481///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001482/// @param Name The name of the entity that name lookup was
1483/// searching for.
1484///
1485/// @param NameLoc The location of the name within the source code.
1486///
1487/// @param LookupRange A source range that provides more
1488/// source-location information concerning the lookup itself. For
1489/// example, this range might highlight a nested-name-specifier that
1490/// precedes the name.
1491///
1492/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001493bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001494 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1495
John McCall27b18f82009-11-17 02:14:36 +00001496 DeclarationName Name = Result.getLookupName();
1497 SourceLocation NameLoc = Result.getNameLoc();
1498 SourceRange LookupRange = Result.getContextRange();
1499
John McCall6538c932009-10-10 05:48:19 +00001500 switch (Result.getAmbiguityKind()) {
1501 case LookupResult::AmbiguousBaseSubobjects: {
1502 CXXBasePaths *Paths = Result.getBasePaths();
1503 QualType SubobjectType = Paths->front().back().Base->getType();
1504 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1505 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1506 << LookupRange;
1507
1508 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1509 while (isa<CXXMethodDecl>(*Found) &&
1510 cast<CXXMethodDecl>(*Found)->isStatic())
1511 ++Found;
1512
1513 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1514
1515 return true;
1516 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001517
John McCall6538c932009-10-10 05:48:19 +00001518 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001519 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1520 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001521
1522 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001523 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001524 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1525 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001526 Path != PathEnd; ++Path) {
1527 Decl *D = *Path->Decls.first;
1528 if (DeclsPrinted.insert(D).second)
1529 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1530 }
1531
Douglas Gregor1c846b02009-01-16 00:38:09 +00001532 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001533 }
1534
John McCall6538c932009-10-10 05:48:19 +00001535 case LookupResult::AmbiguousTagHiding: {
1536 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001537
John McCall6538c932009-10-10 05:48:19 +00001538 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1539
1540 LookupResult::iterator DI, DE = Result.end();
1541 for (DI = Result.begin(); DI != DE; ++DI)
1542 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1543 TagDecls.insert(TD);
1544 Diag(TD->getLocation(), diag::note_hidden_tag);
1545 }
1546
1547 for (DI = Result.begin(); DI != DE; ++DI)
1548 if (!isa<TagDecl>(*DI))
1549 Diag((*DI)->getLocation(), diag::note_hiding_object);
1550
1551 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001552 LookupResult::Filter F = Result.makeFilter();
1553 while (F.hasNext()) {
1554 if (TagDecls.count(F.next()))
1555 F.erase();
1556 }
1557 F.done();
John McCall6538c932009-10-10 05:48:19 +00001558
1559 return true;
1560 }
1561
1562 case LookupResult::AmbiguousReference: {
1563 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001564
John McCall6538c932009-10-10 05:48:19 +00001565 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1566 for (; DI != DE; ++DI)
1567 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001568
John McCall6538c932009-10-10 05:48:19 +00001569 return true;
1570 }
1571 }
1572
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001573 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001574 return true;
1575}
Douglas Gregore254f902009-02-04 00:32:51 +00001576
John McCallf24d7bb2010-05-28 18:45:08 +00001577namespace {
1578 struct AssociatedLookup {
1579 AssociatedLookup(Sema &S,
1580 Sema::AssociatedNamespaceSet &Namespaces,
1581 Sema::AssociatedClassSet &Classes)
1582 : S(S), Namespaces(Namespaces), Classes(Classes) {
1583 }
1584
1585 Sema &S;
1586 Sema::AssociatedNamespaceSet &Namespaces;
1587 Sema::AssociatedClassSet &Classes;
1588 };
1589}
1590
Mike Stump11289f42009-09-09 15:08:12 +00001591static void
John McCallf24d7bb2010-05-28 18:45:08 +00001592addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001593
Douglas Gregor8b895222010-04-30 07:08:38 +00001594static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1595 DeclContext *Ctx) {
1596 // Add the associated namespace for this class.
1597
1598 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1599 // be a locally scoped record.
1600
1601 while (Ctx->isRecord() || Ctx->isTransparentContext())
1602 Ctx = Ctx->getParent();
1603
John McCallc7e8e792009-08-07 22:18:02 +00001604 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001605 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001606}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001607
Mike Stump11289f42009-09-09 15:08:12 +00001608// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001609// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001610static void
John McCallf24d7bb2010-05-28 18:45:08 +00001611addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1612 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001613 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001614 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001615 switch (Arg.getKind()) {
1616 case TemplateArgument::Null:
1617 break;
Mike Stump11289f42009-09-09 15:08:12 +00001618
Douglas Gregor197e5f72009-07-08 07:51:57 +00001619 case TemplateArgument::Type:
1620 // [...] the namespaces and classes associated with the types of the
1621 // template arguments provided for template type parameters (excluding
1622 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001623 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001624 break;
Mike Stump11289f42009-09-09 15:08:12 +00001625
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001626 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001627 // [...] the namespaces in which any template template arguments are
1628 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001629 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001630 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001631 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001632 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001633 DeclContext *Ctx = ClassTemplate->getDeclContext();
1634 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001635 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001636 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001637 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001638 }
1639 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001640 }
1641
1642 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001643 case TemplateArgument::Integral:
1644 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001645 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001646 // associated namespaces. ]
1647 break;
Mike Stump11289f42009-09-09 15:08:12 +00001648
Douglas Gregor197e5f72009-07-08 07:51:57 +00001649 case TemplateArgument::Pack:
1650 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1651 PEnd = Arg.pack_end();
1652 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001653 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001654 break;
1655 }
1656}
1657
Douglas Gregore254f902009-02-04 00:32:51 +00001658// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001659// argument-dependent lookup with an argument of class type
1660// (C++ [basic.lookup.koenig]p2).
1661static void
John McCallf24d7bb2010-05-28 18:45:08 +00001662addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1663 CXXRecordDecl *Class) {
1664
1665 // Just silently ignore anything whose name is __va_list_tag.
1666 if (Class->getDeclName() == Result.S.VAListTagName)
1667 return;
1668
Douglas Gregore254f902009-02-04 00:32:51 +00001669 // C++ [basic.lookup.koenig]p2:
1670 // [...]
1671 // -- If T is a class type (including unions), its associated
1672 // classes are: the class itself; the class of which it is a
1673 // member, if any; and its direct and indirect base
1674 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001675 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001676
1677 // Add the class of which it is a member, if any.
1678 DeclContext *Ctx = Class->getDeclContext();
1679 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001680 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001681 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001682 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001683
Douglas Gregore254f902009-02-04 00:32:51 +00001684 // Add the class itself. If we've already seen this class, we don't
1685 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001686 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001687 return;
1688
Mike Stump11289f42009-09-09 15:08:12 +00001689 // -- If T is a template-id, its associated namespaces and classes are
1690 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001691 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001692 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001693 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001694 // namespaces in which any template template arguments are defined; and
1695 // the classes in which any member templates used as template template
1696 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001697 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001698 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001699 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1700 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1701 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001702 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001703 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001704 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001705
Douglas Gregor197e5f72009-07-08 07:51:57 +00001706 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1707 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001708 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001709 }
Mike Stump11289f42009-09-09 15:08:12 +00001710
John McCall67da35c2010-02-04 22:26:26 +00001711 // Only recurse into base classes for complete types.
1712 if (!Class->hasDefinition()) {
1713 // FIXME: we might need to instantiate templates here
1714 return;
1715 }
1716
Douglas Gregore254f902009-02-04 00:32:51 +00001717 // Add direct and indirect base classes along with their associated
1718 // namespaces.
1719 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1720 Bases.push_back(Class);
1721 while (!Bases.empty()) {
1722 // Pop this class off the stack.
1723 Class = Bases.back();
1724 Bases.pop_back();
1725
1726 // Visit the base classes.
1727 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1728 BaseEnd = Class->bases_end();
1729 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001730 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001731 // In dependent contexts, we do ADL twice, and the first time around,
1732 // the base type might be a dependent TemplateSpecializationType, or a
1733 // TemplateTypeParmType. If that happens, simply ignore it.
1734 // FIXME: If we want to support export, we probably need to add the
1735 // namespace of the template in a TemplateSpecializationType, or even
1736 // the classes and namespaces of known non-dependent arguments.
1737 if (!BaseType)
1738 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001739 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001740 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001741 // Find the associated namespace for this base class.
1742 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001743 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001744
1745 // Make sure we visit the bases of this base class.
1746 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1747 Bases.push_back(BaseDecl);
1748 }
1749 }
1750 }
1751}
1752
1753// \brief Add the associated classes and namespaces for
1754// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001755// (C++ [basic.lookup.koenig]p2).
1756static void
John McCallf24d7bb2010-05-28 18:45:08 +00001757addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001758 // C++ [basic.lookup.koenig]p2:
1759 //
1760 // For each argument type T in the function call, there is a set
1761 // of zero or more associated namespaces and a set of zero or more
1762 // associated classes to be considered. The sets of namespaces and
1763 // classes is determined entirely by the types of the function
1764 // arguments (and the namespace of any template template
1765 // argument). Typedef names and using-declarations used to specify
1766 // the types do not contribute to this set. The sets of namespaces
1767 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001768
John McCall0af3d3b2010-05-28 06:08:54 +00001769 llvm::SmallVector<const Type *, 16> Queue;
1770 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1771
Douglas Gregore254f902009-02-04 00:32:51 +00001772 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001773 switch (T->getTypeClass()) {
1774
1775#define TYPE(Class, Base)
1776#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1777#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1778#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1779#define ABSTRACT_TYPE(Class, Base)
1780#include "clang/AST/TypeNodes.def"
1781 // T is canonical. We can also ignore dependent types because
1782 // we don't need to do ADL at the definition point, but if we
1783 // wanted to implement template export (or if we find some other
1784 // use for associated classes and namespaces...) this would be
1785 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001786 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001787
John McCall0af3d3b2010-05-28 06:08:54 +00001788 // -- If T is a pointer to U or an array of U, its associated
1789 // namespaces and classes are those associated with U.
1790 case Type::Pointer:
1791 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1792 continue;
1793 case Type::ConstantArray:
1794 case Type::IncompleteArray:
1795 case Type::VariableArray:
1796 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1797 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001798
John McCall0af3d3b2010-05-28 06:08:54 +00001799 // -- If T is a fundamental type, its associated sets of
1800 // namespaces and classes are both empty.
1801 case Type::Builtin:
1802 break;
1803
1804 // -- If T is a class type (including unions), its associated
1805 // classes are: the class itself; the class of which it is a
1806 // member, if any; and its direct and indirect base
1807 // classes. Its associated namespaces are the namespaces in
1808 // which its associated classes are defined.
1809 case Type::Record: {
1810 CXXRecordDecl *Class
1811 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001812 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001813 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001814 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001815
John McCall0af3d3b2010-05-28 06:08:54 +00001816 // -- If T is an enumeration type, its associated namespace is
1817 // the namespace in which it is defined. If it is class
1818 // member, its associated class is the member’s class; else
1819 // it has no associated class.
1820 case Type::Enum: {
1821 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001822
John McCall0af3d3b2010-05-28 06:08:54 +00001823 DeclContext *Ctx = Enum->getDeclContext();
1824 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001825 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001826
John McCall0af3d3b2010-05-28 06:08:54 +00001827 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001828 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001829
John McCall0af3d3b2010-05-28 06:08:54 +00001830 break;
1831 }
1832
1833 // -- If T is a function type, its associated namespaces and
1834 // classes are those associated with the function parameter
1835 // types and those associated with the return type.
1836 case Type::FunctionProto: {
1837 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1838 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1839 ArgEnd = Proto->arg_type_end();
1840 Arg != ArgEnd; ++Arg)
1841 Queue.push_back(Arg->getTypePtr());
1842 // fallthrough
1843 }
1844 case Type::FunctionNoProto: {
1845 const FunctionType *FnType = cast<FunctionType>(T);
1846 T = FnType->getResultType().getTypePtr();
1847 continue;
1848 }
1849
1850 // -- If T is a pointer to a member function of a class X, its
1851 // associated namespaces and classes are those associated
1852 // with the function parameter types and return type,
1853 // together with those associated with X.
1854 //
1855 // -- If T is a pointer to a data member of class X, its
1856 // associated namespaces and classes are those associated
1857 // with the member type together with those associated with
1858 // X.
1859 case Type::MemberPointer: {
1860 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1861
1862 // Queue up the class type into which this points.
1863 Queue.push_back(MemberPtr->getClass());
1864
1865 // And directly continue with the pointee type.
1866 T = MemberPtr->getPointeeType().getTypePtr();
1867 continue;
1868 }
1869
1870 // As an extension, treat this like a normal pointer.
1871 case Type::BlockPointer:
1872 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1873 continue;
1874
1875 // References aren't covered by the standard, but that's such an
1876 // obvious defect that we cover them anyway.
1877 case Type::LValueReference:
1878 case Type::RValueReference:
1879 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1880 continue;
1881
1882 // These are fundamental types.
1883 case Type::Vector:
1884 case Type::ExtVector:
1885 case Type::Complex:
1886 break;
1887
1888 // These are ignored by ADL.
1889 case Type::ObjCObject:
1890 case Type::ObjCInterface:
1891 case Type::ObjCObjectPointer:
1892 break;
1893 }
1894
1895 if (Queue.empty()) break;
1896 T = Queue.back();
1897 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001898 }
Douglas Gregore254f902009-02-04 00:32:51 +00001899}
1900
1901/// \brief Find the associated classes and namespaces for
1902/// argument-dependent lookup for a call with the given set of
1903/// arguments.
1904///
1905/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001906/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001907/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001908void
Douglas Gregore254f902009-02-04 00:32:51 +00001909Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1910 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001911 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001912 AssociatedNamespaces.clear();
1913 AssociatedClasses.clear();
1914
John McCallf24d7bb2010-05-28 18:45:08 +00001915 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1916
Douglas Gregore254f902009-02-04 00:32:51 +00001917 // C++ [basic.lookup.koenig]p2:
1918 // For each argument type T in the function call, there is a set
1919 // of zero or more associated namespaces and a set of zero or more
1920 // associated classes to be considered. The sets of namespaces and
1921 // classes is determined entirely by the types of the function
1922 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001923 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001924 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1925 Expr *Arg = Args[ArgIdx];
1926
1927 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00001928 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001929 continue;
1930 }
1931
1932 // [...] In addition, if the argument is the name or address of a
1933 // set of overloaded functions and/or function templates, its
1934 // associated classes and namespaces are the union of those
1935 // associated with each of the members of the set: the namespace
1936 // in which the function or function template is defined and the
1937 // classes and namespaces associated with its (non-dependent)
1938 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001939 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001940 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1941 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1942 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001943
John McCallf24d7bb2010-05-28 18:45:08 +00001944 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1945 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00001946
John McCallf24d7bb2010-05-28 18:45:08 +00001947 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1948 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001949 // Look through any using declarations to find the underlying function.
1950 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001951
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001952 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1953 if (!FDecl)
1954 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001955
1956 // Add the classes and namespaces associated with the parameter
1957 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00001958 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001959 }
1960 }
1961}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001962
1963/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1964/// an acceptable non-member overloaded operator for a call whose
1965/// arguments have types T1 (and, if non-empty, T2). This routine
1966/// implements the check in C++ [over.match.oper]p3b2 concerning
1967/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001968static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001969IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1970 QualType T1, QualType T2,
1971 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001972 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1973 return true;
1974
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001975 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1976 return true;
1977
John McCall9dd450b2009-09-21 23:43:11 +00001978 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001979 if (Proto->getNumArgs() < 1)
1980 return false;
1981
1982 if (T1->isEnumeralType()) {
1983 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001984 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001985 return true;
1986 }
1987
1988 if (Proto->getNumArgs() < 2)
1989 return false;
1990
1991 if (!T2.isNull() && T2->isEnumeralType()) {
1992 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001993 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001994 return true;
1995 }
1996
1997 return false;
1998}
1999
John McCall5cebab12009-11-18 07:57:50 +00002000NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002001 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002002 LookupNameKind NameKind,
2003 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002004 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002005 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002006 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002007}
2008
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002009/// \brief Find the protocol with the given name, if any.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002010ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2011 SourceLocation IdLoc) {
2012 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2013 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002014 return cast_or_null<ObjCProtocolDecl>(D);
2015}
2016
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002017void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002018 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002019 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002020 // C++ [over.match.oper]p3:
2021 // -- The set of non-member candidates is the result of the
2022 // unqualified lookup of operator@ in the context of the
2023 // expression according to the usual rules for name lookup in
2024 // unqualified function calls (3.4.2) except that all member
2025 // functions are ignored. However, if no operand has a class
2026 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002027 // that have a first parameter of type T1 or "reference to
2028 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002029 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002030 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002031 // when T2 is an enumeration type, are candidate functions.
2032 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002033 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2034 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002035
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002036 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2037
John McCall9f3059a2009-10-09 21:13:30 +00002038 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002039 return;
2040
2041 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2042 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002043 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2044 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002045 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002046 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002047 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002048 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002049 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002050 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002051 // later?
2052 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002053 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002054 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002055 }
2056}
2057
Douglas Gregor52b72822010-07-02 23:12:18 +00002058/// \brief Look up the constructors for the given class.
2059DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +00002060 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002061 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2062 if (!Class->hasDeclaredDefaultConstructor())
2063 DeclareImplicitDefaultConstructor(Class);
2064 if (!Class->hasDeclaredCopyConstructor())
2065 DeclareImplicitCopyConstructor(Class);
2066 }
Douglas Gregora6d69502010-07-02 23:41:54 +00002067
Douglas Gregor52b72822010-07-02 23:12:18 +00002068 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2069 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2070 return Class->lookup(Name);
2071}
2072
Douglas Gregore71edda2010-07-01 22:47:18 +00002073/// \brief Look for the destructor of the given class.
2074///
2075/// During semantic analysis, this routine should be used in lieu of
2076/// CXXRecordDecl::getDestructor().
2077///
2078/// \returns The destructor for this class.
2079CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +00002080 // If the destructor has not yet been declared, do so now.
2081 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2082 !Class->hasDeclaredDestructor())
2083 DeclareImplicitDestructor(Class);
2084
Douglas Gregore71edda2010-07-01 22:47:18 +00002085 return Class->getDestructor();
2086}
2087
John McCall8fe68082010-01-26 07:16:45 +00002088void ADLResult::insert(NamedDecl *New) {
2089 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2090
2091 // If we haven't yet seen a decl for this key, or the last decl
2092 // was exactly this one, we're done.
2093 if (Old == 0 || Old == New) {
2094 Old = New;
2095 return;
2096 }
2097
2098 // Otherwise, decide which is a more recent redeclaration.
2099 FunctionDecl *OldFD, *NewFD;
2100 if (isa<FunctionTemplateDecl>(New)) {
2101 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2102 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2103 } else {
2104 OldFD = cast<FunctionDecl>(Old);
2105 NewFD = cast<FunctionDecl>(New);
2106 }
2107
2108 FunctionDecl *Cursor = NewFD;
2109 while (true) {
2110 Cursor = Cursor->getPreviousDeclaration();
2111
2112 // If we got to the end without finding OldFD, OldFD is the newer
2113 // declaration; leave things as they are.
2114 if (!Cursor) return;
2115
2116 // If we do find OldFD, then NewFD is newer.
2117 if (Cursor == OldFD) break;
2118
2119 // Otherwise, keep looking.
2120 }
2121
2122 Old = New;
2123}
2124
Sebastian Redlc057f422009-10-23 19:23:15 +00002125void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002126 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00002127 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002128 // Find all of the associated namespaces and classes based on the
2129 // arguments we have.
2130 AssociatedNamespaceSet AssociatedNamespaces;
2131 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002132 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002133 AssociatedNamespaces,
2134 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002135
Sebastian Redlc057f422009-10-23 19:23:15 +00002136 QualType T1, T2;
2137 if (Operator) {
2138 T1 = Args[0]->getType();
2139 if (NumArgs >= 2)
2140 T2 = Args[1]->getType();
2141 }
2142
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002143 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002144 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2145 // and let Y be the lookup set produced by argument dependent
2146 // lookup (defined as follows). If X contains [...] then Y is
2147 // empty. Otherwise Y is the set of declarations found in the
2148 // namespaces associated with the argument types as described
2149 // below. The set of declarations found by the lookup of the name
2150 // is the union of X and Y.
2151 //
2152 // Here, we compute Y and add its members to the overloaded
2153 // candidate set.
2154 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002155 NSEnd = AssociatedNamespaces.end();
2156 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002157 // When considering an associated namespace, the lookup is the
2158 // same as the lookup performed when the associated namespace is
2159 // used as a qualifier (3.4.3.2) except that:
2160 //
2161 // -- Any using-directives in the associated namespace are
2162 // ignored.
2163 //
John McCallc7e8e792009-08-07 22:18:02 +00002164 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002165 // associated classes are visible within their respective
2166 // namespaces even if they are not visible during an ordinary
2167 // lookup (11.4).
2168 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002169 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002170 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002171 // If the only declaration here is an ordinary friend, consider
2172 // it only if it was declared in an associated classes.
2173 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002174 DeclContext *LexDC = D->getLexicalDeclContext();
2175 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2176 continue;
2177 }
Mike Stump11289f42009-09-09 15:08:12 +00002178
John McCall91f61fc2010-01-26 06:04:06 +00002179 if (isa<UsingShadowDecl>(D))
2180 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002181
John McCall91f61fc2010-01-26 06:04:06 +00002182 if (isa<FunctionDecl>(D)) {
2183 if (Operator &&
2184 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2185 T1, T2, Context))
2186 continue;
John McCall8fe68082010-01-26 07:16:45 +00002187 } else if (!isa<FunctionTemplateDecl>(D))
2188 continue;
2189
2190 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002191 }
2192 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002193}
Douglas Gregor2d435302009-12-30 17:04:44 +00002194
2195//----------------------------------------------------------------------------
2196// Search for all visible declarations.
2197//----------------------------------------------------------------------------
2198VisibleDeclConsumer::~VisibleDeclConsumer() { }
2199
2200namespace {
2201
2202class ShadowContextRAII;
2203
2204class VisibleDeclsRecord {
2205public:
2206 /// \brief An entry in the shadow map, which is optimized to store a
2207 /// single declaration (the common case) but can also store a list
2208 /// of declarations.
2209 class ShadowMapEntry {
2210 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2211
2212 /// \brief Contains either the solitary NamedDecl * or a vector
2213 /// of declarations.
2214 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2215
2216 public:
2217 ShadowMapEntry() : DeclOrVector() { }
2218
2219 void Add(NamedDecl *ND);
2220 void Destroy();
2221
2222 // Iteration.
2223 typedef NamedDecl **iterator;
2224 iterator begin();
2225 iterator end();
2226 };
2227
2228private:
2229 /// \brief A mapping from declaration names to the declarations that have
2230 /// this name within a particular scope.
2231 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2232
2233 /// \brief A list of shadow maps, which is used to model name hiding.
2234 std::list<ShadowMap> ShadowMaps;
2235
2236 /// \brief The declaration contexts we have already visited.
2237 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2238
2239 friend class ShadowContextRAII;
2240
2241public:
2242 /// \brief Determine whether we have already visited this context
2243 /// (and, if not, note that we are going to visit that context now).
2244 bool visitedContext(DeclContext *Ctx) {
2245 return !VisitedContexts.insert(Ctx);
2246 }
2247
Douglas Gregor39982192010-08-15 06:18:01 +00002248 bool alreadyVisitedContext(DeclContext *Ctx) {
2249 return VisitedContexts.count(Ctx);
2250 }
2251
Douglas Gregor2d435302009-12-30 17:04:44 +00002252 /// \brief Determine whether the given declaration is hidden in the
2253 /// current scope.
2254 ///
2255 /// \returns the declaration that hides the given declaration, or
2256 /// NULL if no such declaration exists.
2257 NamedDecl *checkHidden(NamedDecl *ND);
2258
2259 /// \brief Add a declaration to the current shadow map.
2260 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2261};
2262
2263/// \brief RAII object that records when we've entered a shadow context.
2264class ShadowContextRAII {
2265 VisibleDeclsRecord &Visible;
2266
2267 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2268
2269public:
2270 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2271 Visible.ShadowMaps.push_back(ShadowMap());
2272 }
2273
2274 ~ShadowContextRAII() {
2275 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2276 EEnd = Visible.ShadowMaps.back().end();
2277 E != EEnd;
2278 ++E)
2279 E->second.Destroy();
2280
2281 Visible.ShadowMaps.pop_back();
2282 }
2283};
2284
2285} // end anonymous namespace
2286
2287void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2288 if (DeclOrVector.isNull()) {
2289 // 0 - > 1 elements: just set the single element information.
2290 DeclOrVector = ND;
2291 return;
2292 }
2293
2294 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2295 // 1 -> 2 elements: create the vector of results and push in the
2296 // existing declaration.
2297 DeclVector *Vec = new DeclVector;
2298 Vec->push_back(PrevND);
2299 DeclOrVector = Vec;
2300 }
2301
2302 // Add the new element to the end of the vector.
2303 DeclOrVector.get<DeclVector*>()->push_back(ND);
2304}
2305
2306void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2307 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2308 delete Vec;
2309 DeclOrVector = ((NamedDecl *)0);
2310 }
2311}
2312
2313VisibleDeclsRecord::ShadowMapEntry::iterator
2314VisibleDeclsRecord::ShadowMapEntry::begin() {
2315 if (DeclOrVector.isNull())
2316 return 0;
2317
2318 if (DeclOrVector.dyn_cast<NamedDecl *>())
2319 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2320
2321 return DeclOrVector.get<DeclVector *>()->begin();
2322}
2323
2324VisibleDeclsRecord::ShadowMapEntry::iterator
2325VisibleDeclsRecord::ShadowMapEntry::end() {
2326 if (DeclOrVector.isNull())
2327 return 0;
2328
2329 if (DeclOrVector.dyn_cast<NamedDecl *>())
2330 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2331
2332 return DeclOrVector.get<DeclVector *>()->end();
2333}
2334
2335NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002336 // Look through using declarations.
2337 ND = ND->getUnderlyingDecl();
2338
Douglas Gregor2d435302009-12-30 17:04:44 +00002339 unsigned IDNS = ND->getIdentifierNamespace();
2340 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2341 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2342 SM != SMEnd; ++SM) {
2343 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2344 if (Pos == SM->end())
2345 continue;
2346
2347 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2348 IEnd = Pos->second.end();
2349 I != IEnd; ++I) {
2350 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002351 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor2d435302009-12-30 17:04:44 +00002352 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2353 Decl::IDNS_ObjCProtocol)))
2354 continue;
2355
2356 // Protocols are in distinct namespaces from everything else.
2357 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2358 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2359 (*I)->getIdentifierNamespace() != IDNS)
2360 continue;
2361
Douglas Gregor09bbc652010-01-14 15:47:35 +00002362 // Functions and function templates in the same scope overload
2363 // rather than hide. FIXME: Look for hiding based on function
2364 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002365 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002366 ND->isFunctionOrFunctionTemplate() &&
2367 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002368 continue;
2369
Douglas Gregor2d435302009-12-30 17:04:44 +00002370 // We've found a declaration that hides this one.
2371 return *I;
2372 }
2373 }
2374
2375 return 0;
2376}
2377
2378static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2379 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002380 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002381 VisibleDeclConsumer &Consumer,
2382 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002383 if (!Ctx)
2384 return;
2385
Douglas Gregor2d435302009-12-30 17:04:44 +00002386 // Make sure we don't visit the same context twice.
2387 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2388 return;
2389
Douglas Gregor7454c562010-07-02 20:37:36 +00002390 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2391 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2392
Douglas Gregor2d435302009-12-30 17:04:44 +00002393 // Enumerate all of the results in this context.
2394 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2395 CurCtx = CurCtx->getNextContext()) {
2396 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2397 DEnd = CurCtx->decls_end();
2398 D != DEnd; ++D) {
2399 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2400 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002401 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002402 Visited.add(ND);
2403 }
2404
2405 // Visit transparent contexts inside this context.
2406 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2407 if (InnerCtx->isTransparentContext())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002408 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002409 Consumer, Visited);
2410 }
2411 }
2412 }
2413
2414 // Traverse using directives for qualified name lookup.
2415 if (QualifiedNameLookup) {
2416 ShadowContextRAII Shadow(Visited);
2417 DeclContext::udir_iterator I, E;
2418 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2419 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002420 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002421 }
2422 }
2423
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002424 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002425 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002426 if (!Record->hasDefinition())
2427 return;
2428
Douglas Gregor2d435302009-12-30 17:04:44 +00002429 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2430 BEnd = Record->bases_end();
2431 B != BEnd; ++B) {
2432 QualType BaseType = B->getType();
2433
2434 // Don't look into dependent bases, because name lookup can't look
2435 // there anyway.
2436 if (BaseType->isDependentType())
2437 continue;
2438
2439 const RecordType *Record = BaseType->getAs<RecordType>();
2440 if (!Record)
2441 continue;
2442
2443 // FIXME: It would be nice to be able to determine whether referencing
2444 // a particular member would be ambiguous. For example, given
2445 //
2446 // struct A { int member; };
2447 // struct B { int member; };
2448 // struct C : A, B { };
2449 //
2450 // void f(C *c) { c->### }
2451 //
2452 // accessing 'member' would result in an ambiguity. However, we
2453 // could be smart enough to qualify the member with the base
2454 // class, e.g.,
2455 //
2456 // c->B::member
2457 //
2458 // or
2459 //
2460 // c->A::member
2461
2462 // Find results in this base class (and its bases).
2463 ShadowContextRAII Shadow(Visited);
2464 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002465 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002466 }
2467 }
2468
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002469 // Traverse the contexts of Objective-C classes.
2470 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2471 // Traverse categories.
2472 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2473 Category; Category = Category->getNextClassCategory()) {
2474 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002475 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2476 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002477 }
2478
2479 // Traverse protocols.
2480 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2481 E = IFace->protocol_end(); I != E; ++I) {
2482 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002483 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2484 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002485 }
2486
2487 // Traverse the superclass.
2488 if (IFace->getSuperClass()) {
2489 ShadowContextRAII Shadow(Visited);
2490 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002491 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002492 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002493
2494 // If there is an implementation, traverse it. We do this to find
2495 // synthesized ivars.
2496 if (IFace->getImplementation()) {
2497 ShadowContextRAII Shadow(Visited);
2498 LookupVisibleDecls(IFace->getImplementation(), Result,
2499 QualifiedNameLookup, true, Consumer, Visited);
2500 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002501 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2502 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2503 E = Protocol->protocol_end(); I != E; ++I) {
2504 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002505 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2506 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002507 }
2508 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2509 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2510 E = Category->protocol_end(); I != E; ++I) {
2511 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002512 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2513 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002514 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002515
2516 // If there is an implementation, traverse it.
2517 if (Category->getImplementation()) {
2518 ShadowContextRAII Shadow(Visited);
2519 LookupVisibleDecls(Category->getImplementation(), Result,
2520 QualifiedNameLookup, true, Consumer, Visited);
2521 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002522 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002523}
2524
2525static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2526 UnqualUsingDirectiveSet &UDirs,
2527 VisibleDeclConsumer &Consumer,
2528 VisibleDeclsRecord &Visited) {
2529 if (!S)
2530 return;
2531
Douglas Gregor39982192010-08-15 06:18:01 +00002532 if (!S->getEntity() ||
2533 (!S->getParent() &&
2534 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002535 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2536 // Walk through the declarations in this Scope.
2537 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2538 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002539 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002540 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002541 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002542 Visited.add(ND);
2543 }
2544 }
2545 }
2546
Douglas Gregor66230062010-03-15 14:33:29 +00002547 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002548 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002549 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002550 // Look into this scope's declaration context, along with any of its
2551 // parent lookup contexts (e.g., enclosing classes), up to the point
2552 // where we hit the context stored in the next outer scope.
2553 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002554 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor2d435302009-12-30 17:04:44 +00002555
Douglas Gregorea166062010-03-15 15:26:48 +00002556 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002557 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002558 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2559 if (Method->isInstanceMethod()) {
2560 // For instance methods, look for ivars in the method's interface.
2561 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2562 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002563 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2564 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2565 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002566 }
2567
2568 // We've already performed all of the name lookup that we need
2569 // to for Objective-C methods; the next context will be the
2570 // outer scope.
2571 break;
2572 }
2573
Douglas Gregor2d435302009-12-30 17:04:44 +00002574 if (Ctx->isFunctionOrMethod())
2575 continue;
2576
2577 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002578 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002579 }
2580 } else if (!S->getParent()) {
2581 // Look into the translation unit scope. We walk through the translation
2582 // unit's declaration context, because the Scope itself won't have all of
2583 // the declarations if we loaded a precompiled header.
2584 // FIXME: We would like the translation unit's Scope object to point to the
2585 // translation unit, so we don't need this special "if" branch. However,
2586 // doing so would force the normal C++ name-lookup code to look into the
2587 // translation unit decl when the IdentifierInfo chains would suffice.
2588 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002589 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002590 Entity = Result.getSema().Context.getTranslationUnitDecl();
2591 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002592 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002593 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002594
2595 if (Entity) {
2596 // Lookup visible declarations in any namespaces found by using
2597 // directives.
2598 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2599 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2600 for (; UI != UEnd; ++UI)
2601 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002602 Result, /*QualifiedNameLookup=*/false,
2603 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002604 }
2605
2606 // Lookup names in the parent scope.
2607 ShadowContextRAII Shadow(Visited);
2608 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2609}
2610
2611void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002612 VisibleDeclConsumer &Consumer,
2613 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002614 // Determine the set of using directives available during
2615 // unqualified name lookup.
2616 Scope *Initial = S;
2617 UnqualUsingDirectiveSet UDirs;
2618 if (getLangOptions().CPlusPlus) {
2619 // Find the first namespace or translation-unit scope.
2620 while (S && !isNamespaceOrTranslationUnitScope(S))
2621 S = S->getParent();
2622
2623 UDirs.visitScopeChain(Initial, S);
2624 }
2625 UDirs.done();
2626
2627 // Look for visible declarations.
2628 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2629 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002630 if (!IncludeGlobalScope)
2631 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002632 ShadowContextRAII Shadow(Visited);
2633 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2634}
2635
2636void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002637 VisibleDeclConsumer &Consumer,
2638 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002639 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2640 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002641 if (!IncludeGlobalScope)
2642 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002643 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002644 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2645 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002646}
2647
2648//----------------------------------------------------------------------------
2649// Typo correction
2650//----------------------------------------------------------------------------
2651
2652namespace {
2653class TypoCorrectionConsumer : public VisibleDeclConsumer {
2654 /// \brief The name written that is a typo in the source.
2655 llvm::StringRef Typo;
2656
2657 /// \brief The results found that have the smallest edit distance
2658 /// found (so far) with the typo name.
2659 llvm::SmallVector<NamedDecl *, 4> BestResults;
2660
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002661 /// \brief The keywords that have the smallest edit distance.
2662 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2663
Douglas Gregor2d435302009-12-30 17:04:44 +00002664 /// \brief The best edit distance found so far.
2665 unsigned BestEditDistance;
2666
2667public:
2668 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2669 : Typo(Typo->getName()) { }
2670
Douglas Gregor09bbc652010-01-14 15:47:35 +00002671 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002672 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002673
2674 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2675 iterator begin() const { return BestResults.begin(); }
2676 iterator end() const { return BestResults.end(); }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002677 void clear_decls() { BestResults.clear(); }
2678
2679 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002680
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002681 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2682 keyword_iterator;
2683 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2684 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2685 bool keyword_empty() const { return BestKeywords.empty(); }
2686 unsigned keyword_size() const { return BestKeywords.size(); }
2687
2688 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002689};
2690
2691}
2692
Douglas Gregor09bbc652010-01-14 15:47:35 +00002693void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2694 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002695 // Don't consider hidden names for typo correction.
2696 if (Hiding)
2697 return;
2698
2699 // Only consider entities with identifiers for names, ignoring
2700 // special names (constructors, overloaded operators, selectors,
2701 // etc.).
2702 IdentifierInfo *Name = ND->getIdentifier();
2703 if (!Name)
2704 return;
2705
2706 // Compute the edit distance between the typo and the name of this
2707 // entity. If this edit distance is not worse than the best edit
2708 // distance we've seen so far, add it to the list of results.
2709 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002710 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002711 if (ED < BestEditDistance) {
2712 // This result is better than any we've seen before; clear out
2713 // the previous results.
2714 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002715 BestKeywords.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002716 BestEditDistance = ED;
2717 } else if (ED > BestEditDistance) {
2718 // This result is worse than the best results we've seen so far;
2719 // ignore it.
2720 return;
2721 }
2722 } else
2723 BestEditDistance = ED;
2724
2725 BestResults.push_back(ND);
2726}
2727
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002728void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2729 llvm::StringRef Keyword) {
2730 // Compute the edit distance between the typo and this keyword.
2731 // If this edit distance is not worse than the best edit
2732 // distance we've seen so far, add it to the list of results.
2733 unsigned ED = Typo.edit_distance(Keyword);
2734 if (!BestResults.empty() || !BestKeywords.empty()) {
2735 if (ED < BestEditDistance) {
2736 BestResults.clear();
2737 BestKeywords.clear();
2738 BestEditDistance = ED;
2739 } else if (ED > BestEditDistance) {
2740 // This result is worse than the best results we've seen so far;
2741 // ignore it.
2742 return;
2743 }
2744 } else
2745 BestEditDistance = ED;
2746
2747 BestKeywords.push_back(&Context.Idents.get(Keyword));
2748}
2749
Douglas Gregor2d435302009-12-30 17:04:44 +00002750/// \brief Try to "correct" a typo in the source code by finding
2751/// visible declarations whose names are similar to the name that was
2752/// present in the source code.
2753///
2754/// \param Res the \c LookupResult structure that contains the name
2755/// that was present in the source code along with the name-lookup
2756/// criteria used to search for the name. On success, this structure
2757/// will contain the results of name lookup.
2758///
2759/// \param S the scope in which name lookup occurs.
2760///
2761/// \param SS the nested-name-specifier that precedes the name we're
2762/// looking for, if present.
2763///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002764/// \param MemberContext if non-NULL, the context in which to look for
2765/// a member access expression.
2766///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002767/// \param EnteringContext whether we're entering the context described by
2768/// the nested-name-specifier SS.
2769///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002770/// \param CTC The context in which typo correction occurs, which impacts the
2771/// set of keywords permitted.
2772///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002773/// \param OPT when non-NULL, the search for visible declarations will
2774/// also walk the protocols in the qualified interfaces of \p OPT.
2775///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002776/// \returns the corrected name if the typo was corrected, otherwise returns an
2777/// empty \c DeclarationName. When a typo was corrected, the result structure
2778/// may contain the results of name lookup for the correct name or it may be
2779/// empty.
2780DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002781 DeclContext *MemberContext,
2782 bool EnteringContext,
2783 CorrectTypoContext CTC,
2784 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00002785 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002786 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002787
2788 // Provide a stop gap for files that are just seriously broken. Trying
2789 // to correct all typos can turn into a HUGE performance penalty, causing
2790 // some files to take minutes to get rejected by the parser.
2791 // FIXME: Is this the right solution?
2792 if (TyposCorrected == 20)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002793 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002794 ++TyposCorrected;
Ted Kremeneke51136e2010-01-06 00:23:04 +00002795
Douglas Gregor2d435302009-12-30 17:04:44 +00002796 // We only attempt to correct typos for identifiers.
2797 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2798 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002799 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002800
2801 // If the scope specifier itself was invalid, don't try to correct
2802 // typos.
2803 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002804 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002805
2806 // Never try to correct typos during template deduction or
2807 // instantiation.
2808 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002809 return DeclarationName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002810
Douglas Gregor2d435302009-12-30 17:04:44 +00002811 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002812
2813 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002814 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002815 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002816
2817 // Look in qualified interfaces.
2818 if (OPT) {
2819 for (ObjCObjectPointerType::qual_iterator
2820 I = OPT->qual_begin(), E = OPT->qual_end();
2821 I != E; ++I)
2822 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2823 }
2824 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002825 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2826 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002827 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002828
2829 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2830 } else {
2831 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2832 }
2833
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002834 // Add context-dependent keywords.
2835 bool WantTypeSpecifiers = false;
2836 bool WantExpressionKeywords = false;
2837 bool WantCXXNamedCasts = false;
2838 bool WantRemainingKeywords = false;
2839 switch (CTC) {
2840 case CTC_Unknown:
2841 WantTypeSpecifiers = true;
2842 WantExpressionKeywords = true;
2843 WantCXXNamedCasts = true;
2844 WantRemainingKeywords = true;
Douglas Gregor5fd04d42010-05-18 16:14:23 +00002845
2846 if (ObjCMethodDecl *Method = getCurMethodDecl())
2847 if (Method->getClassInterface() &&
2848 Method->getClassInterface()->getSuperClass())
2849 Consumer.addKeywordResult(Context, "super");
2850
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002851 break;
2852
2853 case CTC_NoKeywords:
2854 break;
2855
2856 case CTC_Type:
2857 WantTypeSpecifiers = true;
2858 break;
2859
2860 case CTC_ObjCMessageReceiver:
2861 Consumer.addKeywordResult(Context, "super");
2862 // Fall through to handle message receivers like expressions.
2863
2864 case CTC_Expression:
2865 if (getLangOptions().CPlusPlus)
2866 WantTypeSpecifiers = true;
2867 WantExpressionKeywords = true;
2868 // Fall through to get C++ named casts.
2869
2870 case CTC_CXXCasts:
2871 WantCXXNamedCasts = true;
2872 break;
2873
2874 case CTC_MemberLookup:
2875 if (getLangOptions().CPlusPlus)
2876 Consumer.addKeywordResult(Context, "template");
2877 break;
2878 }
2879
2880 if (WantTypeSpecifiers) {
2881 // Add type-specifier keywords to the set of results.
2882 const char *CTypeSpecs[] = {
2883 "char", "const", "double", "enum", "float", "int", "long", "short",
2884 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2885 "_Complex", "_Imaginary",
2886 // storage-specifiers as well
2887 "extern", "inline", "static", "typedef"
2888 };
2889
2890 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2891 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2892 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2893
2894 if (getLangOptions().C99)
2895 Consumer.addKeywordResult(Context, "restrict");
2896 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2897 Consumer.addKeywordResult(Context, "bool");
2898
2899 if (getLangOptions().CPlusPlus) {
2900 Consumer.addKeywordResult(Context, "class");
2901 Consumer.addKeywordResult(Context, "typename");
2902 Consumer.addKeywordResult(Context, "wchar_t");
2903
2904 if (getLangOptions().CPlusPlus0x) {
2905 Consumer.addKeywordResult(Context, "char16_t");
2906 Consumer.addKeywordResult(Context, "char32_t");
2907 Consumer.addKeywordResult(Context, "constexpr");
2908 Consumer.addKeywordResult(Context, "decltype");
2909 Consumer.addKeywordResult(Context, "thread_local");
2910 }
2911 }
2912
2913 if (getLangOptions().GNUMode)
2914 Consumer.addKeywordResult(Context, "typeof");
2915 }
2916
Douglas Gregor86ad0852010-05-18 16:30:22 +00002917 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002918 Consumer.addKeywordResult(Context, "const_cast");
2919 Consumer.addKeywordResult(Context, "dynamic_cast");
2920 Consumer.addKeywordResult(Context, "reinterpret_cast");
2921 Consumer.addKeywordResult(Context, "static_cast");
2922 }
2923
2924 if (WantExpressionKeywords) {
2925 Consumer.addKeywordResult(Context, "sizeof");
2926 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2927 Consumer.addKeywordResult(Context, "false");
2928 Consumer.addKeywordResult(Context, "true");
2929 }
2930
2931 if (getLangOptions().CPlusPlus) {
2932 const char *CXXExprs[] = {
2933 "delete", "new", "operator", "throw", "typeid"
2934 };
2935 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2936 for (unsigned I = 0; I != NumCXXExprs; ++I)
2937 Consumer.addKeywordResult(Context, CXXExprs[I]);
2938
2939 if (isa<CXXMethodDecl>(CurContext) &&
2940 cast<CXXMethodDecl>(CurContext)->isInstance())
2941 Consumer.addKeywordResult(Context, "this");
2942
2943 if (getLangOptions().CPlusPlus0x) {
2944 Consumer.addKeywordResult(Context, "alignof");
2945 Consumer.addKeywordResult(Context, "nullptr");
2946 }
2947 }
2948 }
2949
2950 if (WantRemainingKeywords) {
2951 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2952 // Statements.
2953 const char *CStmts[] = {
2954 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2955 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2956 for (unsigned I = 0; I != NumCStmts; ++I)
2957 Consumer.addKeywordResult(Context, CStmts[I]);
2958
2959 if (getLangOptions().CPlusPlus) {
2960 Consumer.addKeywordResult(Context, "catch");
2961 Consumer.addKeywordResult(Context, "try");
2962 }
2963
2964 if (S && S->getBreakParent())
2965 Consumer.addKeywordResult(Context, "break");
2966
2967 if (S && S->getContinueParent())
2968 Consumer.addKeywordResult(Context, "continue");
2969
2970 if (!getSwitchStack().empty()) {
2971 Consumer.addKeywordResult(Context, "case");
2972 Consumer.addKeywordResult(Context, "default");
2973 }
2974 } else {
2975 if (getLangOptions().CPlusPlus) {
2976 Consumer.addKeywordResult(Context, "namespace");
2977 Consumer.addKeywordResult(Context, "template");
2978 }
2979
2980 if (S && S->isClassScope()) {
2981 Consumer.addKeywordResult(Context, "explicit");
2982 Consumer.addKeywordResult(Context, "friend");
2983 Consumer.addKeywordResult(Context, "mutable");
2984 Consumer.addKeywordResult(Context, "private");
2985 Consumer.addKeywordResult(Context, "protected");
2986 Consumer.addKeywordResult(Context, "public");
2987 Consumer.addKeywordResult(Context, "virtual");
2988 }
2989 }
2990
2991 if (getLangOptions().CPlusPlus) {
2992 Consumer.addKeywordResult(Context, "using");
2993
2994 if (getLangOptions().CPlusPlus0x)
2995 Consumer.addKeywordResult(Context, "static_assert");
2996 }
2997 }
2998
2999 // If we haven't found anything, we're done.
Douglas Gregor2d435302009-12-30 17:04:44 +00003000 if (Consumer.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003001 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003002
3003 // Only allow a single, closest name in the result set (it's okay to
3004 // have overloads of that name, though).
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003005 DeclarationName BestName;
3006 NamedDecl *BestIvarOrPropertyDecl = 0;
3007 bool FoundIvarOrPropertyDecl = false;
3008
3009 // Check all of the declaration results to find the best name so far.
3010 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3011 IEnd = Consumer.end();
3012 I != IEnd; ++I) {
3013 if (!BestName)
3014 BestName = (*I)->getDeclName();
3015 else if (BestName != (*I)->getDeclName())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003016 return DeclarationName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003017
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003018 // \brief Keep track of either an Objective-C ivar or a property, but not
3019 // both.
3020 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
3021 if (FoundIvarOrPropertyDecl)
3022 BestIvarOrPropertyDecl = 0;
3023 else {
3024 BestIvarOrPropertyDecl = *I;
3025 FoundIvarOrPropertyDecl = true;
3026 }
3027 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003028 }
3029
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003030 // Now check all of the keyword results to find the best name.
3031 switch (Consumer.keyword_size()) {
3032 case 0:
3033 // No keywords matched.
3034 break;
3035
3036 case 1:
3037 // If we already have a name
3038 if (!BestName) {
3039 // We did not have anything previously,
3040 BestName = *Consumer.keyword_begin();
3041 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
3042 // We have a declaration with the same name as a context-sensitive
3043 // keyword. The keyword takes precedence.
3044 BestIvarOrPropertyDecl = 0;
3045 FoundIvarOrPropertyDecl = false;
3046 Consumer.clear_decls();
Douglas Gregor86ad0852010-05-18 16:30:22 +00003047 } else if (CTC == CTC_ObjCMessageReceiver &&
3048 (*Consumer.keyword_begin())->isStr("super")) {
3049 // In an Objective-C message send, give the "super" keyword a slight
3050 // edge over entities not in function or method scope.
3051 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3052 IEnd = Consumer.end();
3053 I != IEnd; ++I) {
3054 if ((*I)->getDeclName() == BestName) {
3055 if ((*I)->getDeclContext()->isFunctionOrMethod())
3056 return DeclarationName();
3057 }
3058 }
3059
3060 // Everything found was outside a function or method; the 'super'
3061 // keyword takes precedence.
3062 BestIvarOrPropertyDecl = 0;
3063 FoundIvarOrPropertyDecl = false;
3064 Consumer.clear_decls();
3065 BestName = *Consumer.keyword_begin();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003066 } else {
3067 // Name collision; we will not correct typos.
3068 return DeclarationName();
3069 }
3070 break;
3071
3072 default:
3073 // Name collision; we will not correct typos.
3074 return DeclarationName();
3075 }
3076
Douglas Gregor2d435302009-12-30 17:04:44 +00003077 // BestName is the closest viable name to what the user
3078 // typed. However, to make sure that we don't pick something that's
3079 // way off, make sure that the user typed at least 3 characters for
3080 // each correction.
3081 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003082 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
3083 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003084 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003085
3086 // Perform name lookup again with the name we chose, and declare
3087 // success if we found something that was not ambiguous.
3088 Res.clear();
3089 Res.setLookupName(BestName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003090
3091 // If we found an ivar or property, add that result; no further
3092 // lookup is required.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003093 if (BestIvarOrPropertyDecl)
3094 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003095 // If we're looking into the context of a member, perform qualified
3096 // name lookup on the best name.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003097 else if (!Consumer.keyword_empty()) {
3098 // The best match was a keyword. Return it.
3099 return BestName;
3100 } else if (MemberContext)
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003101 LookupQualifiedName(Res, MemberContext);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003102 // Perform lookup as if we had just parsed the best name.
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003103 else
3104 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3105 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00003106
3107 if (Res.isAmbiguous()) {
3108 Res.suppressDiagnostics();
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003109 return DeclarationName();
Douglas Gregor598b08f2009-12-31 05:20:13 +00003110 }
3111
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003112 if (Res.getResultKind() != LookupResult::NotFound)
3113 return BestName;
3114
3115 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003116}