blob: 774a82b7c74188631316921b6909023be0153187 [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
John McCall9f3059a2009-10-09 21:13:30 +0000450// Adds all qualifying matches for a name within a decl context to the
451// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000452static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000453 bool Found = false;
454
John McCallf6c8a4e2009-11-10 07:01:13 +0000455 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000456 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000457 NamedDecl *D = *I;
458 if (R.isAcceptableDecl(D)) {
459 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000460 Found = true;
461 }
462 }
John McCall9f3059a2009-10-09 21:13:30 +0000463
Douglas Gregord3a59182010-02-12 05:48:04 +0000464 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
465 return true;
466
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000467 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000468 != DeclarationName::CXXConversionFunctionName ||
469 R.getLookupName().getCXXNameType()->isDependentType() ||
470 !isa<CXXRecordDecl>(DC))
471 return Found;
472
473 // C++ [temp.mem]p6:
474 // A specialization of a conversion function template is not found by
475 // name lookup. Instead, any conversion function templates visible in the
476 // context of the use are considered. [...]
477 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
478 if (!Record->isDefinition())
479 return Found;
480
481 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
482 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
483 UEnd = Unresolved->end(); U != UEnd; ++U) {
484 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
485 if (!ConvTemplate)
486 continue;
487
488 // When we're performing lookup for the purposes of redeclaration, just
489 // add the conversion function template. When we deduce template
490 // arguments for specializations, we'll end up unifying the return
491 // type of the new declaration with the type of the function template.
492 if (R.isForRedeclaration()) {
493 R.addDecl(ConvTemplate);
494 Found = true;
495 continue;
496 }
497
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000498 // C++ [temp.mem]p6:
Chandler Carruth3a693b72010-01-31 11:44:02 +0000499 // [...] For each such operator, if argument deduction succeeds
500 // (14.9.2.3), the resulting specialization is used as if found by
501 // name lookup.
502 //
503 // When referencing a conversion function for any purpose other than
504 // a redeclaration (such that we'll be building an expression with the
505 // result), perform template argument deduction and place the
506 // specialization into the result set. We do this to avoid forcing all
507 // callers to perform special deduction for conversion functions.
John McCallbc077cf2010-02-08 23:07:23 +0000508 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000509 FunctionDecl *Specialization = 0;
510
511 const FunctionProtoType *ConvProto
512 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
513 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000514
Chandler Carruth3a693b72010-01-31 11:44:02 +0000515 // Compute the type of the function that we would expect the conversion
516 // function to have, if it were to match the name given.
517 // FIXME: Calling convention!
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000518 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruth3a693b72010-01-31 11:44:02 +0000519 QualType ExpectedType
520 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
521 0, 0, ConvProto->isVariadic(),
522 ConvProto->getTypeQuals(),
523 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000524 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruth3a693b72010-01-31 11:44:02 +0000525
526 // Perform template argument deduction against the type that we would
527 // expect the function to have.
528 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
529 Specialization, Info)
530 == Sema::TDK_Success) {
531 R.addDecl(Specialization);
532 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000533 }
534 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000535
John McCall9f3059a2009-10-09 21:13:30 +0000536 return Found;
537}
538
John McCallf6c8a4e2009-11-10 07:01:13 +0000539// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000540static bool
Douglas Gregord3a59182010-02-12 05:48:04 +0000541CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
542 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000543
544 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
545
John McCallf6c8a4e2009-11-10 07:01:13 +0000546 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000547 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000548
John McCallf6c8a4e2009-11-10 07:01:13 +0000549 // Perform direct name lookup into the namespaces nominated by the
550 // using directives whose common ancestor is this namespace.
551 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
552 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000553
John McCallf6c8a4e2009-11-10 07:01:13 +0000554 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000555 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000556 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000557
558 R.resolveKind();
559
560 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000561}
562
563static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000564 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000565 return Ctx->isFileContext();
566 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000567}
Douglas Gregored8f2882009-01-30 01:04:22 +0000568
Douglas Gregor66230062010-03-15 14:33:29 +0000569// Find the next outer declaration context from this scope. This
570// routine actually returns the semantic outer context, which may
571// differ from the lexical context (encoded directly in the Scope
572// stack) when we are parsing a member of a class template. In this
573// case, the second element of the pair will be true, to indicate that
574// name lookup should continue searching in this semantic context when
575// it leaves the current template parameter scope.
576static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
577 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
578 DeclContext *Lexical = 0;
579 for (Scope *OuterS = S->getParent(); OuterS;
580 OuterS = OuterS->getParent()) {
581 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000582 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000583 break;
584 }
585 }
586
587 // C++ [temp.local]p8:
588 // In the definition of a member of a class template that appears
589 // outside of the namespace containing the class template
590 // definition, the name of a template-parameter hides the name of
591 // a member of this namespace.
592 //
593 // Example:
594 //
595 // namespace N {
596 // class C { };
597 //
598 // template<class T> class B {
599 // void f(T);
600 // };
601 // }
602 //
603 // template<class C> void N::B<C>::f(C) {
604 // C b; // C is the template parameter, not N::C
605 // }
606 //
607 // In this example, the lexical context we return is the
608 // TranslationUnit, while the semantic context is the namespace N.
609 if (!Lexical || !DC || !S->getParent() ||
610 !S->getParent()->isTemplateParamScope())
611 return std::make_pair(Lexical, false);
612
613 // Find the outermost template parameter scope.
614 // For the example, this is the scope for the template parameters of
615 // template<class C>.
616 Scope *OutermostTemplateScope = S->getParent();
617 while (OutermostTemplateScope->getParent() &&
618 OutermostTemplateScope->getParent()->isTemplateParamScope())
619 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregor7f737c02009-09-10 16:57:35 +0000620
Douglas Gregor66230062010-03-15 14:33:29 +0000621 // Find the namespace context in which the original scope occurs. In
622 // the example, this is namespace N.
623 DeclContext *Semantic = DC;
624 while (!Semantic->isFileContext())
625 Semantic = Semantic->getParent();
626
627 // Find the declaration context just outside of the template
628 // parameter scope. This is the context in which the template is
629 // being lexically declaration (a namespace context). In the
630 // example, this is the global scope.
631 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
632 Lexical->Encloses(Semantic))
633 return std::make_pair(Semantic, true);
634
635 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000636}
637
John McCall27b18f82009-11-17 02:14:36 +0000638bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000639 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000640
641 DeclarationName Name = R.getLookupName();
642
Douglas Gregor889ceb72009-02-03 19:21:40 +0000643 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000644 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000645 I = IdResolver.begin(Name),
646 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000647
Douglas Gregor889ceb72009-02-03 19:21:40 +0000648 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000649 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000650 // ...During unqualified name lookup (3.4.1), the names appear as if
651 // they were declared in the nearest enclosing namespace which contains
652 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000653 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000654 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000655 //
656 // For example:
657 // namespace A { int i; }
658 // void foo() {
659 // int i;
660 // {
661 // using namespace A;
662 // ++i; // finds local 'i', A::i appears at global scope
663 // }
664 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000665 //
Douglas Gregor66230062010-03-15 14:33:29 +0000666 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000667 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000668 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000669 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000670 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000671 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000672 Found = true;
673 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000674 }
675 }
John McCall9f3059a2009-10-09 21:13:30 +0000676 if (Found) {
677 R.resolveKind();
678 return true;
679 }
680
Daniel Dunbarfd5ed842010-05-19 21:07:14 +0000681 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000682 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
683 S->getParent() && !S->getParent()->isTemplateParamScope()) {
684 // We've just searched the last template parameter scope and
685 // found nothing, so look into the the contexts between the
686 // lexical and semantic declaration contexts returned by
687 // findOuterContext(). This implements the name lookup behavior
688 // of C++ [temp.local]p8.
689 Ctx = OutsideOfTemplateParamDC;
690 OutsideOfTemplateParamDC = 0;
691 }
692
693 if (Ctx) {
694 DeclContext *OuterCtx;
695 bool SearchAfterTemplateScope;
696 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
697 if (SearchAfterTemplateScope)
698 OutsideOfTemplateParamDC = OuterCtx;
699
Douglas Gregorea166062010-03-15 15:26:48 +0000700 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000701 // We do not directly look into transparent contexts, since
702 // those entities will be found in the nearest enclosing
703 // non-transparent context.
704 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000705 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000706
707 // We do not look directly into function or method contexts,
708 // since all of the local variables and parameters of the
709 // function/method are present within the Scope.
710 if (Ctx->isFunctionOrMethod()) {
711 // If we have an Objective-C instance method, look for ivars
712 // in the corresponding interface.
713 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
714 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
715 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
716 ObjCInterfaceDecl *ClassDeclared;
717 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
718 Name.getAsIdentifierInfo(),
719 ClassDeclared)) {
720 if (R.isAcceptableDecl(Ivar)) {
721 R.addDecl(Ivar);
722 R.resolveKind();
723 return true;
724 }
725 }
726 }
727 }
728
729 continue;
730 }
731
Douglas Gregor7f737c02009-09-10 16:57:35 +0000732 // Perform qualified name lookup into this context.
733 // FIXME: In some cases, we know that every name that could be found by
734 // this qualified name lookup will also be on the identifier chain. For
735 // example, inside a class without any base classes, we never need to
736 // perform qualified lookup because all of the members are on top of the
737 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000738 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000739 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000740 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000741 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000742 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000743
John McCallf6c8a4e2009-11-10 07:01:13 +0000744 // Stop if we ran out of scopes.
745 // FIXME: This really, really shouldn't be happening.
746 if (!S) return false;
747
Douglas Gregor700792c2009-02-05 19:25:20 +0000748 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000749 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000750 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000751 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
752 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000753
John McCallf6c8a4e2009-11-10 07:01:13 +0000754 UnqualUsingDirectiveSet UDirs;
755 UDirs.visitScopeChain(Initial, S);
756 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000757
Douglas Gregor700792c2009-02-05 19:25:20 +0000758 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000759 // Unqualified name lookup in C++ requires looking into scopes
760 // that aren't strictly lexical, and therefore we walk through the
761 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000762
Douglas Gregor889ceb72009-02-03 19:21:40 +0000763 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000764 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000765 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000766 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000767 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000768 // We found something. Look for anything else in our scope
769 // with this same name and in an acceptable identifier
770 // namespace, so that we can construct an overload set if we
771 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000772 Found = true;
773 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000774 }
775 }
776
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000777 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000778 R.resolveKind();
779 return true;
780 }
781
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000782 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
783 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
784 S->getParent() && !S->getParent()->isTemplateParamScope()) {
785 // We've just searched the last template parameter scope and
786 // found nothing, so look into the the contexts between the
787 // lexical and semantic declaration contexts returned by
788 // findOuterContext(). This implements the name lookup behavior
789 // of C++ [temp.local]p8.
790 Ctx = OutsideOfTemplateParamDC;
791 OutsideOfTemplateParamDC = 0;
792 }
793
794 if (Ctx) {
795 DeclContext *OuterCtx;
796 bool SearchAfterTemplateScope;
797 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
798 if (SearchAfterTemplateScope)
799 OutsideOfTemplateParamDC = OuterCtx;
800
801 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
802 // We do not directly look into transparent contexts, since
803 // those entities will be found in the nearest enclosing
804 // non-transparent context.
805 if (Ctx->isTransparentContext())
806 continue;
807
808 // If we have a context, and it's not a context stashed in the
809 // template parameter scope for an out-of-line definition, also
810 // look into that context.
811 if (!(Found && S && S->isTemplateParamScope())) {
812 assert(Ctx->isFileContext() &&
813 "We should have been looking only at file context here already.");
814
815 // Look into context considering using-directives.
816 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
817 Found = true;
818 }
819
820 if (Found) {
821 R.resolveKind();
822 return true;
823 }
824
825 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
826 return false;
827 }
828 }
829
Douglas Gregor3ce74932010-02-05 07:07:10 +0000830 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000831 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000832 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000833
John McCall9f3059a2009-10-09 21:13:30 +0000834 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000835}
836
Douglas Gregor34074322009-01-14 22:20:51 +0000837/// @brief Perform unqualified name lookup starting from a given
838/// scope.
839///
840/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
841/// used to find names within the current scope. For example, 'x' in
842/// @code
843/// int x;
844/// int f() {
845/// return x; // unqualified name look finds 'x' in the global scope
846/// }
847/// @endcode
848///
849/// Different lookup criteria can find different names. For example, a
850/// particular scope can have both a struct and a function of the same
851/// name, and each can be found by certain lookup criteria. For more
852/// information about lookup criteria, see the documentation for the
853/// class LookupCriteria.
854///
855/// @param S The scope from which unqualified name lookup will
856/// begin. If the lookup criteria permits, name lookup may also search
857/// in the parent scopes.
858///
859/// @param Name The name of the entity that we are searching for.
860///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000861/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000862/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000863/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000864///
865/// @returns The result of name lookup, which includes zero or more
866/// declarations and possibly additional information used to diagnose
867/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000868bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
869 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +0000870 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000871
John McCall27b18f82009-11-17 02:14:36 +0000872 LookupNameKind NameKind = R.getLookupKind();
873
Douglas Gregor34074322009-01-14 22:20:51 +0000874 if (!getLangOptions().CPlusPlus) {
875 // Unqualified name lookup in C/Objective-C is purely lexical, so
876 // search in the declarations attached to the name.
877
John McCallea305ed2009-12-18 10:40:03 +0000878 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000879 // Find the nearest non-transparent declaration scope.
880 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000881 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000882 static_cast<DeclContext *>(S->getEntity())
883 ->isTransparentContext()))
884 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +0000885 }
886
John McCallea305ed2009-12-18 10:40:03 +0000887 unsigned IDNS = R.getIdentifierNamespace();
888
Douglas Gregor34074322009-01-14 22:20:51 +0000889 // Scan up the scope chain looking for a decl that matches this
890 // identifier that is in the appropriate namespace. This search
891 // should not take long, as shadowing of names is uncommon, and
892 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000893 bool LeftStartingScope = false;
894
Douglas Gregored8f2882009-01-30 01:04:22 +0000895 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000896 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000897 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000898 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000899 if (NameKind == LookupRedeclarationWithLinkage) {
900 // Determine whether this (or a previous) declaration is
901 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000902 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000903 LeftStartingScope = true;
904
905 // If we found something outside of our starting scope that
906 // does not have linkage, skip it.
907 if (LeftStartingScope && !((*I)->hasLinkage()))
908 continue;
909 }
910
John McCall9f3059a2009-10-09 21:13:30 +0000911 R.addDecl(*I);
912
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000913 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000914 // If this declaration has the "overloadable" attribute, we
915 // might have a set of overloaded functions.
916
917 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000918 while (!(S->getFlags() & Scope::DeclScope) ||
919 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000920 S = S->getParent();
921
922 // Find the last declaration in this scope (with the same
923 // name, naturally).
924 IdentifierResolver::iterator LastI = I;
925 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000926 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000927 break;
John McCall9f3059a2009-10-09 21:13:30 +0000928 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000929 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000930 }
931
John McCall9f3059a2009-10-09 21:13:30 +0000932 R.resolveKind();
933
934 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000935 }
Douglas Gregor34074322009-01-14 22:20:51 +0000936 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000937 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000938 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +0000939 return true;
Douglas Gregor34074322009-01-14 22:20:51 +0000940 }
941
942 // If we didn't find a use of this identifier, and if the identifier
943 // corresponds to a compiler builtin, create the decl object for the builtin
944 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +0000945 if (AllowBuiltinCreation)
946 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000947
John McCall9f3059a2009-10-09 21:13:30 +0000948 return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000949}
950
John McCall6538c932009-10-10 05:48:19 +0000951/// @brief Perform qualified name lookup in the namespaces nominated by
952/// using directives by the given context.
953///
954/// C++98 [namespace.qual]p2:
955/// Given X::m (where X is a user-declared namespace), or given ::m
956/// (where X is the global namespace), let S be the set of all
957/// declarations of m in X and in the transitive closure of all
958/// namespaces nominated by using-directives in X and its used
959/// namespaces, except that using-directives are ignored in any
960/// namespace, including X, directly containing one or more
961/// declarations of m. No namespace is searched more than once in
962/// the lookup of a name. If S is the empty set, the program is
963/// ill-formed. Otherwise, if S has exactly one member, or if the
964/// context of the reference is a using-declaration
965/// (namespace.udecl), S is the required set of declarations of
966/// m. Otherwise if the use of m is not one that allows a unique
967/// declaration to be chosen from S, the program is ill-formed.
968/// C++98 [namespace.qual]p5:
969/// During the lookup of a qualified namespace member name, if the
970/// lookup finds more than one declaration of the member, and if one
971/// declaration introduces a class name or enumeration name and the
972/// other declarations either introduce the same object, the same
973/// enumerator or a set of functions, the non-type name hides the
974/// class or enumeration name if and only if the declarations are
975/// from the same namespace; otherwise (the declarations are from
976/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +0000977static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +0000978 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +0000979 assert(StartDC->isFileContext() && "start context is not a file context");
980
981 DeclContext::udir_iterator I = StartDC->using_directives_begin();
982 DeclContext::udir_iterator E = StartDC->using_directives_end();
983
984 if (I == E) return false;
985
986 // We have at least added all these contexts to the queue.
987 llvm::DenseSet<DeclContext*> Visited;
988 Visited.insert(StartDC);
989
990 // We have not yet looked into these namespaces, much less added
991 // their "using-children" to the queue.
992 llvm::SmallVector<NamespaceDecl*, 8> Queue;
993
994 // We have already looked into the initial namespace; seed the queue
995 // with its using-children.
996 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +0000997 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +0000998 if (Visited.insert(ND).second)
999 Queue.push_back(ND);
1000 }
1001
1002 // The easiest way to implement the restriction in [namespace.qual]p5
1003 // is to check whether any of the individual results found a tag
1004 // and, if so, to declare an ambiguity if the final result is not
1005 // a tag.
1006 bool FoundTag = false;
1007 bool FoundNonTag = false;
1008
John McCall5cebab12009-11-18 07:57:50 +00001009 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001010
1011 bool Found = false;
1012 while (!Queue.empty()) {
1013 NamespaceDecl *ND = Queue.back();
1014 Queue.pop_back();
1015
1016 // We go through some convolutions here to avoid copying results
1017 // between LookupResults.
1018 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001019 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001020 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001021
1022 if (FoundDirect) {
1023 // First do any local hiding.
1024 DirectR.resolveKind();
1025
1026 // If the local result is a tag, remember that.
1027 if (DirectR.isSingleTagDecl())
1028 FoundTag = true;
1029 else
1030 FoundNonTag = true;
1031
1032 // Append the local results to the total results if necessary.
1033 if (UseLocal) {
1034 R.addAllDecls(LocalR);
1035 LocalR.clear();
1036 }
1037 }
1038
1039 // If we find names in this namespace, ignore its using directives.
1040 if (FoundDirect) {
1041 Found = true;
1042 continue;
1043 }
1044
1045 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1046 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1047 if (Visited.insert(Nom).second)
1048 Queue.push_back(Nom);
1049 }
1050 }
1051
1052 if (Found) {
1053 if (FoundTag && FoundNonTag)
1054 R.setAmbiguousQualifiedTagHiding();
1055 else
1056 R.resolveKind();
1057 }
1058
1059 return Found;
1060}
1061
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001062/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001063///
1064/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1065/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001066/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001067///
1068/// Different lookup criteria can find different names. For example, a
1069/// particular scope can have both a struct and a function of the same
1070/// name, and each can be found by certain lookup criteria. For more
1071/// information about lookup criteria, see the documentation for the
1072/// class LookupCriteria.
1073///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001074/// \param R captures both the lookup criteria and any lookup results found.
1075///
1076/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001077/// search. If the lookup criteria permits, name lookup may also search
1078/// in the parent contexts or (for C++ classes) base classes.
1079///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001080/// \param InUnqualifiedLookup true if this is qualified name lookup that
1081/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001082///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001083/// \returns true if lookup succeeded, false if it failed.
1084bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1085 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001086 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001087
John McCall27b18f82009-11-17 02:14:36 +00001088 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001089 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001090
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001091 // Make sure that the declaration context is complete.
1092 assert((!isa<TagDecl>(LookupCtx) ||
1093 LookupCtx->isDependentContext() ||
1094 cast<TagDecl>(LookupCtx)->isDefinition() ||
1095 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1096 ->isBeingDefined()) &&
1097 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001098
Douglas Gregor34074322009-01-14 22:20:51 +00001099 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001100 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001101 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001102 if (isa<CXXRecordDecl>(LookupCtx))
1103 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001104 return true;
1105 }
Douglas Gregor34074322009-01-14 22:20:51 +00001106
John McCall6538c932009-10-10 05:48:19 +00001107 // Don't descend into implied contexts for redeclarations.
1108 // C++98 [namespace.qual]p6:
1109 // In a declaration for a namespace member in which the
1110 // declarator-id is a qualified-id, given that the qualified-id
1111 // for the namespace member has the form
1112 // nested-name-specifier unqualified-id
1113 // the unqualified-id shall name a member of the namespace
1114 // designated by the nested-name-specifier.
1115 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001116 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001117 return false;
1118
John McCall27b18f82009-11-17 02:14:36 +00001119 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001120 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001121 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001122
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001123 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001124 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001125 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1126 if (!LookupRec)
John McCall9f3059a2009-10-09 21:13:30 +00001127 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001128
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001129 // If we're performing qualified name lookup into a dependent class,
1130 // then we are actually looking into a current instantiation. If we have any
1131 // dependent base classes, then we either have to delay lookup until
1132 // template instantiation time (at which point all bases will be available)
1133 // or we have to fail.
1134 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1135 LookupRec->hasAnyDependentBases()) {
1136 R.setNotFoundInCurrentInstantiation();
1137 return false;
1138 }
1139
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001140 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001141 CXXBasePaths Paths;
1142 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001143
1144 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001145 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001146 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001147 case LookupOrdinaryName:
1148 case LookupMemberName:
1149 case LookupRedeclarationWithLinkage:
1150 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1151 break;
1152
1153 case LookupTagName:
1154 BaseCallback = &CXXRecordDecl::FindTagMember;
1155 break;
John McCall84d87672009-12-10 09:41:52 +00001156
1157 case LookupUsingDeclName:
1158 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001159
1160 case LookupOperatorName:
1161 case LookupNamespaceName:
1162 case LookupObjCProtocolName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001163 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001164 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001165
1166 case LookupNestedNameSpecifierName:
1167 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1168 break;
1169 }
1170
John McCall27b18f82009-11-17 02:14:36 +00001171 if (!LookupRec->lookupInBases(BaseCallback,
1172 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001173 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001174
John McCall553c0792010-01-23 00:46:32 +00001175 R.setNamingClass(LookupRec);
1176
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001177 // C++ [class.member.lookup]p2:
1178 // [...] If the resulting set of declarations are not all from
1179 // sub-objects of the same type, or the set has a nonstatic member
1180 // and includes members from distinct sub-objects, there is an
1181 // ambiguity and the program is ill-formed. Otherwise that set is
1182 // the result of the lookup.
1183 // FIXME: support using declarations!
1184 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001185 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001186 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001187 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001188 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001189 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001190
John McCall401982f2010-01-20 21:53:11 +00001191 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1192 // across all paths.
1193 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1194
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001195 // Determine whether we're looking at a distinct sub-object or not.
1196 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001197 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001198 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1199 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001200 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001201 != Context.getCanonicalType(PathElement.Base->getType())) {
1202 // We found members of the given name in two subobjects of
1203 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001204 R.setAmbiguousBaseSubobjectTypes(Paths);
1205 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001206 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1207 // We have a different subobject of the same type.
1208
1209 // C++ [class.member.lookup]p5:
1210 // A static member, a nested type or an enumerator defined in
1211 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001212 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001213 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001214 if (isa<VarDecl>(FirstDecl) ||
1215 isa<TypeDecl>(FirstDecl) ||
1216 isa<EnumConstantDecl>(FirstDecl))
1217 continue;
1218
1219 if (isa<CXXMethodDecl>(FirstDecl)) {
1220 // Determine whether all of the methods are static.
1221 bool AllMethodsAreStatic = true;
1222 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1223 Func != Path->Decls.second; ++Func) {
1224 if (!isa<CXXMethodDecl>(*Func)) {
1225 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1226 break;
1227 }
1228
1229 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1230 AllMethodsAreStatic = false;
1231 break;
1232 }
1233 }
1234
1235 if (AllMethodsAreStatic)
1236 continue;
1237 }
1238
1239 // We have found a nonstatic member name in multiple, distinct
1240 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001241 R.setAmbiguousBaseSubobjects(Paths);
1242 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001243 }
1244 }
1245
1246 // Lookup in a base class succeeded; return these results.
1247
John McCall9f3059a2009-10-09 21:13:30 +00001248 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001249 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1250 NamedDecl *D = *I;
1251 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1252 D->getAccess());
1253 R.addDecl(D, AS);
1254 }
John McCall9f3059a2009-10-09 21:13:30 +00001255 R.resolveKind();
1256 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001257}
1258
1259/// @brief Performs name lookup for a name that was parsed in the
1260/// source code, and may contain a C++ scope specifier.
1261///
1262/// This routine is a convenience routine meant to be called from
1263/// contexts that receive a name and an optional C++ scope specifier
1264/// (e.g., "N::M::x"). It will then perform either qualified or
1265/// unqualified name lookup (with LookupQualifiedName or LookupName,
1266/// respectively) on the given name and return those results.
1267///
1268/// @param S The scope from which unqualified name lookup will
1269/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001270///
Douglas Gregore861bac2009-08-25 22:51:20 +00001271/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001272///
1273/// @param Name The name of the entity that name lookup will
1274/// search for.
1275///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001276/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001277/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001278/// C library functions (like "malloc") are implicitly declared.
1279///
Douglas Gregore861bac2009-08-25 22:51:20 +00001280/// @param EnteringContext Indicates whether we are going to enter the
1281/// context of the scope-specifier SS (if present).
1282///
John McCall9f3059a2009-10-09 21:13:30 +00001283/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001284bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001285 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001286 if (SS && SS->isInvalid()) {
1287 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001288 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001289 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001290 }
Mike Stump11289f42009-09-09 15:08:12 +00001291
Douglas Gregore861bac2009-08-25 22:51:20 +00001292 if (SS && SS->isSet()) {
1293 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001294 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001295 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001296 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001297 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001298
John McCall27b18f82009-11-17 02:14:36 +00001299 R.setContextRange(SS->getRange());
1300
1301 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001302 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001303
Douglas Gregore861bac2009-08-25 22:51:20 +00001304 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001305 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001306 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001307 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001308 }
1309
Mike Stump11289f42009-09-09 15:08:12 +00001310 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001311 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001312}
1313
Douglas Gregor889ceb72009-02-03 19:21:40 +00001314
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001315/// @brief Produce a diagnostic describing the ambiguity that resulted
1316/// from name lookup.
1317///
1318/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001319///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001320/// @param Name The name of the entity that name lookup was
1321/// searching for.
1322///
1323/// @param NameLoc The location of the name within the source code.
1324///
1325/// @param LookupRange A source range that provides more
1326/// source-location information concerning the lookup itself. For
1327/// example, this range might highlight a nested-name-specifier that
1328/// precedes the name.
1329///
1330/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001331bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001332 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1333
John McCall27b18f82009-11-17 02:14:36 +00001334 DeclarationName Name = Result.getLookupName();
1335 SourceLocation NameLoc = Result.getNameLoc();
1336 SourceRange LookupRange = Result.getContextRange();
1337
John McCall6538c932009-10-10 05:48:19 +00001338 switch (Result.getAmbiguityKind()) {
1339 case LookupResult::AmbiguousBaseSubobjects: {
1340 CXXBasePaths *Paths = Result.getBasePaths();
1341 QualType SubobjectType = Paths->front().back().Base->getType();
1342 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1343 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1344 << LookupRange;
1345
1346 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1347 while (isa<CXXMethodDecl>(*Found) &&
1348 cast<CXXMethodDecl>(*Found)->isStatic())
1349 ++Found;
1350
1351 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1352
1353 return true;
1354 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001355
John McCall6538c932009-10-10 05:48:19 +00001356 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001357 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1358 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001359
1360 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001361 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001362 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1363 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001364 Path != PathEnd; ++Path) {
1365 Decl *D = *Path->Decls.first;
1366 if (DeclsPrinted.insert(D).second)
1367 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1368 }
1369
Douglas Gregor1c846b02009-01-16 00:38:09 +00001370 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001371 }
1372
John McCall6538c932009-10-10 05:48:19 +00001373 case LookupResult::AmbiguousTagHiding: {
1374 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001375
John McCall6538c932009-10-10 05:48:19 +00001376 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1377
1378 LookupResult::iterator DI, DE = Result.end();
1379 for (DI = Result.begin(); DI != DE; ++DI)
1380 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1381 TagDecls.insert(TD);
1382 Diag(TD->getLocation(), diag::note_hidden_tag);
1383 }
1384
1385 for (DI = Result.begin(); DI != DE; ++DI)
1386 if (!isa<TagDecl>(*DI))
1387 Diag((*DI)->getLocation(), diag::note_hiding_object);
1388
1389 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001390 LookupResult::Filter F = Result.makeFilter();
1391 while (F.hasNext()) {
1392 if (TagDecls.count(F.next()))
1393 F.erase();
1394 }
1395 F.done();
John McCall6538c932009-10-10 05:48:19 +00001396
1397 return true;
1398 }
1399
1400 case LookupResult::AmbiguousReference: {
1401 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001402
John McCall6538c932009-10-10 05:48:19 +00001403 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1404 for (; DI != DE; ++DI)
1405 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001406
John McCall6538c932009-10-10 05:48:19 +00001407 return true;
1408 }
1409 }
1410
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001411 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001412 return true;
1413}
Douglas Gregore254f902009-02-04 00:32:51 +00001414
Mike Stump11289f42009-09-09 15:08:12 +00001415static void
1416addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001417 ASTContext &Context,
1418 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001419 Sema::AssociatedClassSet &AssociatedClasses);
1420
Douglas Gregor8b895222010-04-30 07:08:38 +00001421static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1422 DeclContext *Ctx) {
1423 // Add the associated namespace for this class.
1424
1425 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1426 // be a locally scoped record.
1427
1428 while (Ctx->isRecord() || Ctx->isTransparentContext())
1429 Ctx = Ctx->getParent();
1430
John McCallc7e8e792009-08-07 22:18:02 +00001431 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001432 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001433}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001434
Mike Stump11289f42009-09-09 15:08:12 +00001435// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001436// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001437static void
1438addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001439 ASTContext &Context,
1440 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001441 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001442 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001443 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001444 switch (Arg.getKind()) {
1445 case TemplateArgument::Null:
1446 break;
Mike Stump11289f42009-09-09 15:08:12 +00001447
Douglas Gregor197e5f72009-07-08 07:51:57 +00001448 case TemplateArgument::Type:
1449 // [...] the namespaces and classes associated with the types of the
1450 // template arguments provided for template type parameters (excluding
1451 // template template parameters)
1452 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1453 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001454 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001455 break;
Mike Stump11289f42009-09-09 15:08:12 +00001456
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001457 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001458 // [...] the namespaces in which any template template arguments are
1459 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001460 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001461 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001462 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001463 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001464 DeclContext *Ctx = ClassTemplate->getDeclContext();
1465 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1466 AssociatedClasses.insert(EnclosingClass);
1467 // Add the associated namespace for this class.
Douglas Gregor8b895222010-04-30 07:08:38 +00001468 CollectEnclosingNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001469 }
1470 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001471 }
1472
1473 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001474 case TemplateArgument::Integral:
1475 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001476 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001477 // associated namespaces. ]
1478 break;
Mike Stump11289f42009-09-09 15:08:12 +00001479
Douglas Gregor197e5f72009-07-08 07:51:57 +00001480 case TemplateArgument::Pack:
1481 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1482 PEnd = Arg.pack_end();
1483 P != PEnd; ++P)
1484 addAssociatedClassesAndNamespaces(*P, Context,
1485 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001486 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001487 break;
1488 }
1489}
1490
Douglas Gregore254f902009-02-04 00:32:51 +00001491// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001492// argument-dependent lookup with an argument of class type
1493// (C++ [basic.lookup.koenig]p2).
1494static void
1495addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregore254f902009-02-04 00:32:51 +00001496 ASTContext &Context,
1497 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001498 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001499 // C++ [basic.lookup.koenig]p2:
1500 // [...]
1501 // -- If T is a class type (including unions), its associated
1502 // classes are: the class itself; the class of which it is a
1503 // member, if any; and its direct and indirect base
1504 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001505 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001506
1507 // Add the class of which it is a member, if any.
1508 DeclContext *Ctx = Class->getDeclContext();
1509 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1510 AssociatedClasses.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001511 // Add the associated namespace for this class.
Douglas Gregor8b895222010-04-30 07:08:38 +00001512 CollectEnclosingNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001513
Douglas Gregore254f902009-02-04 00:32:51 +00001514 // Add the class itself. If we've already seen this class, we don't
1515 // need to visit base classes.
1516 if (!AssociatedClasses.insert(Class))
1517 return;
1518
Mike Stump11289f42009-09-09 15:08:12 +00001519 // -- If T is a template-id, its associated namespaces and classes are
1520 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001521 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001522 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001523 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001524 // namespaces in which any template template arguments are defined; and
1525 // the classes in which any member templates used as template template
1526 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001527 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001528 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001529 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1530 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1531 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1532 AssociatedClasses.insert(EnclosingClass);
1533 // Add the associated namespace for this class.
Douglas Gregor8b895222010-04-30 07:08:38 +00001534 CollectEnclosingNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001535
Douglas Gregor197e5f72009-07-08 07:51:57 +00001536 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1537 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1538 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1539 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001540 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001541 }
Mike Stump11289f42009-09-09 15:08:12 +00001542
John McCall67da35c2010-02-04 22:26:26 +00001543 // Only recurse into base classes for complete types.
1544 if (!Class->hasDefinition()) {
1545 // FIXME: we might need to instantiate templates here
1546 return;
1547 }
1548
Douglas Gregore254f902009-02-04 00:32:51 +00001549 // Add direct and indirect base classes along with their associated
1550 // namespaces.
1551 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1552 Bases.push_back(Class);
1553 while (!Bases.empty()) {
1554 // Pop this class off the stack.
1555 Class = Bases.back();
1556 Bases.pop_back();
1557
1558 // Visit the base classes.
1559 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1560 BaseEnd = Class->bases_end();
1561 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001562 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001563 // In dependent contexts, we do ADL twice, and the first time around,
1564 // the base type might be a dependent TemplateSpecializationType, or a
1565 // TemplateTypeParmType. If that happens, simply ignore it.
1566 // FIXME: If we want to support export, we probably need to add the
1567 // namespace of the template in a TemplateSpecializationType, or even
1568 // the classes and namespaces of known non-dependent arguments.
1569 if (!BaseType)
1570 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001571 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1572 if (AssociatedClasses.insert(BaseDecl)) {
1573 // Find the associated namespace for this base class.
1574 DeclContext *BaseCtx = BaseDecl->getDeclContext();
Douglas Gregor8b895222010-04-30 07:08:38 +00001575 CollectEnclosingNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001576
1577 // Make sure we visit the bases of this base class.
1578 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1579 Bases.push_back(BaseDecl);
1580 }
1581 }
1582 }
1583}
1584
1585// \brief Add the associated classes and namespaces for
1586// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001587// (C++ [basic.lookup.koenig]p2).
1588static void
1589addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregore254f902009-02-04 00:32:51 +00001590 ASTContext &Context,
1591 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001592 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001593 // C++ [basic.lookup.koenig]p2:
1594 //
1595 // For each argument type T in the function call, there is a set
1596 // of zero or more associated namespaces and a set of zero or more
1597 // associated classes to be considered. The sets of namespaces and
1598 // classes is determined entirely by the types of the function
1599 // arguments (and the namespace of any template template
1600 // argument). Typedef names and using-declarations used to specify
1601 // the types do not contribute to this set. The sets of namespaces
1602 // and classes are determined in the following way:
1603 T = Context.getCanonicalType(T).getUnqualifiedType();
1604
1605 // -- If T is a pointer to U or an array of U, its associated
Mike Stump11289f42009-09-09 15:08:12 +00001606 // namespaces and classes are those associated with U.
Douglas Gregore254f902009-02-04 00:32:51 +00001607 //
1608 // We handle this by unwrapping pointer and array types immediately,
1609 // to avoid unnecessary recursion.
1610 while (true) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001611 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001612 T = Ptr->getPointeeType();
1613 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1614 T = Ptr->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001615 else
Douglas Gregore254f902009-02-04 00:32:51 +00001616 break;
1617 }
1618
1619 // -- If T is a fundamental type, its associated sets of
1620 // namespaces and classes are both empty.
John McCall9dd450b2009-09-21 23:43:11 +00001621 if (T->getAs<BuiltinType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001622 return;
1623
1624 // -- If T is a class type (including unions), its associated
1625 // classes are: the class itself; the class of which it is a
1626 // member, if any; and its direct and indirect base
1627 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001628 // which its associated classes are defined.
Douglas Gregorfe60c142010-05-20 02:26:51 +00001629 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump11289f42009-09-09 15:08:12 +00001630 if (CXXRecordDecl *ClassDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001631 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001632 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1633 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001634 AssociatedClasses);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001635 return;
1636 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001637
Douglas Gregore254f902009-02-04 00:32:51 +00001638 // -- If T is an enumeration type, its associated namespace is
1639 // the namespace in which it is defined. If it is class
1640 // member, its associated class is the member’s class; else
Mike Stump11289f42009-09-09 15:08:12 +00001641 // it has no associated class.
John McCall9dd450b2009-09-21 23:43:11 +00001642 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001643 EnumDecl *Enum = EnumT->getDecl();
1644
1645 DeclContext *Ctx = Enum->getDeclContext();
1646 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1647 AssociatedClasses.insert(EnclosingClass);
1648
1649 // Add the associated namespace for this class.
Douglas Gregor8b895222010-04-30 07:08:38 +00001650 CollectEnclosingNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001651
1652 return;
1653 }
1654
1655 // -- If T is a function type, its associated namespaces and
1656 // classes are those associated with the function parameter
1657 // types and those associated with the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001658 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001659 // Return type
John McCall9dd450b2009-09-21 23:43:11 +00001660 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregore254f902009-02-04 00:32:51 +00001661 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001662 AssociatedNamespaces, AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001663
John McCall9dd450b2009-09-21 23:43:11 +00001664 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregore254f902009-02-04 00:32:51 +00001665 if (!Proto)
1666 return;
1667
1668 // Argument types
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001669 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001670 ArgEnd = Proto->arg_type_end();
Douglas Gregore254f902009-02-04 00:32:51 +00001671 Arg != ArgEnd; ++Arg)
1672 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallc7e8e792009-08-07 22:18:02 +00001673 AssociatedNamespaces, AssociatedClasses);
Mike Stump11289f42009-09-09 15:08:12 +00001674
Douglas Gregore254f902009-02-04 00:32:51 +00001675 return;
1676 }
1677
1678 // -- If T is a pointer to a member function of a class X, its
1679 // associated namespaces and classes are those associated
1680 // with the function parameter types and return type,
Mike Stump11289f42009-09-09 15:08:12 +00001681 // together with those associated with X.
Douglas Gregore254f902009-02-04 00:32:51 +00001682 //
1683 // -- If T is a pointer to a data member of class X, its
1684 // associated namespaces and classes are those associated
1685 // with the member type together with those associated with
Mike Stump11289f42009-09-09 15:08:12 +00001686 // X.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001687 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001688 // Handle the type that the pointer to member points to.
1689 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1690 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001691 AssociatedNamespaces,
1692 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001693
1694 // Handle the class type into which this points.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001695 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001696 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1697 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001698 AssociatedNamespaces,
1699 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001700
1701 return;
1702 }
1703
1704 // FIXME: What about block pointers?
1705 // FIXME: What about Objective-C message sends?
1706}
1707
1708/// \brief Find the associated classes and namespaces for
1709/// argument-dependent lookup for a call with the given set of
1710/// arguments.
1711///
1712/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001713/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001714/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001715void
Douglas Gregore254f902009-02-04 00:32:51 +00001716Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1717 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001718 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001719 AssociatedNamespaces.clear();
1720 AssociatedClasses.clear();
1721
1722 // C++ [basic.lookup.koenig]p2:
1723 // For each argument type T in the function call, there is a set
1724 // of zero or more associated namespaces and a set of zero or more
1725 // associated classes to be considered. The sets of namespaces and
1726 // classes is determined entirely by the types of the function
1727 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001728 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001729 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1730 Expr *Arg = Args[ArgIdx];
1731
1732 if (Arg->getType() != Context.OverloadTy) {
1733 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001734 AssociatedNamespaces,
1735 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001736 continue;
1737 }
1738
1739 // [...] In addition, if the argument is the name or address of a
1740 // set of overloaded functions and/or function templates, its
1741 // associated classes and namespaces are the union of those
1742 // associated with each of the members of the set: the namespace
1743 // in which the function or function template is defined and the
1744 // classes and namespaces associated with its (non-dependent)
1745 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001746 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001747 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1748 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1749 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001750
John McCalld14a8642009-11-21 08:51:07 +00001751 // TODO: avoid the copies. This should be easy when the cases
1752 // share a storage implementation.
1753 llvm::SmallVector<NamedDecl*, 8> Functions;
1754
1755 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1756 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00001757 else
Douglas Gregore254f902009-02-04 00:32:51 +00001758 continue;
1759
John McCalld14a8642009-11-21 08:51:07 +00001760 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1761 E = Functions.end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001762 // Look through any using declarations to find the underlying function.
1763 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001764
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001765 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1766 if (!FDecl)
1767 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001768
1769 // Add the classes and namespaces associated with the parameter
1770 // types and return type of this function.
1771 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001772 AssociatedNamespaces,
1773 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001774 }
1775 }
1776}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001777
1778/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1779/// an acceptable non-member overloaded operator for a call whose
1780/// arguments have types T1 (and, if non-empty, T2). This routine
1781/// implements the check in C++ [over.match.oper]p3b2 concerning
1782/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001783static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001784IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1785 QualType T1, QualType T2,
1786 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001787 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1788 return true;
1789
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001790 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1791 return true;
1792
John McCall9dd450b2009-09-21 23:43:11 +00001793 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001794 if (Proto->getNumArgs() < 1)
1795 return false;
1796
1797 if (T1->isEnumeralType()) {
1798 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001799 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001800 return true;
1801 }
1802
1803 if (Proto->getNumArgs() < 2)
1804 return false;
1805
1806 if (!T2.isNull() && T2->isEnumeralType()) {
1807 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001808 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001809 return true;
1810 }
1811
1812 return false;
1813}
1814
John McCall5cebab12009-11-18 07:57:50 +00001815NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001816 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00001817 LookupNameKind NameKind,
1818 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001819 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00001820 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00001821 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00001822}
1823
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001824/// \brief Find the protocol with the given name, if any.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001825ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
1826 SourceLocation IdLoc) {
1827 Decl *D = LookupSingleName(TUScope, II, IdLoc,
1828 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001829 return cast_or_null<ObjCProtocolDecl>(D);
1830}
1831
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001832void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001833 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00001834 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001835 // C++ [over.match.oper]p3:
1836 // -- The set of non-member candidates is the result of the
1837 // unqualified lookup of operator@ in the context of the
1838 // expression according to the usual rules for name lookup in
1839 // unqualified function calls (3.4.2) except that all member
1840 // functions are ignored. However, if no operand has a class
1841 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001842 // that have a first parameter of type T1 or "reference to
1843 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001844 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001845 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001846 // when T2 is an enumeration type, are candidate functions.
1847 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00001848 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1849 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00001850
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001851 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1852
John McCall9f3059a2009-10-09 21:13:30 +00001853 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001854 return;
1855
1856 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1857 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00001858 NamedDecl *Found = (*Op)->getUnderlyingDecl();
1859 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001860 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00001861 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001862 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00001863 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001864 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001865 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001866 // later?
1867 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00001868 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00001869 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001870 }
1871}
1872
John McCall8fe68082010-01-26 07:16:45 +00001873void ADLResult::insert(NamedDecl *New) {
1874 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1875
1876 // If we haven't yet seen a decl for this key, or the last decl
1877 // was exactly this one, we're done.
1878 if (Old == 0 || Old == New) {
1879 Old = New;
1880 return;
1881 }
1882
1883 // Otherwise, decide which is a more recent redeclaration.
1884 FunctionDecl *OldFD, *NewFD;
1885 if (isa<FunctionTemplateDecl>(New)) {
1886 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1887 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1888 } else {
1889 OldFD = cast<FunctionDecl>(Old);
1890 NewFD = cast<FunctionDecl>(New);
1891 }
1892
1893 FunctionDecl *Cursor = NewFD;
1894 while (true) {
1895 Cursor = Cursor->getPreviousDeclaration();
1896
1897 // If we got to the end without finding OldFD, OldFD is the newer
1898 // declaration; leave things as they are.
1899 if (!Cursor) return;
1900
1901 // If we do find OldFD, then NewFD is newer.
1902 if (Cursor == OldFD) break;
1903
1904 // Otherwise, keep looking.
1905 }
1906
1907 Old = New;
1908}
1909
Sebastian Redlc057f422009-10-23 19:23:15 +00001910void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001911 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00001912 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001913 // Find all of the associated namespaces and classes based on the
1914 // arguments we have.
1915 AssociatedNamespaceSet AssociatedNamespaces;
1916 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00001917 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00001918 AssociatedNamespaces,
1919 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001920
Sebastian Redlc057f422009-10-23 19:23:15 +00001921 QualType T1, T2;
1922 if (Operator) {
1923 T1 = Args[0]->getType();
1924 if (NumArgs >= 2)
1925 T2 = Args[1]->getType();
1926 }
1927
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001928 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001929 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1930 // and let Y be the lookup set produced by argument dependent
1931 // lookup (defined as follows). If X contains [...] then Y is
1932 // empty. Otherwise Y is the set of declarations found in the
1933 // namespaces associated with the argument types as described
1934 // below. The set of declarations found by the lookup of the name
1935 // is the union of X and Y.
1936 //
1937 // Here, we compute Y and add its members to the overloaded
1938 // candidate set.
1939 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001940 NSEnd = AssociatedNamespaces.end();
1941 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001942 // When considering an associated namespace, the lookup is the
1943 // same as the lookup performed when the associated namespace is
1944 // used as a qualifier (3.4.3.2) except that:
1945 //
1946 // -- Any using-directives in the associated namespace are
1947 // ignored.
1948 //
John McCallc7e8e792009-08-07 22:18:02 +00001949 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001950 // associated classes are visible within their respective
1951 // namespaces even if they are not visible during an ordinary
1952 // lookup (11.4).
1953 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00001954 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00001955 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00001956 // If the only declaration here is an ordinary friend, consider
1957 // it only if it was declared in an associated classes.
1958 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00001959 DeclContext *LexDC = D->getLexicalDeclContext();
1960 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1961 continue;
1962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963
John McCall91f61fc2010-01-26 06:04:06 +00001964 if (isa<UsingShadowDecl>(D))
1965 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00001966
John McCall91f61fc2010-01-26 06:04:06 +00001967 if (isa<FunctionDecl>(D)) {
1968 if (Operator &&
1969 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
1970 T1, T2, Context))
1971 continue;
John McCall8fe68082010-01-26 07:16:45 +00001972 } else if (!isa<FunctionTemplateDecl>(D))
1973 continue;
1974
1975 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00001976 }
1977 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001978}
Douglas Gregor2d435302009-12-30 17:04:44 +00001979
1980//----------------------------------------------------------------------------
1981// Search for all visible declarations.
1982//----------------------------------------------------------------------------
1983VisibleDeclConsumer::~VisibleDeclConsumer() { }
1984
1985namespace {
1986
1987class ShadowContextRAII;
1988
1989class VisibleDeclsRecord {
1990public:
1991 /// \brief An entry in the shadow map, which is optimized to store a
1992 /// single declaration (the common case) but can also store a list
1993 /// of declarations.
1994 class ShadowMapEntry {
1995 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1996
1997 /// \brief Contains either the solitary NamedDecl * or a vector
1998 /// of declarations.
1999 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2000
2001 public:
2002 ShadowMapEntry() : DeclOrVector() { }
2003
2004 void Add(NamedDecl *ND);
2005 void Destroy();
2006
2007 // Iteration.
2008 typedef NamedDecl **iterator;
2009 iterator begin();
2010 iterator end();
2011 };
2012
2013private:
2014 /// \brief A mapping from declaration names to the declarations that have
2015 /// this name within a particular scope.
2016 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2017
2018 /// \brief A list of shadow maps, which is used to model name hiding.
2019 std::list<ShadowMap> ShadowMaps;
2020
2021 /// \brief The declaration contexts we have already visited.
2022 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2023
2024 friend class ShadowContextRAII;
2025
2026public:
2027 /// \brief Determine whether we have already visited this context
2028 /// (and, if not, note that we are going to visit that context now).
2029 bool visitedContext(DeclContext *Ctx) {
2030 return !VisitedContexts.insert(Ctx);
2031 }
2032
2033 /// \brief Determine whether the given declaration is hidden in the
2034 /// current scope.
2035 ///
2036 /// \returns the declaration that hides the given declaration, or
2037 /// NULL if no such declaration exists.
2038 NamedDecl *checkHidden(NamedDecl *ND);
2039
2040 /// \brief Add a declaration to the current shadow map.
2041 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2042};
2043
2044/// \brief RAII object that records when we've entered a shadow context.
2045class ShadowContextRAII {
2046 VisibleDeclsRecord &Visible;
2047
2048 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2049
2050public:
2051 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2052 Visible.ShadowMaps.push_back(ShadowMap());
2053 }
2054
2055 ~ShadowContextRAII() {
2056 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2057 EEnd = Visible.ShadowMaps.back().end();
2058 E != EEnd;
2059 ++E)
2060 E->second.Destroy();
2061
2062 Visible.ShadowMaps.pop_back();
2063 }
2064};
2065
2066} // end anonymous namespace
2067
2068void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2069 if (DeclOrVector.isNull()) {
2070 // 0 - > 1 elements: just set the single element information.
2071 DeclOrVector = ND;
2072 return;
2073 }
2074
2075 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2076 // 1 -> 2 elements: create the vector of results and push in the
2077 // existing declaration.
2078 DeclVector *Vec = new DeclVector;
2079 Vec->push_back(PrevND);
2080 DeclOrVector = Vec;
2081 }
2082
2083 // Add the new element to the end of the vector.
2084 DeclOrVector.get<DeclVector*>()->push_back(ND);
2085}
2086
2087void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2088 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2089 delete Vec;
2090 DeclOrVector = ((NamedDecl *)0);
2091 }
2092}
2093
2094VisibleDeclsRecord::ShadowMapEntry::iterator
2095VisibleDeclsRecord::ShadowMapEntry::begin() {
2096 if (DeclOrVector.isNull())
2097 return 0;
2098
2099 if (DeclOrVector.dyn_cast<NamedDecl *>())
2100 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2101
2102 return DeclOrVector.get<DeclVector *>()->begin();
2103}
2104
2105VisibleDeclsRecord::ShadowMapEntry::iterator
2106VisibleDeclsRecord::ShadowMapEntry::end() {
2107 if (DeclOrVector.isNull())
2108 return 0;
2109
2110 if (DeclOrVector.dyn_cast<NamedDecl *>())
2111 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2112
2113 return DeclOrVector.get<DeclVector *>()->end();
2114}
2115
2116NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002117 // Look through using declarations.
2118 ND = ND->getUnderlyingDecl();
2119
Douglas Gregor2d435302009-12-30 17:04:44 +00002120 unsigned IDNS = ND->getIdentifierNamespace();
2121 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2122 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2123 SM != SMEnd; ++SM) {
2124 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2125 if (Pos == SM->end())
2126 continue;
2127
2128 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2129 IEnd = Pos->second.end();
2130 I != IEnd; ++I) {
2131 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002132 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor2d435302009-12-30 17:04:44 +00002133 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2134 Decl::IDNS_ObjCProtocol)))
2135 continue;
2136
2137 // Protocols are in distinct namespaces from everything else.
2138 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2139 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2140 (*I)->getIdentifierNamespace() != IDNS)
2141 continue;
2142
Douglas Gregor09bbc652010-01-14 15:47:35 +00002143 // Functions and function templates in the same scope overload
2144 // rather than hide. FIXME: Look for hiding based on function
2145 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002146 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002147 ND->isFunctionOrFunctionTemplate() &&
2148 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002149 continue;
2150
Douglas Gregor2d435302009-12-30 17:04:44 +00002151 // We've found a declaration that hides this one.
2152 return *I;
2153 }
2154 }
2155
2156 return 0;
2157}
2158
2159static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2160 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002161 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002162 VisibleDeclConsumer &Consumer,
2163 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002164 if (!Ctx)
2165 return;
2166
Douglas Gregor2d435302009-12-30 17:04:44 +00002167 // Make sure we don't visit the same context twice.
2168 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2169 return;
2170
2171 // Enumerate all of the results in this context.
2172 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2173 CurCtx = CurCtx->getNextContext()) {
2174 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2175 DEnd = CurCtx->decls_end();
2176 D != DEnd; ++D) {
2177 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2178 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002179 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002180 Visited.add(ND);
2181 }
2182
2183 // Visit transparent contexts inside this context.
2184 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2185 if (InnerCtx->isTransparentContext())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002186 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002187 Consumer, Visited);
2188 }
2189 }
2190 }
2191
2192 // Traverse using directives for qualified name lookup.
2193 if (QualifiedNameLookup) {
2194 ShadowContextRAII Shadow(Visited);
2195 DeclContext::udir_iterator I, E;
2196 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2197 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002198 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002199 }
2200 }
2201
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002202 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002203 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002204 if (!Record->hasDefinition())
2205 return;
2206
Douglas Gregor2d435302009-12-30 17:04:44 +00002207 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2208 BEnd = Record->bases_end();
2209 B != BEnd; ++B) {
2210 QualType BaseType = B->getType();
2211
2212 // Don't look into dependent bases, because name lookup can't look
2213 // there anyway.
2214 if (BaseType->isDependentType())
2215 continue;
2216
2217 const RecordType *Record = BaseType->getAs<RecordType>();
2218 if (!Record)
2219 continue;
2220
2221 // FIXME: It would be nice to be able to determine whether referencing
2222 // a particular member would be ambiguous. For example, given
2223 //
2224 // struct A { int member; };
2225 // struct B { int member; };
2226 // struct C : A, B { };
2227 //
2228 // void f(C *c) { c->### }
2229 //
2230 // accessing 'member' would result in an ambiguity. However, we
2231 // could be smart enough to qualify the member with the base
2232 // class, e.g.,
2233 //
2234 // c->B::member
2235 //
2236 // or
2237 //
2238 // c->A::member
2239
2240 // Find results in this base class (and its bases).
2241 ShadowContextRAII Shadow(Visited);
2242 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002243 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002244 }
2245 }
2246
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002247 // Traverse the contexts of Objective-C classes.
2248 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2249 // Traverse categories.
2250 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2251 Category; Category = Category->getNextClassCategory()) {
2252 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002253 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2254 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002255 }
2256
2257 // Traverse protocols.
2258 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2259 E = IFace->protocol_end(); I != E; ++I) {
2260 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002261 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2262 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002263 }
2264
2265 // Traverse the superclass.
2266 if (IFace->getSuperClass()) {
2267 ShadowContextRAII Shadow(Visited);
2268 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002269 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002270 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002271
2272 // If there is an implementation, traverse it. We do this to find
2273 // synthesized ivars.
2274 if (IFace->getImplementation()) {
2275 ShadowContextRAII Shadow(Visited);
2276 LookupVisibleDecls(IFace->getImplementation(), Result,
2277 QualifiedNameLookup, true, Consumer, Visited);
2278 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002279 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2280 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2281 E = Protocol->protocol_end(); I != E; ++I) {
2282 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002283 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2284 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002285 }
2286 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2287 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2288 E = Category->protocol_end(); I != E; ++I) {
2289 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002290 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2291 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002292 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002293
2294 // If there is an implementation, traverse it.
2295 if (Category->getImplementation()) {
2296 ShadowContextRAII Shadow(Visited);
2297 LookupVisibleDecls(Category->getImplementation(), Result,
2298 QualifiedNameLookup, true, Consumer, Visited);
2299 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002300 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002301}
2302
2303static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2304 UnqualUsingDirectiveSet &UDirs,
2305 VisibleDeclConsumer &Consumer,
2306 VisibleDeclsRecord &Visited) {
2307 if (!S)
2308 return;
2309
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002310 if (!S->getEntity() || !S->getParent() ||
2311 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2312 // Walk through the declarations in this Scope.
2313 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2314 D != DEnd; ++D) {
2315 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2316 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002317 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002318 Visited.add(ND);
2319 }
2320 }
2321 }
2322
Douglas Gregor66230062010-03-15 14:33:29 +00002323 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002324 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002325 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002326 // Look into this scope's declaration context, along with any of its
2327 // parent lookup contexts (e.g., enclosing classes), up to the point
2328 // where we hit the context stored in the next outer scope.
2329 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002330 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor2d435302009-12-30 17:04:44 +00002331
Douglas Gregorea166062010-03-15 15:26:48 +00002332 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002333 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002334 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2335 if (Method->isInstanceMethod()) {
2336 // For instance methods, look for ivars in the method's interface.
2337 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2338 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002339 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2340 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2341 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002342 }
2343
2344 // We've already performed all of the name lookup that we need
2345 // to for Objective-C methods; the next context will be the
2346 // outer scope.
2347 break;
2348 }
2349
Douglas Gregor2d435302009-12-30 17:04:44 +00002350 if (Ctx->isFunctionOrMethod())
2351 continue;
2352
2353 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002354 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002355 }
2356 } else if (!S->getParent()) {
2357 // Look into the translation unit scope. We walk through the translation
2358 // unit's declaration context, because the Scope itself won't have all of
2359 // the declarations if we loaded a precompiled header.
2360 // FIXME: We would like the translation unit's Scope object to point to the
2361 // translation unit, so we don't need this special "if" branch. However,
2362 // doing so would force the normal C++ name-lookup code to look into the
2363 // translation unit decl when the IdentifierInfo chains would suffice.
2364 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002365 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002366 Entity = Result.getSema().Context.getTranslationUnitDecl();
2367 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002368 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002369 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002370
2371 if (Entity) {
2372 // Lookup visible declarations in any namespaces found by using
2373 // directives.
2374 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2375 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2376 for (; UI != UEnd; ++UI)
2377 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002378 Result, /*QualifiedNameLookup=*/false,
2379 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002380 }
2381
2382 // Lookup names in the parent scope.
2383 ShadowContextRAII Shadow(Visited);
2384 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2385}
2386
2387void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2388 VisibleDeclConsumer &Consumer) {
2389 // Determine the set of using directives available during
2390 // unqualified name lookup.
2391 Scope *Initial = S;
2392 UnqualUsingDirectiveSet UDirs;
2393 if (getLangOptions().CPlusPlus) {
2394 // Find the first namespace or translation-unit scope.
2395 while (S && !isNamespaceOrTranslationUnitScope(S))
2396 S = S->getParent();
2397
2398 UDirs.visitScopeChain(Initial, S);
2399 }
2400 UDirs.done();
2401
2402 // Look for visible declarations.
2403 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2404 VisibleDeclsRecord Visited;
2405 ShadowContextRAII Shadow(Visited);
2406 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2407}
2408
2409void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2410 VisibleDeclConsumer &Consumer) {
2411 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2412 VisibleDeclsRecord Visited;
2413 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002414 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2415 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002416}
2417
2418//----------------------------------------------------------------------------
2419// Typo correction
2420//----------------------------------------------------------------------------
2421
2422namespace {
2423class TypoCorrectionConsumer : public VisibleDeclConsumer {
2424 /// \brief The name written that is a typo in the source.
2425 llvm::StringRef Typo;
2426
2427 /// \brief The results found that have the smallest edit distance
2428 /// found (so far) with the typo name.
2429 llvm::SmallVector<NamedDecl *, 4> BestResults;
2430
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002431 /// \brief The keywords that have the smallest edit distance.
2432 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2433
Douglas Gregor2d435302009-12-30 17:04:44 +00002434 /// \brief The best edit distance found so far.
2435 unsigned BestEditDistance;
2436
2437public:
2438 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2439 : Typo(Typo->getName()) { }
2440
Douglas Gregor09bbc652010-01-14 15:47:35 +00002441 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002442 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002443
2444 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2445 iterator begin() const { return BestResults.begin(); }
2446 iterator end() const { return BestResults.end(); }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002447 void clear_decls() { BestResults.clear(); }
2448
2449 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002450
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002451 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2452 keyword_iterator;
2453 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2454 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2455 bool keyword_empty() const { return BestKeywords.empty(); }
2456 unsigned keyword_size() const { return BestKeywords.size(); }
2457
2458 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002459};
2460
2461}
2462
Douglas Gregor09bbc652010-01-14 15:47:35 +00002463void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2464 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002465 // Don't consider hidden names for typo correction.
2466 if (Hiding)
2467 return;
2468
2469 // Only consider entities with identifiers for names, ignoring
2470 // special names (constructors, overloaded operators, selectors,
2471 // etc.).
2472 IdentifierInfo *Name = ND->getIdentifier();
2473 if (!Name)
2474 return;
2475
2476 // Compute the edit distance between the typo and the name of this
2477 // entity. If this edit distance is not worse than the best edit
2478 // distance we've seen so far, add it to the list of results.
2479 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002480 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002481 if (ED < BestEditDistance) {
2482 // This result is better than any we've seen before; clear out
2483 // the previous results.
2484 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002485 BestKeywords.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002486 BestEditDistance = ED;
2487 } else if (ED > BestEditDistance) {
2488 // This result is worse than the best results we've seen so far;
2489 // ignore it.
2490 return;
2491 }
2492 } else
2493 BestEditDistance = ED;
2494
2495 BestResults.push_back(ND);
2496}
2497
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002498void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2499 llvm::StringRef Keyword) {
2500 // Compute the edit distance between the typo and this keyword.
2501 // If this edit distance is not worse than the best edit
2502 // distance we've seen so far, add it to the list of results.
2503 unsigned ED = Typo.edit_distance(Keyword);
2504 if (!BestResults.empty() || !BestKeywords.empty()) {
2505 if (ED < BestEditDistance) {
2506 BestResults.clear();
2507 BestKeywords.clear();
2508 BestEditDistance = ED;
2509 } else if (ED > BestEditDistance) {
2510 // This result is worse than the best results we've seen so far;
2511 // ignore it.
2512 return;
2513 }
2514 } else
2515 BestEditDistance = ED;
2516
2517 BestKeywords.push_back(&Context.Idents.get(Keyword));
2518}
2519
Douglas Gregor2d435302009-12-30 17:04:44 +00002520/// \brief Try to "correct" a typo in the source code by finding
2521/// visible declarations whose names are similar to the name that was
2522/// present in the source code.
2523///
2524/// \param Res the \c LookupResult structure that contains the name
2525/// that was present in the source code along with the name-lookup
2526/// criteria used to search for the name. On success, this structure
2527/// will contain the results of name lookup.
2528///
2529/// \param S the scope in which name lookup occurs.
2530///
2531/// \param SS the nested-name-specifier that precedes the name we're
2532/// looking for, if present.
2533///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002534/// \param MemberContext if non-NULL, the context in which to look for
2535/// a member access expression.
2536///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002537/// \param EnteringContext whether we're entering the context described by
2538/// the nested-name-specifier SS.
2539///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002540/// \param CTC The context in which typo correction occurs, which impacts the
2541/// set of keywords permitted.
2542///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002543/// \param OPT when non-NULL, the search for visible declarations will
2544/// also walk the protocols in the qualified interfaces of \p OPT.
2545///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002546/// \returns the corrected name if the typo was corrected, otherwise returns an
2547/// empty \c DeclarationName. When a typo was corrected, the result structure
2548/// may contain the results of name lookup for the correct name or it may be
2549/// empty.
2550DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002551 DeclContext *MemberContext,
2552 bool EnteringContext,
2553 CorrectTypoContext CTC,
2554 const ObjCObjectPointerType *OPT) {
Ted Kremeneke51136e2010-01-06 00:23:04 +00002555 if (Diags.hasFatalErrorOccurred())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002556 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002557
2558 // Provide a stop gap for files that are just seriously broken. Trying
2559 // to correct all typos can turn into a HUGE performance penalty, causing
2560 // some files to take minutes to get rejected by the parser.
2561 // FIXME: Is this the right solution?
2562 if (TyposCorrected == 20)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002563 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002564 ++TyposCorrected;
Ted Kremeneke51136e2010-01-06 00:23:04 +00002565
Douglas Gregor2d435302009-12-30 17:04:44 +00002566 // We only attempt to correct typos for identifiers.
2567 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2568 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002569 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002570
2571 // If the scope specifier itself was invalid, don't try to correct
2572 // typos.
2573 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002574 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002575
2576 // Never try to correct typos during template deduction or
2577 // instantiation.
2578 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002579 return DeclarationName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002580
Douglas Gregor2d435302009-12-30 17:04:44 +00002581 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002582
2583 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002584 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002585 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002586
2587 // Look in qualified interfaces.
2588 if (OPT) {
2589 for (ObjCObjectPointerType::qual_iterator
2590 I = OPT->qual_begin(), E = OPT->qual_end();
2591 I != E; ++I)
2592 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2593 }
2594 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002595 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2596 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002597 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002598
2599 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2600 } else {
2601 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2602 }
2603
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002604 // Add context-dependent keywords.
2605 bool WantTypeSpecifiers = false;
2606 bool WantExpressionKeywords = false;
2607 bool WantCXXNamedCasts = false;
2608 bool WantRemainingKeywords = false;
2609 switch (CTC) {
2610 case CTC_Unknown:
2611 WantTypeSpecifiers = true;
2612 WantExpressionKeywords = true;
2613 WantCXXNamedCasts = true;
2614 WantRemainingKeywords = true;
Douglas Gregor5fd04d42010-05-18 16:14:23 +00002615
2616 if (ObjCMethodDecl *Method = getCurMethodDecl())
2617 if (Method->getClassInterface() &&
2618 Method->getClassInterface()->getSuperClass())
2619 Consumer.addKeywordResult(Context, "super");
2620
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002621 break;
2622
2623 case CTC_NoKeywords:
2624 break;
2625
2626 case CTC_Type:
2627 WantTypeSpecifiers = true;
2628 break;
2629
2630 case CTC_ObjCMessageReceiver:
2631 Consumer.addKeywordResult(Context, "super");
2632 // Fall through to handle message receivers like expressions.
2633
2634 case CTC_Expression:
2635 if (getLangOptions().CPlusPlus)
2636 WantTypeSpecifiers = true;
2637 WantExpressionKeywords = true;
2638 // Fall through to get C++ named casts.
2639
2640 case CTC_CXXCasts:
2641 WantCXXNamedCasts = true;
2642 break;
2643
2644 case CTC_MemberLookup:
2645 if (getLangOptions().CPlusPlus)
2646 Consumer.addKeywordResult(Context, "template");
2647 break;
2648 }
2649
2650 if (WantTypeSpecifiers) {
2651 // Add type-specifier keywords to the set of results.
2652 const char *CTypeSpecs[] = {
2653 "char", "const", "double", "enum", "float", "int", "long", "short",
2654 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2655 "_Complex", "_Imaginary",
2656 // storage-specifiers as well
2657 "extern", "inline", "static", "typedef"
2658 };
2659
2660 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2661 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2662 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2663
2664 if (getLangOptions().C99)
2665 Consumer.addKeywordResult(Context, "restrict");
2666 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2667 Consumer.addKeywordResult(Context, "bool");
2668
2669 if (getLangOptions().CPlusPlus) {
2670 Consumer.addKeywordResult(Context, "class");
2671 Consumer.addKeywordResult(Context, "typename");
2672 Consumer.addKeywordResult(Context, "wchar_t");
2673
2674 if (getLangOptions().CPlusPlus0x) {
2675 Consumer.addKeywordResult(Context, "char16_t");
2676 Consumer.addKeywordResult(Context, "char32_t");
2677 Consumer.addKeywordResult(Context, "constexpr");
2678 Consumer.addKeywordResult(Context, "decltype");
2679 Consumer.addKeywordResult(Context, "thread_local");
2680 }
2681 }
2682
2683 if (getLangOptions().GNUMode)
2684 Consumer.addKeywordResult(Context, "typeof");
2685 }
2686
Douglas Gregor86ad0852010-05-18 16:30:22 +00002687 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002688 Consumer.addKeywordResult(Context, "const_cast");
2689 Consumer.addKeywordResult(Context, "dynamic_cast");
2690 Consumer.addKeywordResult(Context, "reinterpret_cast");
2691 Consumer.addKeywordResult(Context, "static_cast");
2692 }
2693
2694 if (WantExpressionKeywords) {
2695 Consumer.addKeywordResult(Context, "sizeof");
2696 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2697 Consumer.addKeywordResult(Context, "false");
2698 Consumer.addKeywordResult(Context, "true");
2699 }
2700
2701 if (getLangOptions().CPlusPlus) {
2702 const char *CXXExprs[] = {
2703 "delete", "new", "operator", "throw", "typeid"
2704 };
2705 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2706 for (unsigned I = 0; I != NumCXXExprs; ++I)
2707 Consumer.addKeywordResult(Context, CXXExprs[I]);
2708
2709 if (isa<CXXMethodDecl>(CurContext) &&
2710 cast<CXXMethodDecl>(CurContext)->isInstance())
2711 Consumer.addKeywordResult(Context, "this");
2712
2713 if (getLangOptions().CPlusPlus0x) {
2714 Consumer.addKeywordResult(Context, "alignof");
2715 Consumer.addKeywordResult(Context, "nullptr");
2716 }
2717 }
2718 }
2719
2720 if (WantRemainingKeywords) {
2721 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2722 // Statements.
2723 const char *CStmts[] = {
2724 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2725 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2726 for (unsigned I = 0; I != NumCStmts; ++I)
2727 Consumer.addKeywordResult(Context, CStmts[I]);
2728
2729 if (getLangOptions().CPlusPlus) {
2730 Consumer.addKeywordResult(Context, "catch");
2731 Consumer.addKeywordResult(Context, "try");
2732 }
2733
2734 if (S && S->getBreakParent())
2735 Consumer.addKeywordResult(Context, "break");
2736
2737 if (S && S->getContinueParent())
2738 Consumer.addKeywordResult(Context, "continue");
2739
2740 if (!getSwitchStack().empty()) {
2741 Consumer.addKeywordResult(Context, "case");
2742 Consumer.addKeywordResult(Context, "default");
2743 }
2744 } else {
2745 if (getLangOptions().CPlusPlus) {
2746 Consumer.addKeywordResult(Context, "namespace");
2747 Consumer.addKeywordResult(Context, "template");
2748 }
2749
2750 if (S && S->isClassScope()) {
2751 Consumer.addKeywordResult(Context, "explicit");
2752 Consumer.addKeywordResult(Context, "friend");
2753 Consumer.addKeywordResult(Context, "mutable");
2754 Consumer.addKeywordResult(Context, "private");
2755 Consumer.addKeywordResult(Context, "protected");
2756 Consumer.addKeywordResult(Context, "public");
2757 Consumer.addKeywordResult(Context, "virtual");
2758 }
2759 }
2760
2761 if (getLangOptions().CPlusPlus) {
2762 Consumer.addKeywordResult(Context, "using");
2763
2764 if (getLangOptions().CPlusPlus0x)
2765 Consumer.addKeywordResult(Context, "static_assert");
2766 }
2767 }
2768
2769 // If we haven't found anything, we're done.
Douglas Gregor2d435302009-12-30 17:04:44 +00002770 if (Consumer.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002771 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002772
2773 // Only allow a single, closest name in the result set (it's okay to
2774 // have overloads of that name, though).
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002775 DeclarationName BestName;
2776 NamedDecl *BestIvarOrPropertyDecl = 0;
2777 bool FoundIvarOrPropertyDecl = false;
2778
2779 // Check all of the declaration results to find the best name so far.
2780 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2781 IEnd = Consumer.end();
2782 I != IEnd; ++I) {
2783 if (!BestName)
2784 BestName = (*I)->getDeclName();
2785 else if (BestName != (*I)->getDeclName())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002786 return DeclarationName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002787
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002788 // \brief Keep track of either an Objective-C ivar or a property, but not
2789 // both.
2790 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
2791 if (FoundIvarOrPropertyDecl)
2792 BestIvarOrPropertyDecl = 0;
2793 else {
2794 BestIvarOrPropertyDecl = *I;
2795 FoundIvarOrPropertyDecl = true;
2796 }
2797 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002798 }
2799
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002800 // Now check all of the keyword results to find the best name.
2801 switch (Consumer.keyword_size()) {
2802 case 0:
2803 // No keywords matched.
2804 break;
2805
2806 case 1:
2807 // If we already have a name
2808 if (!BestName) {
2809 // We did not have anything previously,
2810 BestName = *Consumer.keyword_begin();
2811 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
2812 // We have a declaration with the same name as a context-sensitive
2813 // keyword. The keyword takes precedence.
2814 BestIvarOrPropertyDecl = 0;
2815 FoundIvarOrPropertyDecl = false;
2816 Consumer.clear_decls();
Douglas Gregor86ad0852010-05-18 16:30:22 +00002817 } else if (CTC == CTC_ObjCMessageReceiver &&
2818 (*Consumer.keyword_begin())->isStr("super")) {
2819 // In an Objective-C message send, give the "super" keyword a slight
2820 // edge over entities not in function or method scope.
2821 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2822 IEnd = Consumer.end();
2823 I != IEnd; ++I) {
2824 if ((*I)->getDeclName() == BestName) {
2825 if ((*I)->getDeclContext()->isFunctionOrMethod())
2826 return DeclarationName();
2827 }
2828 }
2829
2830 // Everything found was outside a function or method; the 'super'
2831 // keyword takes precedence.
2832 BestIvarOrPropertyDecl = 0;
2833 FoundIvarOrPropertyDecl = false;
2834 Consumer.clear_decls();
2835 BestName = *Consumer.keyword_begin();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002836 } else {
2837 // Name collision; we will not correct typos.
2838 return DeclarationName();
2839 }
2840 break;
2841
2842 default:
2843 // Name collision; we will not correct typos.
2844 return DeclarationName();
2845 }
2846
Douglas Gregor2d435302009-12-30 17:04:44 +00002847 // BestName is the closest viable name to what the user
2848 // typed. However, to make sure that we don't pick something that's
2849 // way off, make sure that the user typed at least 3 characters for
2850 // each correction.
2851 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002852 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
2853 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002854 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002855
2856 // Perform name lookup again with the name we chose, and declare
2857 // success if we found something that was not ambiguous.
2858 Res.clear();
2859 Res.setLookupName(BestName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002860
2861 // If we found an ivar or property, add that result; no further
2862 // lookup is required.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002863 if (BestIvarOrPropertyDecl)
2864 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002865 // If we're looking into the context of a member, perform qualified
2866 // name lookup on the best name.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002867 else if (!Consumer.keyword_empty()) {
2868 // The best match was a keyword. Return it.
2869 return BestName;
2870 } else if (MemberContext)
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002871 LookupQualifiedName(Res, MemberContext);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002872 // Perform lookup as if we had just parsed the best name.
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002873 else
2874 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2875 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00002876
2877 if (Res.isAmbiguous()) {
2878 Res.suppressDiagnostics();
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002879 return DeclarationName();
Douglas Gregor598b08f2009-12-31 05:20:13 +00002880 }
2881
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002882 if (Res.getResultKind() != LookupResult::NotFound)
2883 return BestName;
2884
2885 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002886}