blob: b13deec19abb69b329e91a3f330a2d335c7066fc [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor34074322009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6538c932009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2d435302009-12-30 17:04:44 +000030#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000031#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000032#include <vector>
33#include <iterator>
34#include <utility>
35#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000036
37using namespace clang;
38
John McCallf6c8a4e2009-11-10 07:01:13 +000039namespace {
40 class UnqualUsingEntry {
41 const DeclContext *Nominated;
42 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000043
John McCallf6c8a4e2009-11-10 07:01:13 +000044 public:
45 UnqualUsingEntry(const DeclContext *Nominated,
46 const DeclContext *CommonAncestor)
47 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
48 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000049
John McCallf6c8a4e2009-11-10 07:01:13 +000050 const DeclContext *getCommonAncestor() const {
51 return CommonAncestor;
52 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000053
John McCallf6c8a4e2009-11-10 07:01:13 +000054 const DeclContext *getNominatedNamespace() const {
55 return Nominated;
56 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 // Sort by the pointer value of the common ancestor.
59 struct Comparator {
60 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
61 return L.getCommonAncestor() < R.getCommonAncestor();
62 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
65 return E.getCommonAncestor() < DC;
66 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000067
John McCallf6c8a4e2009-11-10 07:01:13 +000068 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
69 return DC < E.getCommonAncestor();
70 }
71 };
72 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 /// A collection of using directives, as used by C++ unqualified
75 /// lookup.
76 class UnqualUsingDirectiveSet {
77 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000078
John McCallf6c8a4e2009-11-10 07:01:13 +000079 ListTy list;
80 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 public:
83 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000084
John McCallf6c8a4e2009-11-10 07:01:13 +000085 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
86 // C++ [namespace.udir]p1:
87 // During unqualified name lookup, the names appear as if they
88 // were declared in the nearest enclosing namespace which contains
89 // both the using-directive and the nominated namespace.
90 DeclContext *InnermostFileDC
91 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
92 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +000095 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
96 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
97 visit(Ctx, EffectiveDC);
98 } else {
99 Scope::udir_iterator I = S->using_directives_begin(),
100 End = S->using_directives_end();
101
102 for (; I != End; ++I)
103 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
104 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000105 }
106 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000107
108 // Visits a context and collect all of its using directives
109 // recursively. Treats all using directives as if they were
110 // declared in the context.
111 //
112 // A given context is only every visited once, so it is important
113 // that contexts be visited from the inside out in order to get
114 // the effective DCs right.
115 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
116 if (!visited.insert(DC))
117 return;
118
119 addUsingDirectives(DC, EffectiveDC);
120 }
121
122 // Visits a using directive and collects all of its using
123 // directives recursively. Treats all using directives as if they
124 // were declared in the effective DC.
125 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
126 DeclContext *NS = UD->getNominatedNamespace();
127 if (!visited.insert(NS))
128 return;
129
130 addUsingDirective(UD, EffectiveDC);
131 addUsingDirectives(NS, EffectiveDC);
132 }
133
134 // Adds all the using directives in a context (and those nominated
135 // by its using directives, transitively) as if they appeared in
136 // the given effective context.
137 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
138 llvm::SmallVector<DeclContext*,4> queue;
139 while (true) {
140 DeclContext::udir_iterator I, End;
141 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
142 UsingDirectiveDecl *UD = *I;
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (visited.insert(NS)) {
145 addUsingDirective(UD, EffectiveDC);
146 queue.push_back(NS);
147 }
148 }
149
150 if (queue.empty())
151 return;
152
153 DC = queue.back();
154 queue.pop_back();
155 }
156 }
157
158 // Add a using directive as if it had been declared in the given
159 // context. This helps implement C++ [namespace.udir]p3:
160 // The using-directive is transitive: if a scope contains a
161 // using-directive that nominates a second namespace that itself
162 // contains using-directives, the effect is as if the
163 // using-directives from the second namespace also appeared in
164 // the first.
165 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
166 // Find the common ancestor between the effective context and
167 // the nominated namespace.
168 DeclContext *Common = UD->getNominatedNamespace();
169 while (!Common->Encloses(EffectiveDC))
170 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000171 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000172
173 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
174 }
175
176 void done() {
177 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
178 }
179
180 typedef ListTy::iterator iterator;
181 typedef ListTy::const_iterator const_iterator;
182
183 iterator begin() { return list.begin(); }
184 iterator end() { return list.end(); }
185 const_iterator begin() const { return list.begin(); }
186 const_iterator end() const { return list.end(); }
187
188 std::pair<const_iterator,const_iterator>
189 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000190 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000191 UnqualUsingEntry::Comparator());
192 }
193 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000194}
195
Douglas Gregor889ceb72009-02-03 19:21:40 +0000196// Retrieve the set of identifier namespaces that correspond to a
197// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000198static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
199 bool CPlusPlus,
200 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000201 unsigned IDNS = 0;
202 switch (NameKind) {
203 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000204 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000206 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCallea305ed2009-12-18 10:40:03 +0000208 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
209 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210 break;
211
John McCallb9467b62010-04-24 01:30:58 +0000212 case Sema::LookupOperatorName:
213 // Operator lookup is its own crazy thing; it is not the same
214 // as (e.g.) looking up an operator name for redeclaration.
215 assert(!Redeclaration && "cannot do redeclaration operator lookup");
216 IDNS = Decl::IDNS_NonMemberOperator;
217 break;
218
Douglas Gregor889ceb72009-02-03 19:21:40 +0000219 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000220 if (CPlusPlus) {
221 IDNS = Decl::IDNS_Type;
222
223 // When looking for a redeclaration of a tag name, we add:
224 // 1) TagFriend to find undeclared friend decls
225 // 2) Namespace because they can't "overload" with tag decls.
226 // 3) Tag because it includes class templates, which can't
227 // "overload" with tag decls.
228 if (Redeclaration)
229 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
230 } else {
231 IDNS = Decl::IDNS_Tag;
232 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000233 break;
234
235 case Sema::LookupMemberName:
236 IDNS = Decl::IDNS_Member;
237 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000238 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000239 break;
240
241 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000242 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
243 break;
244
Douglas Gregor889ceb72009-02-03 19:21:40 +0000245 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000246 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000247 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000248
John McCall84d87672009-12-10 09:41:52 +0000249 case Sema::LookupUsingDeclName:
250 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
251 | Decl::IDNS_Member | Decl::IDNS_Using;
252 break;
253
Douglas Gregor79947a22009-04-24 00:11:27 +0000254 case Sema::LookupObjCProtocolName:
255 IDNS = Decl::IDNS_ObjCProtocol;
256 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000257 }
258 return IDNS;
259}
260
John McCallea305ed2009-12-18 10:40:03 +0000261void LookupResult::configure() {
262 IDNS = getIDNS(LookupKind,
263 SemaRef.getLangOptions().CPlusPlus,
264 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000265
266 // If we're looking for one of the allocation or deallocation
267 // operators, make sure that the implicitly-declared new and delete
268 // operators can be found.
269 if (!isForRedeclaration()) {
270 switch (Name.getCXXOverloadedOperator()) {
271 case OO_New:
272 case OO_Delete:
273 case OO_Array_New:
274 case OO_Array_Delete:
275 SemaRef.DeclareGlobalNewDelete();
276 break;
277
278 default:
279 break;
280 }
281 }
John McCallea305ed2009-12-18 10:40:03 +0000282}
283
John McCall9f3059a2009-10-09 21:13:30 +0000284// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000285void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000286 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000287}
288
John McCall283b9012009-11-22 00:44:51 +0000289/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000290void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000291 unsigned N = Decls.size();
John McCall84d87672009-12-10 09:41:52 +0000292
John McCall9f3059a2009-10-09 21:13:30 +0000293 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000294 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000295 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000296 return;
297 }
298
John McCall283b9012009-11-22 00:44:51 +0000299 // If there's a single decl, we need to examine it to decide what
300 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000301 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000302 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
303 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000304 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000305 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000306 ResultKind = FoundUnresolvedValue;
307 return;
308 }
John McCall9f3059a2009-10-09 21:13:30 +0000309
John McCall6538c932009-10-10 05:48:19 +0000310 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000311 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000312
John McCall9f3059a2009-10-09 21:13:30 +0000313 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
314
315 bool Ambiguous = false;
316 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000317 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000318
319 unsigned UniqueTagIndex = 0;
320
321 unsigned I = 0;
322 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000323 NamedDecl *D = Decls[I]->getUnderlyingDecl();
324 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000325
John McCallf0f1cf02009-11-17 07:50:12 +0000326 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000327 // If it's not unique, pull something off the back (and
328 // continue at this index).
329 Decls[I] = Decls[--N];
John McCall9f3059a2009-10-09 21:13:30 +0000330 } else {
331 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000332
333 if (isa<UnresolvedUsingValueDecl>(D)) {
334 HasUnresolved = true;
335 } else if (isa<TagDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000336 if (HasTag)
337 Ambiguous = true;
338 UniqueTagIndex = I;
339 HasTag = true;
John McCall283b9012009-11-22 00:44:51 +0000340 } else if (isa<FunctionTemplateDecl>(D)) {
341 HasFunction = true;
342 HasFunctionTemplate = true;
343 } else if (isa<FunctionDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000344 HasFunction = true;
345 } else {
346 if (HasNonFunction)
347 Ambiguous = true;
348 HasNonFunction = true;
349 }
350 I++;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000351 }
Mike Stump11289f42009-09-09 15:08:12 +0000352 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000353
John McCall9f3059a2009-10-09 21:13:30 +0000354 // C++ [basic.scope.hiding]p2:
355 // A class name or enumeration name can be hidden by the name of
356 // an object, function, or enumerator declared in the same
357 // scope. If a class or enumeration name and an object, function,
358 // or enumerator are declared in the same scope (in any order)
359 // with the same name, the class or enumeration name is hidden
360 // wherever the object, function, or enumerator name is visible.
361 // But it's still an error if there are distinct tag types found,
362 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000363 if (HideTags && HasTag && !Ambiguous &&
364 (HasFunction || HasNonFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000365 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000366
John McCall9f3059a2009-10-09 21:13:30 +0000367 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000368
John McCall80053822009-12-03 00:58:24 +0000369 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000370 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000371
John McCall9f3059a2009-10-09 21:13:30 +0000372 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000373 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000374 else if (HasUnresolved)
375 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000376 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000377 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000378 else
John McCall27b18f82009-11-17 02:14:36 +0000379 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000380}
381
John McCall5cebab12009-11-18 07:57:50 +0000382void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000383 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000384 DeclContext::lookup_iterator DI, DE;
385 for (I = P.begin(), E = P.end(); I != E; ++I)
386 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
387 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000388}
389
John McCall5cebab12009-11-18 07:57:50 +0000390void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000391 Paths = new CXXBasePaths;
392 Paths->swap(P);
393 addDeclsFromBasePaths(*Paths);
394 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000395 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000396}
397
John McCall5cebab12009-11-18 07:57:50 +0000398void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000399 Paths = new CXXBasePaths;
400 Paths->swap(P);
401 addDeclsFromBasePaths(*Paths);
402 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000403 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000404}
405
John McCall5cebab12009-11-18 07:57:50 +0000406void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000407 Out << Decls.size() << " result(s)";
408 if (isAmbiguous()) Out << ", ambiguous";
409 if (Paths) Out << ", base paths present";
410
411 for (iterator I = begin(), E = end(); I != E; ++I) {
412 Out << "\n";
413 (*I)->print(Out, 2);
414 }
415}
416
Douglas Gregord3a59182010-02-12 05:48:04 +0000417/// \brief Lookup a builtin function, when name lookup would otherwise
418/// fail.
419static bool LookupBuiltin(Sema &S, LookupResult &R) {
420 Sema::LookupNameKind NameKind = R.getLookupKind();
421
422 // If we didn't find a use of this identifier, and if the identifier
423 // corresponds to a compiler builtin, create the decl object for the builtin
424 // now, injecting it into translation unit scope, and return it.
425 if (NameKind == Sema::LookupOrdinaryName ||
426 NameKind == Sema::LookupRedeclarationWithLinkage) {
427 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
428 if (II) {
429 // If this is a builtin on this (or all) targets, create the decl.
430 if (unsigned BuiltinID = II->getBuiltinID()) {
431 // In C++, we don't have any predefined library functions like
432 // 'malloc'. Instead, we'll just error.
433 if (S.getLangOptions().CPlusPlus &&
434 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
435 return false;
436
437 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
438 S.TUScope, R.isForRedeclaration(),
439 R.getNameLoc());
440 if (D)
441 R.addDecl(D);
442 return (D != NULL);
443 }
444 }
445 }
446
447 return false;
448}
449
Douglas Gregor7454c562010-07-02 20:37:36 +0000450/// \brief Determine whether we can declare a special member function within
451/// the class at this point.
452static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
453 const CXXRecordDecl *Class) {
454 // We need to have a definition for the class.
455 if (!Class->getDefinition() || Class->isDependentContext())
456 return false;
457
458 // We can't be in the middle of defining the class.
459 if (const RecordType *RecordTy
460 = Context.getTypeDeclType(Class)->getAs<RecordType>())
461 return !RecordTy->isBeingDefined();
462
463 return false;
464}
465
466void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000467 if (!CanDeclareSpecialMemberFunction(Context, Class))
468 return;
469
470 // If the copy constructor has not yet been declared, do so now.
471 if (!Class->hasDeclaredCopyConstructor())
472 DeclareImplicitCopyConstructor(Class);
473
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000474 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000475 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000476 DeclareImplicitCopyAssignment(Class);
477
Douglas Gregor7454c562010-07-02 20:37:36 +0000478 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000479 if (!Class->hasDeclaredDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +0000480 DeclareImplicitDestructor(Class);
481}
482
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000483/// \brief Determine whether this is the name of an implicitly-declared
484/// special member function.
485static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
486 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000487 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000488 case DeclarationName::CXXDestructorName:
489 return true;
490
491 case DeclarationName::CXXOperatorName:
492 return Name.getCXXOverloadedOperator() == OO_Equal;
493
494 default:
495 break;
496 }
497
498 return false;
499}
500
501/// \brief If there are any implicit member functions with the given name
502/// that need to be declared in the given declaration context, do so.
503static void DeclareImplicitMemberFunctionsWithName(Sema &S,
504 DeclarationName Name,
505 const DeclContext *DC) {
506 if (!DC)
507 return;
508
509 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000510 case DeclarationName::CXXConstructorName:
511 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
512 if (Record->getDefinition() && !Record->hasDeclaredCopyConstructor() &&
513 CanDeclareSpecialMemberFunction(S.Context, Record))
514 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
515 break;
516
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000517 case DeclarationName::CXXDestructorName:
518 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
519 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
520 CanDeclareSpecialMemberFunction(S.Context, Record))
521 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000522 break;
523
524 case DeclarationName::CXXOperatorName:
525 if (Name.getCXXOverloadedOperator() != OO_Equal)
526 break;
527
528 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
529 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
530 CanDeclareSpecialMemberFunction(S.Context, Record))
531 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
532 break;
533
534 default:
535 break;
536 }
537}
Douglas Gregor7454c562010-07-02 20:37:36 +0000538
John McCall9f3059a2009-10-09 21:13:30 +0000539// Adds all qualifying matches for a name within a decl context to the
540// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000541static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000542 bool Found = false;
543
Douglas Gregor7454c562010-07-02 20:37:36 +0000544 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000545 if (S.getLangOptions().CPlusPlus)
546 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor7454c562010-07-02 20:37:36 +0000547
548 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000549 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000550 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000551 NamedDecl *D = *I;
552 if (R.isAcceptableDecl(D)) {
553 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000554 Found = true;
555 }
556 }
John McCall9f3059a2009-10-09 21:13:30 +0000557
Douglas Gregord3a59182010-02-12 05:48:04 +0000558 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
559 return true;
560
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000561 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000562 != DeclarationName::CXXConversionFunctionName ||
563 R.getLookupName().getCXXNameType()->isDependentType() ||
564 !isa<CXXRecordDecl>(DC))
565 return Found;
566
567 // C++ [temp.mem]p6:
568 // A specialization of a conversion function template is not found by
569 // name lookup. Instead, any conversion function templates visible in the
570 // context of the use are considered. [...]
571 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
572 if (!Record->isDefinition())
573 return Found;
574
575 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
576 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
577 UEnd = Unresolved->end(); U != UEnd; ++U) {
578 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
579 if (!ConvTemplate)
580 continue;
581
582 // When we're performing lookup for the purposes of redeclaration, just
583 // add the conversion function template. When we deduce template
584 // arguments for specializations, we'll end up unifying the return
585 // type of the new declaration with the type of the function template.
586 if (R.isForRedeclaration()) {
587 R.addDecl(ConvTemplate);
588 Found = true;
589 continue;
590 }
591
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000592 // C++ [temp.mem]p6:
Chandler Carruth3a693b72010-01-31 11:44:02 +0000593 // [...] For each such operator, if argument deduction succeeds
594 // (14.9.2.3), the resulting specialization is used as if found by
595 // name lookup.
596 //
597 // When referencing a conversion function for any purpose other than
598 // a redeclaration (such that we'll be building an expression with the
599 // result), perform template argument deduction and place the
600 // specialization into the result set. We do this to avoid forcing all
601 // callers to perform special deduction for conversion functions.
John McCallbc077cf2010-02-08 23:07:23 +0000602 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000603 FunctionDecl *Specialization = 0;
604
605 const FunctionProtoType *ConvProto
606 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
607 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000608
Chandler Carruth3a693b72010-01-31 11:44:02 +0000609 // Compute the type of the function that we would expect the conversion
610 // function to have, if it were to match the name given.
611 // FIXME: Calling convention!
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000612 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruth3a693b72010-01-31 11:44:02 +0000613 QualType ExpectedType
614 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
615 0, 0, ConvProto->isVariadic(),
616 ConvProto->getTypeQuals(),
617 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000618 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruth3a693b72010-01-31 11:44:02 +0000619
620 // Perform template argument deduction against the type that we would
621 // expect the function to have.
622 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
623 Specialization, Info)
624 == Sema::TDK_Success) {
625 R.addDecl(Specialization);
626 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000627 }
628 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000629
John McCall9f3059a2009-10-09 21:13:30 +0000630 return Found;
631}
632
John McCallf6c8a4e2009-11-10 07:01:13 +0000633// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000634static bool
Douglas Gregord3a59182010-02-12 05:48:04 +0000635CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
636 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000637
638 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
639
John McCallf6c8a4e2009-11-10 07:01:13 +0000640 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000641 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000642
John McCallf6c8a4e2009-11-10 07:01:13 +0000643 // Perform direct name lookup into the namespaces nominated by the
644 // using directives whose common ancestor is this namespace.
645 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
646 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000647
John McCallf6c8a4e2009-11-10 07:01:13 +0000648 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000649 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000650 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000651
652 R.resolveKind();
653
654 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000655}
656
657static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000658 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000659 return Ctx->isFileContext();
660 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000661}
Douglas Gregored8f2882009-01-30 01:04:22 +0000662
Douglas Gregor66230062010-03-15 14:33:29 +0000663// Find the next outer declaration context from this scope. This
664// routine actually returns the semantic outer context, which may
665// differ from the lexical context (encoded directly in the Scope
666// stack) when we are parsing a member of a class template. In this
667// case, the second element of the pair will be true, to indicate that
668// name lookup should continue searching in this semantic context when
669// it leaves the current template parameter scope.
670static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
671 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
672 DeclContext *Lexical = 0;
673 for (Scope *OuterS = S->getParent(); OuterS;
674 OuterS = OuterS->getParent()) {
675 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000676 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000677 break;
678 }
679 }
680
681 // C++ [temp.local]p8:
682 // In the definition of a member of a class template that appears
683 // outside of the namespace containing the class template
684 // definition, the name of a template-parameter hides the name of
685 // a member of this namespace.
686 //
687 // Example:
688 //
689 // namespace N {
690 // class C { };
691 //
692 // template<class T> class B {
693 // void f(T);
694 // };
695 // }
696 //
697 // template<class C> void N::B<C>::f(C) {
698 // C b; // C is the template parameter, not N::C
699 // }
700 //
701 // In this example, the lexical context we return is the
702 // TranslationUnit, while the semantic context is the namespace N.
703 if (!Lexical || !DC || !S->getParent() ||
704 !S->getParent()->isTemplateParamScope())
705 return std::make_pair(Lexical, false);
706
707 // Find the outermost template parameter scope.
708 // For the example, this is the scope for the template parameters of
709 // template<class C>.
710 Scope *OutermostTemplateScope = S->getParent();
711 while (OutermostTemplateScope->getParent() &&
712 OutermostTemplateScope->getParent()->isTemplateParamScope())
713 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregor7f737c02009-09-10 16:57:35 +0000714
Douglas Gregor66230062010-03-15 14:33:29 +0000715 // Find the namespace context in which the original scope occurs. In
716 // the example, this is namespace N.
717 DeclContext *Semantic = DC;
718 while (!Semantic->isFileContext())
719 Semantic = Semantic->getParent();
720
721 // Find the declaration context just outside of the template
722 // parameter scope. This is the context in which the template is
723 // being lexically declaration (a namespace context). In the
724 // example, this is the global scope.
725 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
726 Lexical->Encloses(Semantic))
727 return std::make_pair(Semantic, true);
728
729 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000730}
731
John McCall27b18f82009-11-17 02:14:36 +0000732bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000733 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000734
735 DeclarationName Name = R.getLookupName();
736
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000737 // If this is the name of an implicitly-declared special member function,
738 // go through the scope stack to implicitly declare
739 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
740 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
741 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
742 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
743 }
744
745 // Implicitly declare member functions with the name we're looking for, if in
746 // fact we are in a scope where it matters.
747
Douglas Gregor889ceb72009-02-03 19:21:40 +0000748 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000749 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000750 I = IdResolver.begin(Name),
751 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000752
Douglas Gregor889ceb72009-02-03 19:21:40 +0000753 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000754 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000755 // ...During unqualified name lookup (3.4.1), the names appear as if
756 // they were declared in the nearest enclosing namespace which contains
757 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000758 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000759 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000760 //
761 // For example:
762 // namespace A { int i; }
763 // void foo() {
764 // int i;
765 // {
766 // using namespace A;
767 // ++i; // finds local 'i', A::i appears at global scope
768 // }
769 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000770 //
Douglas Gregor66230062010-03-15 14:33:29 +0000771 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000772 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000773 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
774
Douglas Gregor889ceb72009-02-03 19:21:40 +0000775 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000776 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000777 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000778 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000779 Found = true;
780 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000781 }
782 }
John McCall9f3059a2009-10-09 21:13:30 +0000783 if (Found) {
784 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000785 if (S->isClassScope())
786 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
787 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000788 return true;
789 }
790
Douglas Gregor66230062010-03-15 14:33:29 +0000791 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
792 S->getParent() && !S->getParent()->isTemplateParamScope()) {
793 // We've just searched the last template parameter scope and
794 // found nothing, so look into the the contexts between the
795 // lexical and semantic declaration contexts returned by
796 // findOuterContext(). This implements the name lookup behavior
797 // of C++ [temp.local]p8.
798 Ctx = OutsideOfTemplateParamDC;
799 OutsideOfTemplateParamDC = 0;
800 }
801
802 if (Ctx) {
803 DeclContext *OuterCtx;
804 bool SearchAfterTemplateScope;
805 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
806 if (SearchAfterTemplateScope)
807 OutsideOfTemplateParamDC = OuterCtx;
808
Douglas Gregorea166062010-03-15 15:26:48 +0000809 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000810 // We do not directly look into transparent contexts, since
811 // those entities will be found in the nearest enclosing
812 // non-transparent context.
813 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000814 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000815
816 // We do not look directly into function or method contexts,
817 // since all of the local variables and parameters of the
818 // function/method are present within the Scope.
819 if (Ctx->isFunctionOrMethod()) {
820 // If we have an Objective-C instance method, look for ivars
821 // in the corresponding interface.
822 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
823 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
824 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
825 ObjCInterfaceDecl *ClassDeclared;
826 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
827 Name.getAsIdentifierInfo(),
828 ClassDeclared)) {
829 if (R.isAcceptableDecl(Ivar)) {
830 R.addDecl(Ivar);
831 R.resolveKind();
832 return true;
833 }
834 }
835 }
836 }
837
838 continue;
839 }
840
Douglas Gregor7f737c02009-09-10 16:57:35 +0000841 // Perform qualified name lookup into this context.
842 // FIXME: In some cases, we know that every name that could be found by
843 // this qualified name lookup will also be on the identifier chain. For
844 // example, inside a class without any base classes, we never need to
845 // perform qualified lookup because all of the members are on top of the
846 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000847 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000848 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000849 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000850 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000851 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000852
John McCallf6c8a4e2009-11-10 07:01:13 +0000853 // Stop if we ran out of scopes.
854 // FIXME: This really, really shouldn't be happening.
855 if (!S) return false;
856
Douglas Gregor700792c2009-02-05 19:25:20 +0000857 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000858 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000859 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000860 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
861 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000862
John McCallf6c8a4e2009-11-10 07:01:13 +0000863 UnqualUsingDirectiveSet UDirs;
864 UDirs.visitScopeChain(Initial, S);
865 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000866
Douglas Gregor700792c2009-02-05 19:25:20 +0000867 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000868 // Unqualified name lookup in C++ requires looking into scopes
869 // that aren't strictly lexical, and therefore we walk through the
870 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000871
Douglas Gregor889ceb72009-02-03 19:21:40 +0000872 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000873 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000874 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000875 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000876 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000877 // We found something. Look for anything else in our scope
878 // with this same name and in an acceptable identifier
879 // namespace, so that we can construct an overload set if we
880 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000881 Found = true;
882 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000883 }
884 }
885
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000886 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000887 R.resolveKind();
888 return true;
889 }
890
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000891 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
892 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
893 S->getParent() && !S->getParent()->isTemplateParamScope()) {
894 // We've just searched the last template parameter scope and
895 // found nothing, so look into the the contexts between the
896 // lexical and semantic declaration contexts returned by
897 // findOuterContext(). This implements the name lookup behavior
898 // of C++ [temp.local]p8.
899 Ctx = OutsideOfTemplateParamDC;
900 OutsideOfTemplateParamDC = 0;
901 }
902
903 if (Ctx) {
904 DeclContext *OuterCtx;
905 bool SearchAfterTemplateScope;
906 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
907 if (SearchAfterTemplateScope)
908 OutsideOfTemplateParamDC = OuterCtx;
909
910 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
911 // We do not directly look into transparent contexts, since
912 // those entities will be found in the nearest enclosing
913 // non-transparent context.
914 if (Ctx->isTransparentContext())
915 continue;
916
917 // If we have a context, and it's not a context stashed in the
918 // template parameter scope for an out-of-line definition, also
919 // look into that context.
920 if (!(Found && S && S->isTemplateParamScope())) {
921 assert(Ctx->isFileContext() &&
922 "We should have been looking only at file context here already.");
923
924 // Look into context considering using-directives.
925 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
926 Found = true;
927 }
928
929 if (Found) {
930 R.resolveKind();
931 return true;
932 }
933
934 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
935 return false;
936 }
937 }
938
Douglas Gregor3ce74932010-02-05 07:07:10 +0000939 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000940 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000941 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000942
John McCall9f3059a2009-10-09 21:13:30 +0000943 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000944}
945
Douglas Gregor34074322009-01-14 22:20:51 +0000946/// @brief Perform unqualified name lookup starting from a given
947/// scope.
948///
949/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
950/// used to find names within the current scope. For example, 'x' in
951/// @code
952/// int x;
953/// int f() {
954/// return x; // unqualified name look finds 'x' in the global scope
955/// }
956/// @endcode
957///
958/// Different lookup criteria can find different names. For example, a
959/// particular scope can have both a struct and a function of the same
960/// name, and each can be found by certain lookup criteria. For more
961/// information about lookup criteria, see the documentation for the
962/// class LookupCriteria.
963///
964/// @param S The scope from which unqualified name lookup will
965/// begin. If the lookup criteria permits, name lookup may also search
966/// in the parent scopes.
967///
968/// @param Name The name of the entity that we are searching for.
969///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000970/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000971/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000972/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000973///
974/// @returns The result of name lookup, which includes zero or more
975/// declarations and possibly additional information used to diagnose
976/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000977bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
978 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +0000979 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000980
John McCall27b18f82009-11-17 02:14:36 +0000981 LookupNameKind NameKind = R.getLookupKind();
982
Douglas Gregor34074322009-01-14 22:20:51 +0000983 if (!getLangOptions().CPlusPlus) {
984 // Unqualified name lookup in C/Objective-C is purely lexical, so
985 // search in the declarations attached to the name.
986
John McCallea305ed2009-12-18 10:40:03 +0000987 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000988 // Find the nearest non-transparent declaration scope.
989 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000990 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000991 static_cast<DeclContext *>(S->getEntity())
992 ->isTransparentContext()))
993 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +0000994 }
995
John McCallea305ed2009-12-18 10:40:03 +0000996 unsigned IDNS = R.getIdentifierNamespace();
997
Douglas Gregor34074322009-01-14 22:20:51 +0000998 // Scan up the scope chain looking for a decl that matches this
999 // identifier that is in the appropriate namespace. This search
1000 // should not take long, as shadowing of names is uncommon, and
1001 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001002 bool LeftStartingScope = false;
1003
Douglas Gregored8f2882009-01-30 01:04:22 +00001004 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001005 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001006 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001007 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001008 if (NameKind == LookupRedeclarationWithLinkage) {
1009 // Determine whether this (or a previous) declaration is
1010 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00001011 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001012 LeftStartingScope = true;
1013
1014 // If we found something outside of our starting scope that
1015 // does not have linkage, skip it.
1016 if (LeftStartingScope && !((*I)->hasLinkage()))
1017 continue;
1018 }
1019
John McCall9f3059a2009-10-09 21:13:30 +00001020 R.addDecl(*I);
1021
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001022 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001023 // If this declaration has the "overloadable" attribute, we
1024 // might have a set of overloaded functions.
1025
1026 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001027 while (!(S->getFlags() & Scope::DeclScope) ||
1028 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001029 S = S->getParent();
1030
1031 // Find the last declaration in this scope (with the same
1032 // name, naturally).
1033 IdentifierResolver::iterator LastI = I;
1034 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +00001035 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001036 break;
John McCall9f3059a2009-10-09 21:13:30 +00001037 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001038 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001039 }
1040
John McCall9f3059a2009-10-09 21:13:30 +00001041 R.resolveKind();
1042
1043 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001044 }
Douglas Gregor34074322009-01-14 22:20:51 +00001045 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001046 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001047 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001048 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001049 }
1050
1051 // If we didn't find a use of this identifier, and if the identifier
1052 // corresponds to a compiler builtin, create the decl object for the builtin
1053 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +00001054 if (AllowBuiltinCreation)
1055 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001056
John McCall9f3059a2009-10-09 21:13:30 +00001057 return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001058}
1059
John McCall6538c932009-10-10 05:48:19 +00001060/// @brief Perform qualified name lookup in the namespaces nominated by
1061/// using directives by the given context.
1062///
1063/// C++98 [namespace.qual]p2:
1064/// Given X::m (where X is a user-declared namespace), or given ::m
1065/// (where X is the global namespace), let S be the set of all
1066/// declarations of m in X and in the transitive closure of all
1067/// namespaces nominated by using-directives in X and its used
1068/// namespaces, except that using-directives are ignored in any
1069/// namespace, including X, directly containing one or more
1070/// declarations of m. No namespace is searched more than once in
1071/// the lookup of a name. If S is the empty set, the program is
1072/// ill-formed. Otherwise, if S has exactly one member, or if the
1073/// context of the reference is a using-declaration
1074/// (namespace.udecl), S is the required set of declarations of
1075/// m. Otherwise if the use of m is not one that allows a unique
1076/// declaration to be chosen from S, the program is ill-formed.
1077/// C++98 [namespace.qual]p5:
1078/// During the lookup of a qualified namespace member name, if the
1079/// lookup finds more than one declaration of the member, and if one
1080/// declaration introduces a class name or enumeration name and the
1081/// other declarations either introduce the same object, the same
1082/// enumerator or a set of functions, the non-type name hides the
1083/// class or enumeration name if and only if the declarations are
1084/// from the same namespace; otherwise (the declarations are from
1085/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001086static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001087 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001088 assert(StartDC->isFileContext() && "start context is not a file context");
1089
1090 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1091 DeclContext::udir_iterator E = StartDC->using_directives_end();
1092
1093 if (I == E) return false;
1094
1095 // We have at least added all these contexts to the queue.
1096 llvm::DenseSet<DeclContext*> Visited;
1097 Visited.insert(StartDC);
1098
1099 // We have not yet looked into these namespaces, much less added
1100 // their "using-children" to the queue.
1101 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1102
1103 // We have already looked into the initial namespace; seed the queue
1104 // with its using-children.
1105 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001106 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001107 if (Visited.insert(ND).second)
1108 Queue.push_back(ND);
1109 }
1110
1111 // The easiest way to implement the restriction in [namespace.qual]p5
1112 // is to check whether any of the individual results found a tag
1113 // and, if so, to declare an ambiguity if the final result is not
1114 // a tag.
1115 bool FoundTag = false;
1116 bool FoundNonTag = false;
1117
John McCall5cebab12009-11-18 07:57:50 +00001118 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001119
1120 bool Found = false;
1121 while (!Queue.empty()) {
1122 NamespaceDecl *ND = Queue.back();
1123 Queue.pop_back();
1124
1125 // We go through some convolutions here to avoid copying results
1126 // between LookupResults.
1127 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001128 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001129 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001130
1131 if (FoundDirect) {
1132 // First do any local hiding.
1133 DirectR.resolveKind();
1134
1135 // If the local result is a tag, remember that.
1136 if (DirectR.isSingleTagDecl())
1137 FoundTag = true;
1138 else
1139 FoundNonTag = true;
1140
1141 // Append the local results to the total results if necessary.
1142 if (UseLocal) {
1143 R.addAllDecls(LocalR);
1144 LocalR.clear();
1145 }
1146 }
1147
1148 // If we find names in this namespace, ignore its using directives.
1149 if (FoundDirect) {
1150 Found = true;
1151 continue;
1152 }
1153
1154 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1155 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1156 if (Visited.insert(Nom).second)
1157 Queue.push_back(Nom);
1158 }
1159 }
1160
1161 if (Found) {
1162 if (FoundTag && FoundNonTag)
1163 R.setAmbiguousQualifiedTagHiding();
1164 else
1165 R.resolveKind();
1166 }
1167
1168 return Found;
1169}
1170
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001171/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001172///
1173/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1174/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001175/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001176///
1177/// Different lookup criteria can find different names. For example, a
1178/// particular scope can have both a struct and a function of the same
1179/// name, and each can be found by certain lookup criteria. For more
1180/// information about lookup criteria, see the documentation for the
1181/// class LookupCriteria.
1182///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001183/// \param R captures both the lookup criteria and any lookup results found.
1184///
1185/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001186/// search. If the lookup criteria permits, name lookup may also search
1187/// in the parent contexts or (for C++ classes) base classes.
1188///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001189/// \param InUnqualifiedLookup true if this is qualified name lookup that
1190/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001191///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001192/// \returns true if lookup succeeded, false if it failed.
1193bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1194 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001195 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001196
John McCall27b18f82009-11-17 02:14:36 +00001197 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001198 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001199
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001200 // Make sure that the declaration context is complete.
1201 assert((!isa<TagDecl>(LookupCtx) ||
1202 LookupCtx->isDependentContext() ||
1203 cast<TagDecl>(LookupCtx)->isDefinition() ||
1204 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1205 ->isBeingDefined()) &&
1206 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001207
Douglas Gregor34074322009-01-14 22:20:51 +00001208 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001209 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001210 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001211 if (isa<CXXRecordDecl>(LookupCtx))
1212 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001213 return true;
1214 }
Douglas Gregor34074322009-01-14 22:20:51 +00001215
John McCall6538c932009-10-10 05:48:19 +00001216 // Don't descend into implied contexts for redeclarations.
1217 // C++98 [namespace.qual]p6:
1218 // In a declaration for a namespace member in which the
1219 // declarator-id is a qualified-id, given that the qualified-id
1220 // for the namespace member has the form
1221 // nested-name-specifier unqualified-id
1222 // the unqualified-id shall name a member of the namespace
1223 // designated by the nested-name-specifier.
1224 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001225 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001226 return false;
1227
John McCall27b18f82009-11-17 02:14:36 +00001228 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001229 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001230 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001231
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001232 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001233 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001234 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001235 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001236 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001237
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001238 // If we're performing qualified name lookup into a dependent class,
1239 // then we are actually looking into a current instantiation. If we have any
1240 // dependent base classes, then we either have to delay lookup until
1241 // template instantiation time (at which point all bases will be available)
1242 // or we have to fail.
1243 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1244 LookupRec->hasAnyDependentBases()) {
1245 R.setNotFoundInCurrentInstantiation();
1246 return false;
1247 }
1248
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001249 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001250 CXXBasePaths Paths;
1251 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001252
1253 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001254 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001255 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001256 case LookupOrdinaryName:
1257 case LookupMemberName:
1258 case LookupRedeclarationWithLinkage:
1259 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1260 break;
1261
1262 case LookupTagName:
1263 BaseCallback = &CXXRecordDecl::FindTagMember;
1264 break;
John McCall84d87672009-12-10 09:41:52 +00001265
1266 case LookupUsingDeclName:
1267 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001268
1269 case LookupOperatorName:
1270 case LookupNamespaceName:
1271 case LookupObjCProtocolName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001272 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001273 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001274
1275 case LookupNestedNameSpecifierName:
1276 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1277 break;
1278 }
1279
John McCall27b18f82009-11-17 02:14:36 +00001280 if (!LookupRec->lookupInBases(BaseCallback,
1281 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001282 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001283
John McCall553c0792010-01-23 00:46:32 +00001284 R.setNamingClass(LookupRec);
1285
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001286 // C++ [class.member.lookup]p2:
1287 // [...] If the resulting set of declarations are not all from
1288 // sub-objects of the same type, or the set has a nonstatic member
1289 // and includes members from distinct sub-objects, there is an
1290 // ambiguity and the program is ill-formed. Otherwise that set is
1291 // the result of the lookup.
1292 // FIXME: support using declarations!
1293 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001294 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001295 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001296 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001297 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001298 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001299
John McCall401982f2010-01-20 21:53:11 +00001300 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1301 // across all paths.
1302 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1303
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001304 // Determine whether we're looking at a distinct sub-object or not.
1305 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001306 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001307 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1308 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001309 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001310 != Context.getCanonicalType(PathElement.Base->getType())) {
1311 // We found members of the given name in two subobjects of
1312 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001313 R.setAmbiguousBaseSubobjectTypes(Paths);
1314 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001315 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1316 // We have a different subobject of the same type.
1317
1318 // C++ [class.member.lookup]p5:
1319 // A static member, a nested type or an enumerator defined in
1320 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001321 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001322 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001323 if (isa<VarDecl>(FirstDecl) ||
1324 isa<TypeDecl>(FirstDecl) ||
1325 isa<EnumConstantDecl>(FirstDecl))
1326 continue;
1327
1328 if (isa<CXXMethodDecl>(FirstDecl)) {
1329 // Determine whether all of the methods are static.
1330 bool AllMethodsAreStatic = true;
1331 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1332 Func != Path->Decls.second; ++Func) {
1333 if (!isa<CXXMethodDecl>(*Func)) {
1334 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1335 break;
1336 }
1337
1338 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1339 AllMethodsAreStatic = false;
1340 break;
1341 }
1342 }
1343
1344 if (AllMethodsAreStatic)
1345 continue;
1346 }
1347
1348 // We have found a nonstatic member name in multiple, distinct
1349 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001350 R.setAmbiguousBaseSubobjects(Paths);
1351 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001352 }
1353 }
1354
1355 // Lookup in a base class succeeded; return these results.
1356
John McCall9f3059a2009-10-09 21:13:30 +00001357 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001358 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1359 NamedDecl *D = *I;
1360 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1361 D->getAccess());
1362 R.addDecl(D, AS);
1363 }
John McCall9f3059a2009-10-09 21:13:30 +00001364 R.resolveKind();
1365 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001366}
1367
1368/// @brief Performs name lookup for a name that was parsed in the
1369/// source code, and may contain a C++ scope specifier.
1370///
1371/// This routine is a convenience routine meant to be called from
1372/// contexts that receive a name and an optional C++ scope specifier
1373/// (e.g., "N::M::x"). It will then perform either qualified or
1374/// unqualified name lookup (with LookupQualifiedName or LookupName,
1375/// respectively) on the given name and return those results.
1376///
1377/// @param S The scope from which unqualified name lookup will
1378/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001379///
Douglas Gregore861bac2009-08-25 22:51:20 +00001380/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001381///
1382/// @param Name The name of the entity that name lookup will
1383/// search for.
1384///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001385/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001386/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001387/// C library functions (like "malloc") are implicitly declared.
1388///
Douglas Gregore861bac2009-08-25 22:51:20 +00001389/// @param EnteringContext Indicates whether we are going to enter the
1390/// context of the scope-specifier SS (if present).
1391///
John McCall9f3059a2009-10-09 21:13:30 +00001392/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001393bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001394 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001395 if (SS && SS->isInvalid()) {
1396 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001397 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001398 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001399 }
Mike Stump11289f42009-09-09 15:08:12 +00001400
Douglas Gregore861bac2009-08-25 22:51:20 +00001401 if (SS && SS->isSet()) {
1402 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001403 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001404 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001405 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001406 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001407
John McCall27b18f82009-11-17 02:14:36 +00001408 R.setContextRange(SS->getRange());
1409
1410 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001411 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001412
Douglas Gregore861bac2009-08-25 22:51:20 +00001413 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001414 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001415 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001416 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001417 }
1418
Mike Stump11289f42009-09-09 15:08:12 +00001419 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001420 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001421}
1422
Douglas Gregor889ceb72009-02-03 19:21:40 +00001423
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001424/// @brief Produce a diagnostic describing the ambiguity that resulted
1425/// from name lookup.
1426///
1427/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001428///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001429/// @param Name The name of the entity that name lookup was
1430/// searching for.
1431///
1432/// @param NameLoc The location of the name within the source code.
1433///
1434/// @param LookupRange A source range that provides more
1435/// source-location information concerning the lookup itself. For
1436/// example, this range might highlight a nested-name-specifier that
1437/// precedes the name.
1438///
1439/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001440bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001441 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1442
John McCall27b18f82009-11-17 02:14:36 +00001443 DeclarationName Name = Result.getLookupName();
1444 SourceLocation NameLoc = Result.getNameLoc();
1445 SourceRange LookupRange = Result.getContextRange();
1446
John McCall6538c932009-10-10 05:48:19 +00001447 switch (Result.getAmbiguityKind()) {
1448 case LookupResult::AmbiguousBaseSubobjects: {
1449 CXXBasePaths *Paths = Result.getBasePaths();
1450 QualType SubobjectType = Paths->front().back().Base->getType();
1451 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1452 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1453 << LookupRange;
1454
1455 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1456 while (isa<CXXMethodDecl>(*Found) &&
1457 cast<CXXMethodDecl>(*Found)->isStatic())
1458 ++Found;
1459
1460 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1461
1462 return true;
1463 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001464
John McCall6538c932009-10-10 05:48:19 +00001465 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001466 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1467 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001468
1469 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001470 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001471 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1472 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001473 Path != PathEnd; ++Path) {
1474 Decl *D = *Path->Decls.first;
1475 if (DeclsPrinted.insert(D).second)
1476 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1477 }
1478
Douglas Gregor1c846b02009-01-16 00:38:09 +00001479 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001480 }
1481
John McCall6538c932009-10-10 05:48:19 +00001482 case LookupResult::AmbiguousTagHiding: {
1483 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001484
John McCall6538c932009-10-10 05:48:19 +00001485 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1486
1487 LookupResult::iterator DI, DE = Result.end();
1488 for (DI = Result.begin(); DI != DE; ++DI)
1489 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1490 TagDecls.insert(TD);
1491 Diag(TD->getLocation(), diag::note_hidden_tag);
1492 }
1493
1494 for (DI = Result.begin(); DI != DE; ++DI)
1495 if (!isa<TagDecl>(*DI))
1496 Diag((*DI)->getLocation(), diag::note_hiding_object);
1497
1498 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001499 LookupResult::Filter F = Result.makeFilter();
1500 while (F.hasNext()) {
1501 if (TagDecls.count(F.next()))
1502 F.erase();
1503 }
1504 F.done();
John McCall6538c932009-10-10 05:48:19 +00001505
1506 return true;
1507 }
1508
1509 case LookupResult::AmbiguousReference: {
1510 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001511
John McCall6538c932009-10-10 05:48:19 +00001512 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1513 for (; DI != DE; ++DI)
1514 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001515
John McCall6538c932009-10-10 05:48:19 +00001516 return true;
1517 }
1518 }
1519
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001520 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001521 return true;
1522}
Douglas Gregore254f902009-02-04 00:32:51 +00001523
John McCallf24d7bb2010-05-28 18:45:08 +00001524namespace {
1525 struct AssociatedLookup {
1526 AssociatedLookup(Sema &S,
1527 Sema::AssociatedNamespaceSet &Namespaces,
1528 Sema::AssociatedClassSet &Classes)
1529 : S(S), Namespaces(Namespaces), Classes(Classes) {
1530 }
1531
1532 Sema &S;
1533 Sema::AssociatedNamespaceSet &Namespaces;
1534 Sema::AssociatedClassSet &Classes;
1535 };
1536}
1537
Mike Stump11289f42009-09-09 15:08:12 +00001538static void
John McCallf24d7bb2010-05-28 18:45:08 +00001539addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001540
Douglas Gregor8b895222010-04-30 07:08:38 +00001541static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1542 DeclContext *Ctx) {
1543 // Add the associated namespace for this class.
1544
1545 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1546 // be a locally scoped record.
1547
1548 while (Ctx->isRecord() || Ctx->isTransparentContext())
1549 Ctx = Ctx->getParent();
1550
John McCallc7e8e792009-08-07 22:18:02 +00001551 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001552 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001553}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001554
Mike Stump11289f42009-09-09 15:08:12 +00001555// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001556// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001557static void
John McCallf24d7bb2010-05-28 18:45:08 +00001558addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1559 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001560 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001561 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001562 switch (Arg.getKind()) {
1563 case TemplateArgument::Null:
1564 break;
Mike Stump11289f42009-09-09 15:08:12 +00001565
Douglas Gregor197e5f72009-07-08 07:51:57 +00001566 case TemplateArgument::Type:
1567 // [...] the namespaces and classes associated with the types of the
1568 // template arguments provided for template type parameters (excluding
1569 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001570 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001571 break;
Mike Stump11289f42009-09-09 15:08:12 +00001572
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001573 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001574 // [...] the namespaces in which any template template arguments are
1575 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001576 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001577 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001578 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001579 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001580 DeclContext *Ctx = ClassTemplate->getDeclContext();
1581 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001582 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001583 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001584 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001585 }
1586 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001587 }
1588
1589 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001590 case TemplateArgument::Integral:
1591 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001592 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001593 // associated namespaces. ]
1594 break;
Mike Stump11289f42009-09-09 15:08:12 +00001595
Douglas Gregor197e5f72009-07-08 07:51:57 +00001596 case TemplateArgument::Pack:
1597 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1598 PEnd = Arg.pack_end();
1599 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001600 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001601 break;
1602 }
1603}
1604
Douglas Gregore254f902009-02-04 00:32:51 +00001605// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001606// argument-dependent lookup with an argument of class type
1607// (C++ [basic.lookup.koenig]p2).
1608static void
John McCallf24d7bb2010-05-28 18:45:08 +00001609addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1610 CXXRecordDecl *Class) {
1611
1612 // Just silently ignore anything whose name is __va_list_tag.
1613 if (Class->getDeclName() == Result.S.VAListTagName)
1614 return;
1615
Douglas Gregore254f902009-02-04 00:32:51 +00001616 // C++ [basic.lookup.koenig]p2:
1617 // [...]
1618 // -- If T is a class type (including unions), its associated
1619 // classes are: the class itself; the class of which it is a
1620 // member, if any; and its direct and indirect base
1621 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001622 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001623
1624 // Add the class of which it is a member, if any.
1625 DeclContext *Ctx = Class->getDeclContext();
1626 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001627 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001628 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001629 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001630
Douglas Gregore254f902009-02-04 00:32:51 +00001631 // Add the class itself. If we've already seen this class, we don't
1632 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001633 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001634 return;
1635
Mike Stump11289f42009-09-09 15:08:12 +00001636 // -- If T is a template-id, its associated namespaces and classes are
1637 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001638 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001639 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001640 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001641 // namespaces in which any template template arguments are defined; and
1642 // the classes in which any member templates used as template template
1643 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001644 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001645 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001646 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1647 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1648 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001649 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001650 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001651 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001652
Douglas Gregor197e5f72009-07-08 07:51:57 +00001653 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1654 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001655 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001656 }
Mike Stump11289f42009-09-09 15:08:12 +00001657
John McCall67da35c2010-02-04 22:26:26 +00001658 // Only recurse into base classes for complete types.
1659 if (!Class->hasDefinition()) {
1660 // FIXME: we might need to instantiate templates here
1661 return;
1662 }
1663
Douglas Gregore254f902009-02-04 00:32:51 +00001664 // Add direct and indirect base classes along with their associated
1665 // namespaces.
1666 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1667 Bases.push_back(Class);
1668 while (!Bases.empty()) {
1669 // Pop this class off the stack.
1670 Class = Bases.back();
1671 Bases.pop_back();
1672
1673 // Visit the base classes.
1674 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1675 BaseEnd = Class->bases_end();
1676 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001677 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001678 // In dependent contexts, we do ADL twice, and the first time around,
1679 // the base type might be a dependent TemplateSpecializationType, or a
1680 // TemplateTypeParmType. If that happens, simply ignore it.
1681 // FIXME: If we want to support export, we probably need to add the
1682 // namespace of the template in a TemplateSpecializationType, or even
1683 // the classes and namespaces of known non-dependent arguments.
1684 if (!BaseType)
1685 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001686 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001687 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001688 // Find the associated namespace for this base class.
1689 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001690 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001691
1692 // Make sure we visit the bases of this base class.
1693 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1694 Bases.push_back(BaseDecl);
1695 }
1696 }
1697 }
1698}
1699
1700// \brief Add the associated classes and namespaces for
1701// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001702// (C++ [basic.lookup.koenig]p2).
1703static void
John McCallf24d7bb2010-05-28 18:45:08 +00001704addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001705 // C++ [basic.lookup.koenig]p2:
1706 //
1707 // For each argument type T in the function call, there is a set
1708 // of zero or more associated namespaces and a set of zero or more
1709 // associated classes to be considered. The sets of namespaces and
1710 // classes is determined entirely by the types of the function
1711 // arguments (and the namespace of any template template
1712 // argument). Typedef names and using-declarations used to specify
1713 // the types do not contribute to this set. The sets of namespaces
1714 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001715
John McCall0af3d3b2010-05-28 06:08:54 +00001716 llvm::SmallVector<const Type *, 16> Queue;
1717 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1718
Douglas Gregore254f902009-02-04 00:32:51 +00001719 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001720 switch (T->getTypeClass()) {
1721
1722#define TYPE(Class, Base)
1723#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1724#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1725#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1726#define ABSTRACT_TYPE(Class, Base)
1727#include "clang/AST/TypeNodes.def"
1728 // T is canonical. We can also ignore dependent types because
1729 // we don't need to do ADL at the definition point, but if we
1730 // wanted to implement template export (or if we find some other
1731 // use for associated classes and namespaces...) this would be
1732 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001733 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001734
John McCall0af3d3b2010-05-28 06:08:54 +00001735 // -- If T is a pointer to U or an array of U, its associated
1736 // namespaces and classes are those associated with U.
1737 case Type::Pointer:
1738 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1739 continue;
1740 case Type::ConstantArray:
1741 case Type::IncompleteArray:
1742 case Type::VariableArray:
1743 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1744 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001745
John McCall0af3d3b2010-05-28 06:08:54 +00001746 // -- If T is a fundamental type, its associated sets of
1747 // namespaces and classes are both empty.
1748 case Type::Builtin:
1749 break;
1750
1751 // -- If T is a class type (including unions), its associated
1752 // classes are: the class itself; the class of which it is a
1753 // member, if any; and its direct and indirect base
1754 // classes. Its associated namespaces are the namespaces in
1755 // which its associated classes are defined.
1756 case Type::Record: {
1757 CXXRecordDecl *Class
1758 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001759 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001760 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001761 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001762
John McCall0af3d3b2010-05-28 06:08:54 +00001763 // -- If T is an enumeration type, its associated namespace is
1764 // the namespace in which it is defined. If it is class
1765 // member, its associated class is the member’s class; else
1766 // it has no associated class.
1767 case Type::Enum: {
1768 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001769
John McCall0af3d3b2010-05-28 06:08:54 +00001770 DeclContext *Ctx = Enum->getDeclContext();
1771 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001772 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001773
John McCall0af3d3b2010-05-28 06:08:54 +00001774 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001775 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001776
John McCall0af3d3b2010-05-28 06:08:54 +00001777 break;
1778 }
1779
1780 // -- If T is a function type, its associated namespaces and
1781 // classes are those associated with the function parameter
1782 // types and those associated with the return type.
1783 case Type::FunctionProto: {
1784 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1785 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1786 ArgEnd = Proto->arg_type_end();
1787 Arg != ArgEnd; ++Arg)
1788 Queue.push_back(Arg->getTypePtr());
1789 // fallthrough
1790 }
1791 case Type::FunctionNoProto: {
1792 const FunctionType *FnType = cast<FunctionType>(T);
1793 T = FnType->getResultType().getTypePtr();
1794 continue;
1795 }
1796
1797 // -- If T is a pointer to a member function of a class X, its
1798 // associated namespaces and classes are those associated
1799 // with the function parameter types and return type,
1800 // together with those associated with X.
1801 //
1802 // -- If T is a pointer to a data member of class X, its
1803 // associated namespaces and classes are those associated
1804 // with the member type together with those associated with
1805 // X.
1806 case Type::MemberPointer: {
1807 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1808
1809 // Queue up the class type into which this points.
1810 Queue.push_back(MemberPtr->getClass());
1811
1812 // And directly continue with the pointee type.
1813 T = MemberPtr->getPointeeType().getTypePtr();
1814 continue;
1815 }
1816
1817 // As an extension, treat this like a normal pointer.
1818 case Type::BlockPointer:
1819 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1820 continue;
1821
1822 // References aren't covered by the standard, but that's such an
1823 // obvious defect that we cover them anyway.
1824 case Type::LValueReference:
1825 case Type::RValueReference:
1826 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1827 continue;
1828
1829 // These are fundamental types.
1830 case Type::Vector:
1831 case Type::ExtVector:
1832 case Type::Complex:
1833 break;
1834
1835 // These are ignored by ADL.
1836 case Type::ObjCObject:
1837 case Type::ObjCInterface:
1838 case Type::ObjCObjectPointer:
1839 break;
1840 }
1841
1842 if (Queue.empty()) break;
1843 T = Queue.back();
1844 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001845 }
Douglas Gregore254f902009-02-04 00:32:51 +00001846}
1847
1848/// \brief Find the associated classes and namespaces for
1849/// argument-dependent lookup for a call with the given set of
1850/// arguments.
1851///
1852/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001853/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001854/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001855void
Douglas Gregore254f902009-02-04 00:32:51 +00001856Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1857 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001858 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001859 AssociatedNamespaces.clear();
1860 AssociatedClasses.clear();
1861
John McCallf24d7bb2010-05-28 18:45:08 +00001862 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1863
Douglas Gregore254f902009-02-04 00:32:51 +00001864 // C++ [basic.lookup.koenig]p2:
1865 // For each argument type T in the function call, there is a set
1866 // of zero or more associated namespaces and a set of zero or more
1867 // associated classes to be considered. The sets of namespaces and
1868 // classes is determined entirely by the types of the function
1869 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001870 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001871 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1872 Expr *Arg = Args[ArgIdx];
1873
1874 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00001875 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001876 continue;
1877 }
1878
1879 // [...] In addition, if the argument is the name or address of a
1880 // set of overloaded functions and/or function templates, its
1881 // associated classes and namespaces are the union of those
1882 // associated with each of the members of the set: the namespace
1883 // in which the function or function template is defined and the
1884 // classes and namespaces associated with its (non-dependent)
1885 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001886 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001887 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1888 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1889 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001890
John McCallf24d7bb2010-05-28 18:45:08 +00001891 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1892 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00001893
John McCallf24d7bb2010-05-28 18:45:08 +00001894 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1895 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001896 // Look through any using declarations to find the underlying function.
1897 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001898
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001899 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1900 if (!FDecl)
1901 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001902
1903 // Add the classes and namespaces associated with the parameter
1904 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00001905 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001906 }
1907 }
1908}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001909
1910/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1911/// an acceptable non-member overloaded operator for a call whose
1912/// arguments have types T1 (and, if non-empty, T2). This routine
1913/// implements the check in C++ [over.match.oper]p3b2 concerning
1914/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001915static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001916IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1917 QualType T1, QualType T2,
1918 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001919 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1920 return true;
1921
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001922 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1923 return true;
1924
John McCall9dd450b2009-09-21 23:43:11 +00001925 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001926 if (Proto->getNumArgs() < 1)
1927 return false;
1928
1929 if (T1->isEnumeralType()) {
1930 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001931 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001932 return true;
1933 }
1934
1935 if (Proto->getNumArgs() < 2)
1936 return false;
1937
1938 if (!T2.isNull() && T2->isEnumeralType()) {
1939 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001940 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001941 return true;
1942 }
1943
1944 return false;
1945}
1946
John McCall5cebab12009-11-18 07:57:50 +00001947NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001948 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00001949 LookupNameKind NameKind,
1950 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001951 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00001952 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00001953 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00001954}
1955
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001956/// \brief Find the protocol with the given name, if any.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001957ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
1958 SourceLocation IdLoc) {
1959 Decl *D = LookupSingleName(TUScope, II, IdLoc,
1960 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001961 return cast_or_null<ObjCProtocolDecl>(D);
1962}
1963
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001964void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001965 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00001966 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001967 // C++ [over.match.oper]p3:
1968 // -- The set of non-member candidates is the result of the
1969 // unqualified lookup of operator@ in the context of the
1970 // expression according to the usual rules for name lookup in
1971 // unqualified function calls (3.4.2) except that all member
1972 // functions are ignored. However, if no operand has a class
1973 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001974 // that have a first parameter of type T1 or "reference to
1975 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001976 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001977 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001978 // when T2 is an enumeration type, are candidate functions.
1979 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00001980 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1981 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00001982
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001983 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1984
John McCall9f3059a2009-10-09 21:13:30 +00001985 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001986 return;
1987
1988 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1989 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00001990 NamedDecl *Found = (*Op)->getUnderlyingDecl();
1991 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001992 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00001993 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001994 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00001995 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001996 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001997 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001998 // later?
1999 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002000 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002001 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002002 }
2003}
2004
Douglas Gregor52b72822010-07-02 23:12:18 +00002005/// \brief Look up the constructors for the given class.
2006DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +00002007 // If the copy constructor has not yet been declared, do so now.
2008 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2009 !Class->hasDeclaredCopyConstructor())
2010 DeclareImplicitCopyConstructor(Class);
2011
Douglas Gregor52b72822010-07-02 23:12:18 +00002012 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2013 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2014 return Class->lookup(Name);
2015}
2016
Douglas Gregore71edda2010-07-01 22:47:18 +00002017/// \brief Look for the destructor of the given class.
2018///
2019/// During semantic analysis, this routine should be used in lieu of
2020/// CXXRecordDecl::getDestructor().
2021///
2022/// \returns The destructor for this class.
2023CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +00002024 // If the destructor has not yet been declared, do so now.
2025 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2026 !Class->hasDeclaredDestructor())
2027 DeclareImplicitDestructor(Class);
2028
Douglas Gregore71edda2010-07-01 22:47:18 +00002029 return Class->getDestructor();
2030}
2031
John McCall8fe68082010-01-26 07:16:45 +00002032void ADLResult::insert(NamedDecl *New) {
2033 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2034
2035 // If we haven't yet seen a decl for this key, or the last decl
2036 // was exactly this one, we're done.
2037 if (Old == 0 || Old == New) {
2038 Old = New;
2039 return;
2040 }
2041
2042 // Otherwise, decide which is a more recent redeclaration.
2043 FunctionDecl *OldFD, *NewFD;
2044 if (isa<FunctionTemplateDecl>(New)) {
2045 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2046 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2047 } else {
2048 OldFD = cast<FunctionDecl>(Old);
2049 NewFD = cast<FunctionDecl>(New);
2050 }
2051
2052 FunctionDecl *Cursor = NewFD;
2053 while (true) {
2054 Cursor = Cursor->getPreviousDeclaration();
2055
2056 // If we got to the end without finding OldFD, OldFD is the newer
2057 // declaration; leave things as they are.
2058 if (!Cursor) return;
2059
2060 // If we do find OldFD, then NewFD is newer.
2061 if (Cursor == OldFD) break;
2062
2063 // Otherwise, keep looking.
2064 }
2065
2066 Old = New;
2067}
2068
Sebastian Redlc057f422009-10-23 19:23:15 +00002069void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002070 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00002071 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002072 // Find all of the associated namespaces and classes based on the
2073 // arguments we have.
2074 AssociatedNamespaceSet AssociatedNamespaces;
2075 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002076 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002077 AssociatedNamespaces,
2078 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002079
Sebastian Redlc057f422009-10-23 19:23:15 +00002080 QualType T1, T2;
2081 if (Operator) {
2082 T1 = Args[0]->getType();
2083 if (NumArgs >= 2)
2084 T2 = Args[1]->getType();
2085 }
2086
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002087 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002088 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2089 // and let Y be the lookup set produced by argument dependent
2090 // lookup (defined as follows). If X contains [...] then Y is
2091 // empty. Otherwise Y is the set of declarations found in the
2092 // namespaces associated with the argument types as described
2093 // below. The set of declarations found by the lookup of the name
2094 // is the union of X and Y.
2095 //
2096 // Here, we compute Y and add its members to the overloaded
2097 // candidate set.
2098 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002099 NSEnd = AssociatedNamespaces.end();
2100 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002101 // When considering an associated namespace, the lookup is the
2102 // same as the lookup performed when the associated namespace is
2103 // used as a qualifier (3.4.3.2) except that:
2104 //
2105 // -- Any using-directives in the associated namespace are
2106 // ignored.
2107 //
John McCallc7e8e792009-08-07 22:18:02 +00002108 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002109 // associated classes are visible within their respective
2110 // namespaces even if they are not visible during an ordinary
2111 // lookup (11.4).
2112 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002113 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002114 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002115 // If the only declaration here is an ordinary friend, consider
2116 // it only if it was declared in an associated classes.
2117 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002118 DeclContext *LexDC = D->getLexicalDeclContext();
2119 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2120 continue;
2121 }
Mike Stump11289f42009-09-09 15:08:12 +00002122
John McCall91f61fc2010-01-26 06:04:06 +00002123 if (isa<UsingShadowDecl>(D))
2124 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002125
John McCall91f61fc2010-01-26 06:04:06 +00002126 if (isa<FunctionDecl>(D)) {
2127 if (Operator &&
2128 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2129 T1, T2, Context))
2130 continue;
John McCall8fe68082010-01-26 07:16:45 +00002131 } else if (!isa<FunctionTemplateDecl>(D))
2132 continue;
2133
2134 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002135 }
2136 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002137}
Douglas Gregor2d435302009-12-30 17:04:44 +00002138
2139//----------------------------------------------------------------------------
2140// Search for all visible declarations.
2141//----------------------------------------------------------------------------
2142VisibleDeclConsumer::~VisibleDeclConsumer() { }
2143
2144namespace {
2145
2146class ShadowContextRAII;
2147
2148class VisibleDeclsRecord {
2149public:
2150 /// \brief An entry in the shadow map, which is optimized to store a
2151 /// single declaration (the common case) but can also store a list
2152 /// of declarations.
2153 class ShadowMapEntry {
2154 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2155
2156 /// \brief Contains either the solitary NamedDecl * or a vector
2157 /// of declarations.
2158 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2159
2160 public:
2161 ShadowMapEntry() : DeclOrVector() { }
2162
2163 void Add(NamedDecl *ND);
2164 void Destroy();
2165
2166 // Iteration.
2167 typedef NamedDecl **iterator;
2168 iterator begin();
2169 iterator end();
2170 };
2171
2172private:
2173 /// \brief A mapping from declaration names to the declarations that have
2174 /// this name within a particular scope.
2175 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2176
2177 /// \brief A list of shadow maps, which is used to model name hiding.
2178 std::list<ShadowMap> ShadowMaps;
2179
2180 /// \brief The declaration contexts we have already visited.
2181 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2182
2183 friend class ShadowContextRAII;
2184
2185public:
2186 /// \brief Determine whether we have already visited this context
2187 /// (and, if not, note that we are going to visit that context now).
2188 bool visitedContext(DeclContext *Ctx) {
2189 return !VisitedContexts.insert(Ctx);
2190 }
2191
2192 /// \brief Determine whether the given declaration is hidden in the
2193 /// current scope.
2194 ///
2195 /// \returns the declaration that hides the given declaration, or
2196 /// NULL if no such declaration exists.
2197 NamedDecl *checkHidden(NamedDecl *ND);
2198
2199 /// \brief Add a declaration to the current shadow map.
2200 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2201};
2202
2203/// \brief RAII object that records when we've entered a shadow context.
2204class ShadowContextRAII {
2205 VisibleDeclsRecord &Visible;
2206
2207 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2208
2209public:
2210 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2211 Visible.ShadowMaps.push_back(ShadowMap());
2212 }
2213
2214 ~ShadowContextRAII() {
2215 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2216 EEnd = Visible.ShadowMaps.back().end();
2217 E != EEnd;
2218 ++E)
2219 E->second.Destroy();
2220
2221 Visible.ShadowMaps.pop_back();
2222 }
2223};
2224
2225} // end anonymous namespace
2226
2227void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2228 if (DeclOrVector.isNull()) {
2229 // 0 - > 1 elements: just set the single element information.
2230 DeclOrVector = ND;
2231 return;
2232 }
2233
2234 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2235 // 1 -> 2 elements: create the vector of results and push in the
2236 // existing declaration.
2237 DeclVector *Vec = new DeclVector;
2238 Vec->push_back(PrevND);
2239 DeclOrVector = Vec;
2240 }
2241
2242 // Add the new element to the end of the vector.
2243 DeclOrVector.get<DeclVector*>()->push_back(ND);
2244}
2245
2246void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2247 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2248 delete Vec;
2249 DeclOrVector = ((NamedDecl *)0);
2250 }
2251}
2252
2253VisibleDeclsRecord::ShadowMapEntry::iterator
2254VisibleDeclsRecord::ShadowMapEntry::begin() {
2255 if (DeclOrVector.isNull())
2256 return 0;
2257
2258 if (DeclOrVector.dyn_cast<NamedDecl *>())
2259 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2260
2261 return DeclOrVector.get<DeclVector *>()->begin();
2262}
2263
2264VisibleDeclsRecord::ShadowMapEntry::iterator
2265VisibleDeclsRecord::ShadowMapEntry::end() {
2266 if (DeclOrVector.isNull())
2267 return 0;
2268
2269 if (DeclOrVector.dyn_cast<NamedDecl *>())
2270 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2271
2272 return DeclOrVector.get<DeclVector *>()->end();
2273}
2274
2275NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002276 // Look through using declarations.
2277 ND = ND->getUnderlyingDecl();
2278
Douglas Gregor2d435302009-12-30 17:04:44 +00002279 unsigned IDNS = ND->getIdentifierNamespace();
2280 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2281 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2282 SM != SMEnd; ++SM) {
2283 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2284 if (Pos == SM->end())
2285 continue;
2286
2287 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2288 IEnd = Pos->second.end();
2289 I != IEnd; ++I) {
2290 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002291 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor2d435302009-12-30 17:04:44 +00002292 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2293 Decl::IDNS_ObjCProtocol)))
2294 continue;
2295
2296 // Protocols are in distinct namespaces from everything else.
2297 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2298 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2299 (*I)->getIdentifierNamespace() != IDNS)
2300 continue;
2301
Douglas Gregor09bbc652010-01-14 15:47:35 +00002302 // Functions and function templates in the same scope overload
2303 // rather than hide. FIXME: Look for hiding based on function
2304 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002305 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002306 ND->isFunctionOrFunctionTemplate() &&
2307 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002308 continue;
2309
Douglas Gregor2d435302009-12-30 17:04:44 +00002310 // We've found a declaration that hides this one.
2311 return *I;
2312 }
2313 }
2314
2315 return 0;
2316}
2317
2318static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2319 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002320 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002321 VisibleDeclConsumer &Consumer,
2322 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002323 if (!Ctx)
2324 return;
2325
Douglas Gregor2d435302009-12-30 17:04:44 +00002326 // Make sure we don't visit the same context twice.
2327 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2328 return;
2329
Douglas Gregor7454c562010-07-02 20:37:36 +00002330 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2331 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2332
Douglas Gregor2d435302009-12-30 17:04:44 +00002333 // Enumerate all of the results in this context.
2334 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2335 CurCtx = CurCtx->getNextContext()) {
2336 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2337 DEnd = CurCtx->decls_end();
2338 D != DEnd; ++D) {
2339 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2340 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002341 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002342 Visited.add(ND);
2343 }
2344
2345 // Visit transparent contexts inside this context.
2346 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2347 if (InnerCtx->isTransparentContext())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002348 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002349 Consumer, Visited);
2350 }
2351 }
2352 }
2353
2354 // Traverse using directives for qualified name lookup.
2355 if (QualifiedNameLookup) {
2356 ShadowContextRAII Shadow(Visited);
2357 DeclContext::udir_iterator I, E;
2358 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2359 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002360 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002361 }
2362 }
2363
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002364 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002365 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002366 if (!Record->hasDefinition())
2367 return;
2368
Douglas Gregor2d435302009-12-30 17:04:44 +00002369 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2370 BEnd = Record->bases_end();
2371 B != BEnd; ++B) {
2372 QualType BaseType = B->getType();
2373
2374 // Don't look into dependent bases, because name lookup can't look
2375 // there anyway.
2376 if (BaseType->isDependentType())
2377 continue;
2378
2379 const RecordType *Record = BaseType->getAs<RecordType>();
2380 if (!Record)
2381 continue;
2382
2383 // FIXME: It would be nice to be able to determine whether referencing
2384 // a particular member would be ambiguous. For example, given
2385 //
2386 // struct A { int member; };
2387 // struct B { int member; };
2388 // struct C : A, B { };
2389 //
2390 // void f(C *c) { c->### }
2391 //
2392 // accessing 'member' would result in an ambiguity. However, we
2393 // could be smart enough to qualify the member with the base
2394 // class, e.g.,
2395 //
2396 // c->B::member
2397 //
2398 // or
2399 //
2400 // c->A::member
2401
2402 // Find results in this base class (and its bases).
2403 ShadowContextRAII Shadow(Visited);
2404 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002405 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002406 }
2407 }
2408
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002409 // Traverse the contexts of Objective-C classes.
2410 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2411 // Traverse categories.
2412 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2413 Category; Category = Category->getNextClassCategory()) {
2414 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002415 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2416 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002417 }
2418
2419 // Traverse protocols.
2420 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2421 E = IFace->protocol_end(); I != E; ++I) {
2422 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002423 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2424 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002425 }
2426
2427 // Traverse the superclass.
2428 if (IFace->getSuperClass()) {
2429 ShadowContextRAII Shadow(Visited);
2430 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002431 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002432 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002433
2434 // If there is an implementation, traverse it. We do this to find
2435 // synthesized ivars.
2436 if (IFace->getImplementation()) {
2437 ShadowContextRAII Shadow(Visited);
2438 LookupVisibleDecls(IFace->getImplementation(), Result,
2439 QualifiedNameLookup, true, Consumer, Visited);
2440 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002441 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2442 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2443 E = Protocol->protocol_end(); I != E; ++I) {
2444 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002445 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2446 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002447 }
2448 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2449 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2450 E = Category->protocol_end(); I != E; ++I) {
2451 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002452 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2453 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002454 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002455
2456 // If there is an implementation, traverse it.
2457 if (Category->getImplementation()) {
2458 ShadowContextRAII Shadow(Visited);
2459 LookupVisibleDecls(Category->getImplementation(), Result,
2460 QualifiedNameLookup, true, Consumer, Visited);
2461 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002462 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002463}
2464
2465static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2466 UnqualUsingDirectiveSet &UDirs,
2467 VisibleDeclConsumer &Consumer,
2468 VisibleDeclsRecord &Visited) {
2469 if (!S)
2470 return;
2471
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002472 if (!S->getEntity() || !S->getParent() ||
2473 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2474 // Walk through the declarations in this Scope.
2475 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2476 D != DEnd; ++D) {
2477 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2478 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002479 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002480 Visited.add(ND);
2481 }
2482 }
2483 }
2484
Douglas Gregor66230062010-03-15 14:33:29 +00002485 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002486 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002487 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002488 // Look into this scope's declaration context, along with any of its
2489 // parent lookup contexts (e.g., enclosing classes), up to the point
2490 // where we hit the context stored in the next outer scope.
2491 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002492 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor2d435302009-12-30 17:04:44 +00002493
Douglas Gregorea166062010-03-15 15:26:48 +00002494 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002495 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002496 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2497 if (Method->isInstanceMethod()) {
2498 // For instance methods, look for ivars in the method's interface.
2499 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2500 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002501 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2502 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2503 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002504 }
2505
2506 // We've already performed all of the name lookup that we need
2507 // to for Objective-C methods; the next context will be the
2508 // outer scope.
2509 break;
2510 }
2511
Douglas Gregor2d435302009-12-30 17:04:44 +00002512 if (Ctx->isFunctionOrMethod())
2513 continue;
2514
2515 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002516 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002517 }
2518 } else if (!S->getParent()) {
2519 // Look into the translation unit scope. We walk through the translation
2520 // unit's declaration context, because the Scope itself won't have all of
2521 // the declarations if we loaded a precompiled header.
2522 // FIXME: We would like the translation unit's Scope object to point to the
2523 // translation unit, so we don't need this special "if" branch. However,
2524 // doing so would force the normal C++ name-lookup code to look into the
2525 // translation unit decl when the IdentifierInfo chains would suffice.
2526 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002527 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002528 Entity = Result.getSema().Context.getTranslationUnitDecl();
2529 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002530 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002531 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002532
2533 if (Entity) {
2534 // Lookup visible declarations in any namespaces found by using
2535 // directives.
2536 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2537 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2538 for (; UI != UEnd; ++UI)
2539 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002540 Result, /*QualifiedNameLookup=*/false,
2541 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002542 }
2543
2544 // Lookup names in the parent scope.
2545 ShadowContextRAII Shadow(Visited);
2546 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2547}
2548
2549void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2550 VisibleDeclConsumer &Consumer) {
2551 // Determine the set of using directives available during
2552 // unqualified name lookup.
2553 Scope *Initial = S;
2554 UnqualUsingDirectiveSet UDirs;
2555 if (getLangOptions().CPlusPlus) {
2556 // Find the first namespace or translation-unit scope.
2557 while (S && !isNamespaceOrTranslationUnitScope(S))
2558 S = S->getParent();
2559
2560 UDirs.visitScopeChain(Initial, S);
2561 }
2562 UDirs.done();
2563
2564 // Look for visible declarations.
2565 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2566 VisibleDeclsRecord Visited;
2567 ShadowContextRAII Shadow(Visited);
2568 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2569}
2570
2571void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2572 VisibleDeclConsumer &Consumer) {
2573 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2574 VisibleDeclsRecord Visited;
2575 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002576 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2577 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002578}
2579
2580//----------------------------------------------------------------------------
2581// Typo correction
2582//----------------------------------------------------------------------------
2583
2584namespace {
2585class TypoCorrectionConsumer : public VisibleDeclConsumer {
2586 /// \brief The name written that is a typo in the source.
2587 llvm::StringRef Typo;
2588
2589 /// \brief The results found that have the smallest edit distance
2590 /// found (so far) with the typo name.
2591 llvm::SmallVector<NamedDecl *, 4> BestResults;
2592
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002593 /// \brief The keywords that have the smallest edit distance.
2594 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2595
Douglas Gregor2d435302009-12-30 17:04:44 +00002596 /// \brief The best edit distance found so far.
2597 unsigned BestEditDistance;
2598
2599public:
2600 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2601 : Typo(Typo->getName()) { }
2602
Douglas Gregor09bbc652010-01-14 15:47:35 +00002603 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002604 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002605
2606 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2607 iterator begin() const { return BestResults.begin(); }
2608 iterator end() const { return BestResults.end(); }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002609 void clear_decls() { BestResults.clear(); }
2610
2611 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002612
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002613 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2614 keyword_iterator;
2615 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2616 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2617 bool keyword_empty() const { return BestKeywords.empty(); }
2618 unsigned keyword_size() const { return BestKeywords.size(); }
2619
2620 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002621};
2622
2623}
2624
Douglas Gregor09bbc652010-01-14 15:47:35 +00002625void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2626 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002627 // Don't consider hidden names for typo correction.
2628 if (Hiding)
2629 return;
2630
2631 // Only consider entities with identifiers for names, ignoring
2632 // special names (constructors, overloaded operators, selectors,
2633 // etc.).
2634 IdentifierInfo *Name = ND->getIdentifier();
2635 if (!Name)
2636 return;
2637
2638 // Compute the edit distance between the typo and the name of this
2639 // entity. If this edit distance is not worse than the best edit
2640 // distance we've seen so far, add it to the list of results.
2641 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002642 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002643 if (ED < BestEditDistance) {
2644 // This result is better than any we've seen before; clear out
2645 // the previous results.
2646 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002647 BestKeywords.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002648 BestEditDistance = ED;
2649 } else if (ED > BestEditDistance) {
2650 // This result is worse than the best results we've seen so far;
2651 // ignore it.
2652 return;
2653 }
2654 } else
2655 BestEditDistance = ED;
2656
2657 BestResults.push_back(ND);
2658}
2659
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002660void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2661 llvm::StringRef Keyword) {
2662 // Compute the edit distance between the typo and this keyword.
2663 // If this edit distance is not worse than the best edit
2664 // distance we've seen so far, add it to the list of results.
2665 unsigned ED = Typo.edit_distance(Keyword);
2666 if (!BestResults.empty() || !BestKeywords.empty()) {
2667 if (ED < BestEditDistance) {
2668 BestResults.clear();
2669 BestKeywords.clear();
2670 BestEditDistance = ED;
2671 } else if (ED > BestEditDistance) {
2672 // This result is worse than the best results we've seen so far;
2673 // ignore it.
2674 return;
2675 }
2676 } else
2677 BestEditDistance = ED;
2678
2679 BestKeywords.push_back(&Context.Idents.get(Keyword));
2680}
2681
Douglas Gregor2d435302009-12-30 17:04:44 +00002682/// \brief Try to "correct" a typo in the source code by finding
2683/// visible declarations whose names are similar to the name that was
2684/// present in the source code.
2685///
2686/// \param Res the \c LookupResult structure that contains the name
2687/// that was present in the source code along with the name-lookup
2688/// criteria used to search for the name. On success, this structure
2689/// will contain the results of name lookup.
2690///
2691/// \param S the scope in which name lookup occurs.
2692///
2693/// \param SS the nested-name-specifier that precedes the name we're
2694/// looking for, if present.
2695///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002696/// \param MemberContext if non-NULL, the context in which to look for
2697/// a member access expression.
2698///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002699/// \param EnteringContext whether we're entering the context described by
2700/// the nested-name-specifier SS.
2701///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002702/// \param CTC The context in which typo correction occurs, which impacts the
2703/// set of keywords permitted.
2704///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002705/// \param OPT when non-NULL, the search for visible declarations will
2706/// also walk the protocols in the qualified interfaces of \p OPT.
2707///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002708/// \returns the corrected name if the typo was corrected, otherwise returns an
2709/// empty \c DeclarationName. When a typo was corrected, the result structure
2710/// may contain the results of name lookup for the correct name or it may be
2711/// empty.
2712DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002713 DeclContext *MemberContext,
2714 bool EnteringContext,
2715 CorrectTypoContext CTC,
2716 const ObjCObjectPointerType *OPT) {
Ted Kremeneke51136e2010-01-06 00:23:04 +00002717 if (Diags.hasFatalErrorOccurred())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002718 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002719
2720 // Provide a stop gap for files that are just seriously broken. Trying
2721 // to correct all typos can turn into a HUGE performance penalty, causing
2722 // some files to take minutes to get rejected by the parser.
2723 // FIXME: Is this the right solution?
2724 if (TyposCorrected == 20)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002725 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002726 ++TyposCorrected;
Ted Kremeneke51136e2010-01-06 00:23:04 +00002727
Douglas Gregor2d435302009-12-30 17:04:44 +00002728 // We only attempt to correct typos for identifiers.
2729 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2730 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002731 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002732
2733 // If the scope specifier itself was invalid, don't try to correct
2734 // typos.
2735 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002736 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002737
2738 // Never try to correct typos during template deduction or
2739 // instantiation.
2740 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002741 return DeclarationName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002742
Douglas Gregor2d435302009-12-30 17:04:44 +00002743 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002744
2745 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002746 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002747 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002748
2749 // Look in qualified interfaces.
2750 if (OPT) {
2751 for (ObjCObjectPointerType::qual_iterator
2752 I = OPT->qual_begin(), E = OPT->qual_end();
2753 I != E; ++I)
2754 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2755 }
2756 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002757 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2758 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002759 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002760
2761 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2762 } else {
2763 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2764 }
2765
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002766 // Add context-dependent keywords.
2767 bool WantTypeSpecifiers = false;
2768 bool WantExpressionKeywords = false;
2769 bool WantCXXNamedCasts = false;
2770 bool WantRemainingKeywords = false;
2771 switch (CTC) {
2772 case CTC_Unknown:
2773 WantTypeSpecifiers = true;
2774 WantExpressionKeywords = true;
2775 WantCXXNamedCasts = true;
2776 WantRemainingKeywords = true;
Douglas Gregor5fd04d42010-05-18 16:14:23 +00002777
2778 if (ObjCMethodDecl *Method = getCurMethodDecl())
2779 if (Method->getClassInterface() &&
2780 Method->getClassInterface()->getSuperClass())
2781 Consumer.addKeywordResult(Context, "super");
2782
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002783 break;
2784
2785 case CTC_NoKeywords:
2786 break;
2787
2788 case CTC_Type:
2789 WantTypeSpecifiers = true;
2790 break;
2791
2792 case CTC_ObjCMessageReceiver:
2793 Consumer.addKeywordResult(Context, "super");
2794 // Fall through to handle message receivers like expressions.
2795
2796 case CTC_Expression:
2797 if (getLangOptions().CPlusPlus)
2798 WantTypeSpecifiers = true;
2799 WantExpressionKeywords = true;
2800 // Fall through to get C++ named casts.
2801
2802 case CTC_CXXCasts:
2803 WantCXXNamedCasts = true;
2804 break;
2805
2806 case CTC_MemberLookup:
2807 if (getLangOptions().CPlusPlus)
2808 Consumer.addKeywordResult(Context, "template");
2809 break;
2810 }
2811
2812 if (WantTypeSpecifiers) {
2813 // Add type-specifier keywords to the set of results.
2814 const char *CTypeSpecs[] = {
2815 "char", "const", "double", "enum", "float", "int", "long", "short",
2816 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2817 "_Complex", "_Imaginary",
2818 // storage-specifiers as well
2819 "extern", "inline", "static", "typedef"
2820 };
2821
2822 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2823 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2824 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2825
2826 if (getLangOptions().C99)
2827 Consumer.addKeywordResult(Context, "restrict");
2828 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2829 Consumer.addKeywordResult(Context, "bool");
2830
2831 if (getLangOptions().CPlusPlus) {
2832 Consumer.addKeywordResult(Context, "class");
2833 Consumer.addKeywordResult(Context, "typename");
2834 Consumer.addKeywordResult(Context, "wchar_t");
2835
2836 if (getLangOptions().CPlusPlus0x) {
2837 Consumer.addKeywordResult(Context, "char16_t");
2838 Consumer.addKeywordResult(Context, "char32_t");
2839 Consumer.addKeywordResult(Context, "constexpr");
2840 Consumer.addKeywordResult(Context, "decltype");
2841 Consumer.addKeywordResult(Context, "thread_local");
2842 }
2843 }
2844
2845 if (getLangOptions().GNUMode)
2846 Consumer.addKeywordResult(Context, "typeof");
2847 }
2848
Douglas Gregor86ad0852010-05-18 16:30:22 +00002849 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002850 Consumer.addKeywordResult(Context, "const_cast");
2851 Consumer.addKeywordResult(Context, "dynamic_cast");
2852 Consumer.addKeywordResult(Context, "reinterpret_cast");
2853 Consumer.addKeywordResult(Context, "static_cast");
2854 }
2855
2856 if (WantExpressionKeywords) {
2857 Consumer.addKeywordResult(Context, "sizeof");
2858 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2859 Consumer.addKeywordResult(Context, "false");
2860 Consumer.addKeywordResult(Context, "true");
2861 }
2862
2863 if (getLangOptions().CPlusPlus) {
2864 const char *CXXExprs[] = {
2865 "delete", "new", "operator", "throw", "typeid"
2866 };
2867 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2868 for (unsigned I = 0; I != NumCXXExprs; ++I)
2869 Consumer.addKeywordResult(Context, CXXExprs[I]);
2870
2871 if (isa<CXXMethodDecl>(CurContext) &&
2872 cast<CXXMethodDecl>(CurContext)->isInstance())
2873 Consumer.addKeywordResult(Context, "this");
2874
2875 if (getLangOptions().CPlusPlus0x) {
2876 Consumer.addKeywordResult(Context, "alignof");
2877 Consumer.addKeywordResult(Context, "nullptr");
2878 }
2879 }
2880 }
2881
2882 if (WantRemainingKeywords) {
2883 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2884 // Statements.
2885 const char *CStmts[] = {
2886 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2887 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2888 for (unsigned I = 0; I != NumCStmts; ++I)
2889 Consumer.addKeywordResult(Context, CStmts[I]);
2890
2891 if (getLangOptions().CPlusPlus) {
2892 Consumer.addKeywordResult(Context, "catch");
2893 Consumer.addKeywordResult(Context, "try");
2894 }
2895
2896 if (S && S->getBreakParent())
2897 Consumer.addKeywordResult(Context, "break");
2898
2899 if (S && S->getContinueParent())
2900 Consumer.addKeywordResult(Context, "continue");
2901
2902 if (!getSwitchStack().empty()) {
2903 Consumer.addKeywordResult(Context, "case");
2904 Consumer.addKeywordResult(Context, "default");
2905 }
2906 } else {
2907 if (getLangOptions().CPlusPlus) {
2908 Consumer.addKeywordResult(Context, "namespace");
2909 Consumer.addKeywordResult(Context, "template");
2910 }
2911
2912 if (S && S->isClassScope()) {
2913 Consumer.addKeywordResult(Context, "explicit");
2914 Consumer.addKeywordResult(Context, "friend");
2915 Consumer.addKeywordResult(Context, "mutable");
2916 Consumer.addKeywordResult(Context, "private");
2917 Consumer.addKeywordResult(Context, "protected");
2918 Consumer.addKeywordResult(Context, "public");
2919 Consumer.addKeywordResult(Context, "virtual");
2920 }
2921 }
2922
2923 if (getLangOptions().CPlusPlus) {
2924 Consumer.addKeywordResult(Context, "using");
2925
2926 if (getLangOptions().CPlusPlus0x)
2927 Consumer.addKeywordResult(Context, "static_assert");
2928 }
2929 }
2930
2931 // If we haven't found anything, we're done.
Douglas Gregor2d435302009-12-30 17:04:44 +00002932 if (Consumer.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002933 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002934
2935 // Only allow a single, closest name in the result set (it's okay to
2936 // have overloads of that name, though).
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002937 DeclarationName BestName;
2938 NamedDecl *BestIvarOrPropertyDecl = 0;
2939 bool FoundIvarOrPropertyDecl = false;
2940
2941 // Check all of the declaration results to find the best name so far.
2942 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2943 IEnd = Consumer.end();
2944 I != IEnd; ++I) {
2945 if (!BestName)
2946 BestName = (*I)->getDeclName();
2947 else if (BestName != (*I)->getDeclName())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002948 return DeclarationName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002949
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002950 // \brief Keep track of either an Objective-C ivar or a property, but not
2951 // both.
2952 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
2953 if (FoundIvarOrPropertyDecl)
2954 BestIvarOrPropertyDecl = 0;
2955 else {
2956 BestIvarOrPropertyDecl = *I;
2957 FoundIvarOrPropertyDecl = true;
2958 }
2959 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002960 }
2961
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002962 // Now check all of the keyword results to find the best name.
2963 switch (Consumer.keyword_size()) {
2964 case 0:
2965 // No keywords matched.
2966 break;
2967
2968 case 1:
2969 // If we already have a name
2970 if (!BestName) {
2971 // We did not have anything previously,
2972 BestName = *Consumer.keyword_begin();
2973 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
2974 // We have a declaration with the same name as a context-sensitive
2975 // keyword. The keyword takes precedence.
2976 BestIvarOrPropertyDecl = 0;
2977 FoundIvarOrPropertyDecl = false;
2978 Consumer.clear_decls();
Douglas Gregor86ad0852010-05-18 16:30:22 +00002979 } else if (CTC == CTC_ObjCMessageReceiver &&
2980 (*Consumer.keyword_begin())->isStr("super")) {
2981 // In an Objective-C message send, give the "super" keyword a slight
2982 // edge over entities not in function or method scope.
2983 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2984 IEnd = Consumer.end();
2985 I != IEnd; ++I) {
2986 if ((*I)->getDeclName() == BestName) {
2987 if ((*I)->getDeclContext()->isFunctionOrMethod())
2988 return DeclarationName();
2989 }
2990 }
2991
2992 // Everything found was outside a function or method; the 'super'
2993 // keyword takes precedence.
2994 BestIvarOrPropertyDecl = 0;
2995 FoundIvarOrPropertyDecl = false;
2996 Consumer.clear_decls();
2997 BestName = *Consumer.keyword_begin();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002998 } else {
2999 // Name collision; we will not correct typos.
3000 return DeclarationName();
3001 }
3002 break;
3003
3004 default:
3005 // Name collision; we will not correct typos.
3006 return DeclarationName();
3007 }
3008
Douglas Gregor2d435302009-12-30 17:04:44 +00003009 // BestName is the closest viable name to what the user
3010 // typed. However, to make sure that we don't pick something that's
3011 // way off, make sure that the user typed at least 3 characters for
3012 // each correction.
3013 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003014 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
3015 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003016 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003017
3018 // Perform name lookup again with the name we chose, and declare
3019 // success if we found something that was not ambiguous.
3020 Res.clear();
3021 Res.setLookupName(BestName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003022
3023 // If we found an ivar or property, add that result; no further
3024 // lookup is required.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003025 if (BestIvarOrPropertyDecl)
3026 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003027 // If we're looking into the context of a member, perform qualified
3028 // name lookup on the best name.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003029 else if (!Consumer.keyword_empty()) {
3030 // The best match was a keyword. Return it.
3031 return BestName;
3032 } else if (MemberContext)
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003033 LookupQualifiedName(Res, MemberContext);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003034 // Perform lookup as if we had just parsed the best name.
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003035 else
3036 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3037 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00003038
3039 if (Res.isAmbiguous()) {
3040 Res.suppressDiagnostics();
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003041 return DeclarationName();
Douglas Gregor598b08f2009-12-31 05:20:13 +00003042 }
3043
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003044 if (Res.getResultKind() != LookupResult::NotFound)
3045 return BestName;
3046
3047 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003048}