blob: 4555a86e01c8891435a3b84610758d4fa1eebcf9 [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6e247262009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor546be3c2009-12-30 17:04:44 +000030#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000031#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000032#include <vector>
33#include <iterator>
34#include <utility>
35#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000036
37using namespace clang;
38
John McCalld7be78a2009-11-10 07:01:13 +000039namespace {
40 class UnqualUsingEntry {
41 const DeclContext *Nominated;
42 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000043
John McCalld7be78a2009-11-10 07:01:13 +000044 public:
45 UnqualUsingEntry(const DeclContext *Nominated,
46 const DeclContext *CommonAncestor)
47 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
48 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000049
John McCalld7be78a2009-11-10 07:01:13 +000050 const DeclContext *getCommonAncestor() const {
51 return CommonAncestor;
52 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000053
John McCalld7be78a2009-11-10 07:01:13 +000054 const DeclContext *getNominatedNamespace() const {
55 return Nominated;
56 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000057
John McCalld7be78a2009-11-10 07:01:13 +000058 // Sort by the pointer value of the common ancestor.
59 struct Comparator {
60 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
61 return L.getCommonAncestor() < R.getCommonAncestor();
62 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000063
John McCalld7be78a2009-11-10 07:01:13 +000064 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
65 return E.getCommonAncestor() < DC;
66 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000067
John McCalld7be78a2009-11-10 07:01:13 +000068 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
69 return DC < E.getCommonAncestor();
70 }
71 };
72 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000073
John McCalld7be78a2009-11-10 07:01:13 +000074 /// A collection of using directives, as used by C++ unqualified
75 /// lookup.
76 class UnqualUsingDirectiveSet {
77 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000078
John McCalld7be78a2009-11-10 07:01:13 +000079 ListTy list;
80 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000081
John McCalld7be78a2009-11-10 07:01:13 +000082 public:
83 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000084
John McCalld7be78a2009-11-10 07:01:13 +000085 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
86 // C++ [namespace.udir]p1:
87 // During unqualified name lookup, the names appear as if they
88 // were declared in the nearest enclosing namespace which contains
89 // both the using-directive and the nominated namespace.
90 DeclContext *InnermostFileDC
91 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
92 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +000093
John McCalld7be78a2009-11-10 07:01:13 +000094 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +000095 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
96 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
97 visit(Ctx, EffectiveDC);
98 } else {
99 Scope::udir_iterator I = S->using_directives_begin(),
100 End = S->using_directives_end();
101
102 for (; I != End; ++I)
103 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
104 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000105 }
106 }
John McCalld7be78a2009-11-10 07:01:13 +0000107
108 // Visits a context and collect all of its using directives
109 // recursively. Treats all using directives as if they were
110 // declared in the context.
111 //
112 // A given context is only every visited once, so it is important
113 // that contexts be visited from the inside out in order to get
114 // the effective DCs right.
115 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
116 if (!visited.insert(DC))
117 return;
118
119 addUsingDirectives(DC, EffectiveDC);
120 }
121
122 // Visits a using directive and collects all of its using
123 // directives recursively. Treats all using directives as if they
124 // were declared in the effective DC.
125 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
126 DeclContext *NS = UD->getNominatedNamespace();
127 if (!visited.insert(NS))
128 return;
129
130 addUsingDirective(UD, EffectiveDC);
131 addUsingDirectives(NS, EffectiveDC);
132 }
133
134 // Adds all the using directives in a context (and those nominated
135 // by its using directives, transitively) as if they appeared in
136 // the given effective context.
137 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
138 llvm::SmallVector<DeclContext*,4> queue;
139 while (true) {
140 DeclContext::udir_iterator I, End;
141 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
142 UsingDirectiveDecl *UD = *I;
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (visited.insert(NS)) {
145 addUsingDirective(UD, EffectiveDC);
146 queue.push_back(NS);
147 }
148 }
149
150 if (queue.empty())
151 return;
152
153 DC = queue.back();
154 queue.pop_back();
155 }
156 }
157
158 // Add a using directive as if it had been declared in the given
159 // context. This helps implement C++ [namespace.udir]p3:
160 // The using-directive is transitive: if a scope contains a
161 // using-directive that nominates a second namespace that itself
162 // contains using-directives, the effect is as if the
163 // using-directives from the second namespace also appeared in
164 // the first.
165 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
166 // Find the common ancestor between the effective context and
167 // the nominated namespace.
168 DeclContext *Common = UD->getNominatedNamespace();
169 while (!Common->Encloses(EffectiveDC))
170 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000171 Common = Common->getPrimaryContext();
John McCalld7be78a2009-11-10 07:01:13 +0000172
173 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
174 }
175
176 void done() {
177 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
178 }
179
180 typedef ListTy::iterator iterator;
181 typedef ListTy::const_iterator const_iterator;
182
183 iterator begin() { return list.begin(); }
184 iterator end() { return list.end(); }
185 const_iterator begin() const { return list.begin(); }
186 const_iterator end() const { return list.end(); }
187
188 std::pair<const_iterator,const_iterator>
189 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000190 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000191 UnqualUsingEntry::Comparator());
192 }
193 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000194}
195
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000196// Retrieve the set of identifier namespaces that correspond to a
197// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000198static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
199 bool CPlusPlus,
200 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000201 unsigned IDNS = 0;
202 switch (NameKind) {
203 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000204 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000205 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000206 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCall1d7c5282009-12-18 10:40:03 +0000208 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
209 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000210 break;
211
John McCall76d32642010-04-24 01:30:58 +0000212 case Sema::LookupOperatorName:
213 // Operator lookup is its own crazy thing; it is not the same
214 // as (e.g.) looking up an operator name for redeclaration.
215 assert(!Redeclaration && "cannot do redeclaration operator lookup");
216 IDNS = Decl::IDNS_NonMemberOperator;
217 break;
218
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000219 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000220 if (CPlusPlus) {
221 IDNS = Decl::IDNS_Type;
222
223 // When looking for a redeclaration of a tag name, we add:
224 // 1) TagFriend to find undeclared friend decls
225 // 2) Namespace because they can't "overload" with tag decls.
226 // 3) Tag because it includes class templates, which can't
227 // "overload" with tag decls.
228 if (Redeclaration)
229 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
230 } else {
231 IDNS = Decl::IDNS_Tag;
232 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000233 break;
234
235 case Sema::LookupMemberName:
236 IDNS = Decl::IDNS_Member;
237 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000238 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000239 break;
240
241 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000242 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
243 break;
244
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000245 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000246 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000247 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000248
John McCall9f54ad42009-12-10 09:41:52 +0000249 case Sema::LookupUsingDeclName:
250 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
251 | Decl::IDNS_Member | Decl::IDNS_Using;
252 break;
253
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000254 case Sema::LookupObjCProtocolName:
255 IDNS = Decl::IDNS_ObjCProtocol;
256 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000257 }
258 return IDNS;
259}
260
John McCall1d7c5282009-12-18 10:40:03 +0000261void LookupResult::configure() {
262 IDNS = getIDNS(LookupKind,
263 SemaRef.getLangOptions().CPlusPlus,
264 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000265
266 // If we're looking for one of the allocation or deallocation
267 // operators, make sure that the implicitly-declared new and delete
268 // operators can be found.
269 if (!isForRedeclaration()) {
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 McCall1d7c5282009-12-18 10:40:03 +0000282}
283
John McCallf36e02d2009-10-09 21:13:30 +0000284// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000285void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000286 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000287}
288
John McCall7453ed42009-11-22 00:44:51 +0000289/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000290void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000291 unsigned N = Decls.size();
John McCall9f54ad42009-12-10 09:41:52 +0000292
John McCallf36e02d2009-10-09 21:13:30 +0000293 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000294 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000295 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000296 return;
297 }
298
John McCall7453ed42009-11-22 00:44:51 +0000299 // If there's a single decl, we need to examine it to decide what
300 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000301 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000302 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
303 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000304 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000305 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000306 ResultKind = FoundUnresolvedValue;
307 return;
308 }
John McCallf36e02d2009-10-09 21:13:30 +0000309
John McCall6e247262009-10-10 05:48:19 +0000310 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000311 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000312
John McCallf36e02d2009-10-09 21:13:30 +0000313 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
314
315 bool Ambiguous = false;
316 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000317 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000318
319 unsigned UniqueTagIndex = 0;
320
321 unsigned I = 0;
322 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000323 NamedDecl *D = Decls[I]->getUnderlyingDecl();
324 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000325
John McCall314be4e2009-11-17 07:50:12 +0000326 if (!Unique.insert(D)) {
John McCallf36e02d2009-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 McCallf36e02d2009-10-09 21:13:30 +0000330 } else {
331 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000332
333 if (isa<UnresolvedUsingValueDecl>(D)) {
334 HasUnresolved = true;
335 } else if (isa<TagDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000336 if (HasTag)
337 Ambiguous = true;
338 UniqueTagIndex = I;
339 HasTag = true;
John McCall7453ed42009-11-22 00:44:51 +0000340 } else if (isa<FunctionTemplateDecl>(D)) {
341 HasFunction = true;
342 HasFunctionTemplate = true;
343 } else if (isa<FunctionDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000344 HasFunction = true;
345 } else {
346 if (HasNonFunction)
347 Ambiguous = true;
348 HasNonFunction = true;
349 }
350 I++;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000351 }
Mike Stump1eb44332009-09-09 15:08:12 +0000352 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000353
John McCallf36e02d2009-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 McCallfda8e122009-12-03 00:58:24 +0000363 if (HideTags && HasTag && !Ambiguous &&
364 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000365 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000366
John McCallf36e02d2009-10-09 21:13:30 +0000367 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000368
John McCallfda8e122009-12-03 00:58:24 +0000369 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000370 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000371
John McCallf36e02d2009-10-09 21:13:30 +0000372 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000373 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000374 else if (HasUnresolved)
375 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000376 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000377 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000378 else
John McCalla24dc2e2009-11-17 02:14:36 +0000379 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000380}
381
John McCall7d384dd2009-11-18 07:57:50 +0000382void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000383 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-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 Gregor31a19b62009-04-01 21:51:26 +0000388}
389
John McCall7d384dd2009-11-18 07:57:50 +0000390void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000391 Paths = new CXXBasePaths;
392 Paths->swap(P);
393 addDeclsFromBasePaths(*Paths);
394 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000395 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000396}
397
John McCall7d384dd2009-11-18 07:57:50 +0000398void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000399 Paths = new CXXBasePaths;
400 Paths->swap(P);
401 addDeclsFromBasePaths(*Paths);
402 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000403 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000404}
405
John McCall7d384dd2009-11-18 07:57:50 +0000406void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-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 Gregor85910982010-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 McCallf36e02d2009-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 Gregor85910982010-02-12 05:48:04 +0000452static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000453 bool Found = false;
454
John McCalld7be78a2009-11-10 07:01:13 +0000455 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000456 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000457 NamedDecl *D = *I;
458 if (R.isAcceptableDecl(D)) {
459 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000460 Found = true;
461 }
462 }
John McCallf36e02d2009-10-09 21:13:30 +0000463
Douglas Gregor85910982010-02-12 05:48:04 +0000464 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
465 return true;
466
Douglas Gregor48026d22010-01-11 18:40:55 +0000467 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-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 Gregor48026d22010-01-11 18:40:55 +0000498 // C++ [temp.mem]p6:
Chandler Carruthaaa1a892010-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 McCall5769d612010-02-08 23:07:23 +0000508 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-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 Gregor3f477a12010-01-12 01:17:50 +0000514
Chandler Carruthaaa1a892010-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 Espindola264ba482010-03-30 20:24:48 +0000518 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruthaaa1a892010-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 Espindola264ba482010-03-30 20:24:48 +0000524 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruthaaa1a892010-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 Gregor48026d22010-01-11 18:40:55 +0000533 }
534 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000535
John McCallf36e02d2009-10-09 21:13:30 +0000536 return Found;
537}
538
John McCalld7be78a2009-11-10 07:01:13 +0000539// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000540static bool
Douglas Gregor85910982010-02-12 05:48:04 +0000541CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
542 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000543
544 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
545
John McCalld7be78a2009-11-10 07:01:13 +0000546 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000547 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000548
John McCalld7be78a2009-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 Stump1eb44332009-09-09 15:08:12 +0000553
John McCalld7be78a2009-11-10 07:01:13 +0000554 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000555 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000556 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000557
558 R.resolveKind();
559
560 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000561}
562
563static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000564 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000565 return Ctx->isFileContext();
566 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000567}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000568
Douglas Gregor711be1e2010-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 Gregordbdf5e72010-03-15 15:26:48 +0000582 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-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 Gregore942bbe2009-09-10 16:57:35 +0000620
Douglas Gregor711be1e2010-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 Gregore942bbe2009-09-10 16:57:35 +0000636}
637
John McCalla24dc2e2009-11-17 02:14:36 +0000638bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000639 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000640
641 DeclarationName Name = R.getLookupName();
642
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000643 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000644 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000645 I = IdResolver.begin(Name),
646 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000647
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000648 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000649 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-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 Friedman33a31382009-08-05 19:21:58 +0000653 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000654 // indirectly".
Douglas Gregor2a3009a2009-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 Gregor47b9a1c2009-02-04 17:27:36 +0000665 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000666 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000667 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000668 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
669
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000670 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000671 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000672 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000673 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000674 Found = true;
675 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000676 }
677 }
John McCallf36e02d2009-10-09 21:13:30 +0000678 if (Found) {
679 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000680 if (S->isClassScope())
681 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
682 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000683 return true;
684 }
685
Douglas Gregor711be1e2010-03-15 14:33:29 +0000686 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
687 S->getParent() && !S->getParent()->isTemplateParamScope()) {
688 // We've just searched the last template parameter scope and
689 // found nothing, so look into the the contexts between the
690 // lexical and semantic declaration contexts returned by
691 // findOuterContext(). This implements the name lookup behavior
692 // of C++ [temp.local]p8.
693 Ctx = OutsideOfTemplateParamDC;
694 OutsideOfTemplateParamDC = 0;
695 }
696
697 if (Ctx) {
698 DeclContext *OuterCtx;
699 bool SearchAfterTemplateScope;
700 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
701 if (SearchAfterTemplateScope)
702 OutsideOfTemplateParamDC = OuterCtx;
703
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000704 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000705 // We do not directly look into transparent contexts, since
706 // those entities will be found in the nearest enclosing
707 // non-transparent context.
708 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000709 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000710
711 // We do not look directly into function or method contexts,
712 // since all of the local variables and parameters of the
713 // function/method are present within the Scope.
714 if (Ctx->isFunctionOrMethod()) {
715 // If we have an Objective-C instance method, look for ivars
716 // in the corresponding interface.
717 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
718 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
719 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
720 ObjCInterfaceDecl *ClassDeclared;
721 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
722 Name.getAsIdentifierInfo(),
723 ClassDeclared)) {
724 if (R.isAcceptableDecl(Ivar)) {
725 R.addDecl(Ivar);
726 R.resolveKind();
727 return true;
728 }
729 }
730 }
731 }
732
733 continue;
734 }
735
Douglas Gregore942bbe2009-09-10 16:57:35 +0000736 // Perform qualified name lookup into this context.
737 // FIXME: In some cases, we know that every name that could be found by
738 // this qualified name lookup will also be on the identifier chain. For
739 // example, inside a class without any base classes, we never need to
740 // perform qualified lookup because all of the members are on top of the
741 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000742 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000743 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000744 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000745 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000746 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000747
John McCalld7be78a2009-11-10 07:01:13 +0000748 // Stop if we ran out of scopes.
749 // FIXME: This really, really shouldn't be happening.
750 if (!S) return false;
751
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000752 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000753 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000754 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000755 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
756 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000757
John McCalld7be78a2009-11-10 07:01:13 +0000758 UnqualUsingDirectiveSet UDirs;
759 UDirs.visitScopeChain(Initial, S);
760 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000761
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000762 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000763 // Unqualified name lookup in C++ requires looking into scopes
764 // that aren't strictly lexical, and therefore we walk through the
765 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000766
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000767 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000768 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000769 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000770 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000771 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000772 // We found something. Look for anything else in our scope
773 // with this same name and in an acceptable identifier
774 // namespace, so that we can construct an overload set if we
775 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000776 Found = true;
777 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000778 }
779 }
780
Douglas Gregor00b4b032010-05-14 04:53:42 +0000781 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000782 R.resolveKind();
783 return true;
784 }
785
Douglas Gregor00b4b032010-05-14 04:53:42 +0000786 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
787 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
788 S->getParent() && !S->getParent()->isTemplateParamScope()) {
789 // We've just searched the last template parameter scope and
790 // found nothing, so look into the the contexts between the
791 // lexical and semantic declaration contexts returned by
792 // findOuterContext(). This implements the name lookup behavior
793 // of C++ [temp.local]p8.
794 Ctx = OutsideOfTemplateParamDC;
795 OutsideOfTemplateParamDC = 0;
796 }
797
798 if (Ctx) {
799 DeclContext *OuterCtx;
800 bool SearchAfterTemplateScope;
801 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
802 if (SearchAfterTemplateScope)
803 OutsideOfTemplateParamDC = OuterCtx;
804
805 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
806 // We do not directly look into transparent contexts, since
807 // those entities will be found in the nearest enclosing
808 // non-transparent context.
809 if (Ctx->isTransparentContext())
810 continue;
811
812 // If we have a context, and it's not a context stashed in the
813 // template parameter scope for an out-of-line definition, also
814 // look into that context.
815 if (!(Found && S && S->isTemplateParamScope())) {
816 assert(Ctx->isFileContext() &&
817 "We should have been looking only at file context here already.");
818
819 // Look into context considering using-directives.
820 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
821 Found = true;
822 }
823
824 if (Found) {
825 R.resolveKind();
826 return true;
827 }
828
829 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
830 return false;
831 }
832 }
833
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000834 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000835 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000836 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000837
John McCallf36e02d2009-10-09 21:13:30 +0000838 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000839}
840
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000841/// @brief Perform unqualified name lookup starting from a given
842/// scope.
843///
844/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
845/// used to find names within the current scope. For example, 'x' in
846/// @code
847/// int x;
848/// int f() {
849/// return x; // unqualified name look finds 'x' in the global scope
850/// }
851/// @endcode
852///
853/// Different lookup criteria can find different names. For example, a
854/// particular scope can have both a struct and a function of the same
855/// name, and each can be found by certain lookup criteria. For more
856/// information about lookup criteria, see the documentation for the
857/// class LookupCriteria.
858///
859/// @param S The scope from which unqualified name lookup will
860/// begin. If the lookup criteria permits, name lookup may also search
861/// in the parent scopes.
862///
863/// @param Name The name of the entity that we are searching for.
864///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000865/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +0000866/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +0000867/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000868///
869/// @returns The result of name lookup, which includes zero or more
870/// declarations and possibly additional information used to diagnose
871/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000872bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
873 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +0000874 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000875
John McCalla24dc2e2009-11-17 02:14:36 +0000876 LookupNameKind NameKind = R.getLookupKind();
877
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000878 if (!getLangOptions().CPlusPlus) {
879 // Unqualified name lookup in C/Objective-C is purely lexical, so
880 // search in the declarations attached to the name.
881
John McCall1d7c5282009-12-18 10:40:03 +0000882 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000883 // Find the nearest non-transparent declaration scope.
884 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000885 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000886 static_cast<DeclContext *>(S->getEntity())
887 ->isTransparentContext()))
888 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000889 }
890
John McCall1d7c5282009-12-18 10:40:03 +0000891 unsigned IDNS = R.getIdentifierNamespace();
892
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000893 // Scan up the scope chain looking for a decl that matches this
894 // identifier that is in the appropriate namespace. This search
895 // should not take long, as shadowing of names is uncommon, and
896 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000897 bool LeftStartingScope = false;
898
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000899 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +0000900 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000901 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000902 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000903 if (NameKind == LookupRedeclarationWithLinkage) {
904 // Determine whether this (or a previous) declaration is
905 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000906 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000907 LeftStartingScope = true;
908
909 // If we found something outside of our starting scope that
910 // does not have linkage, skip it.
911 if (LeftStartingScope && !((*I)->hasLinkage()))
912 continue;
913 }
914
John McCallf36e02d2009-10-09 21:13:30 +0000915 R.addDecl(*I);
916
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000917 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000918 // If this declaration has the "overloadable" attribute, we
919 // might have a set of overloaded functions.
920
921 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000922 while (!(S->getFlags() & Scope::DeclScope) ||
923 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000924 S = S->getParent();
925
926 // Find the last declaration in this scope (with the same
927 // name, naturally).
928 IdentifierResolver::iterator LastI = I;
929 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000930 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000931 break;
John McCallf36e02d2009-10-09 21:13:30 +0000932 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000933 }
Douglas Gregorf9201e02009-02-11 23:02:49 +0000934 }
935
John McCallf36e02d2009-10-09 21:13:30 +0000936 R.resolveKind();
937
938 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000939 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000940 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000941 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000942 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +0000943 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000944 }
945
946 // If we didn't find a use of this identifier, and if the identifier
947 // corresponds to a compiler builtin, create the decl object for the builtin
948 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +0000949 if (AllowBuiltinCreation)
950 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000951
John McCallf36e02d2009-10-09 21:13:30 +0000952 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000953}
954
John McCall6e247262009-10-10 05:48:19 +0000955/// @brief Perform qualified name lookup in the namespaces nominated by
956/// using directives by the given context.
957///
958/// C++98 [namespace.qual]p2:
959/// Given X::m (where X is a user-declared namespace), or given ::m
960/// (where X is the global namespace), let S be the set of all
961/// declarations of m in X and in the transitive closure of all
962/// namespaces nominated by using-directives in X and its used
963/// namespaces, except that using-directives are ignored in any
964/// namespace, including X, directly containing one or more
965/// declarations of m. No namespace is searched more than once in
966/// the lookup of a name. If S is the empty set, the program is
967/// ill-formed. Otherwise, if S has exactly one member, or if the
968/// context of the reference is a using-declaration
969/// (namespace.udecl), S is the required set of declarations of
970/// m. Otherwise if the use of m is not one that allows a unique
971/// declaration to be chosen from S, the program is ill-formed.
972/// C++98 [namespace.qual]p5:
973/// During the lookup of a qualified namespace member name, if the
974/// lookup finds more than one declaration of the member, and if one
975/// declaration introduces a class name or enumeration name and the
976/// other declarations either introduce the same object, the same
977/// enumerator or a set of functions, the non-type name hides the
978/// class or enumeration name if and only if the declarations are
979/// from the same namespace; otherwise (the declarations are from
980/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +0000981static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +0000982 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +0000983 assert(StartDC->isFileContext() && "start context is not a file context");
984
985 DeclContext::udir_iterator I = StartDC->using_directives_begin();
986 DeclContext::udir_iterator E = StartDC->using_directives_end();
987
988 if (I == E) return false;
989
990 // We have at least added all these contexts to the queue.
991 llvm::DenseSet<DeclContext*> Visited;
992 Visited.insert(StartDC);
993
994 // We have not yet looked into these namespaces, much less added
995 // their "using-children" to the queue.
996 llvm::SmallVector<NamespaceDecl*, 8> Queue;
997
998 // We have already looked into the initial namespace; seed the queue
999 // with its using-children.
1000 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001001 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001002 if (Visited.insert(ND).second)
1003 Queue.push_back(ND);
1004 }
1005
1006 // The easiest way to implement the restriction in [namespace.qual]p5
1007 // is to check whether any of the individual results found a tag
1008 // and, if so, to declare an ambiguity if the final result is not
1009 // a tag.
1010 bool FoundTag = false;
1011 bool FoundNonTag = false;
1012
John McCall7d384dd2009-11-18 07:57:50 +00001013 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001014
1015 bool Found = false;
1016 while (!Queue.empty()) {
1017 NamespaceDecl *ND = Queue.back();
1018 Queue.pop_back();
1019
1020 // We go through some convolutions here to avoid copying results
1021 // between LookupResults.
1022 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001023 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001024 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001025
1026 if (FoundDirect) {
1027 // First do any local hiding.
1028 DirectR.resolveKind();
1029
1030 // If the local result is a tag, remember that.
1031 if (DirectR.isSingleTagDecl())
1032 FoundTag = true;
1033 else
1034 FoundNonTag = true;
1035
1036 // Append the local results to the total results if necessary.
1037 if (UseLocal) {
1038 R.addAllDecls(LocalR);
1039 LocalR.clear();
1040 }
1041 }
1042
1043 // If we find names in this namespace, ignore its using directives.
1044 if (FoundDirect) {
1045 Found = true;
1046 continue;
1047 }
1048
1049 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1050 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1051 if (Visited.insert(Nom).second)
1052 Queue.push_back(Nom);
1053 }
1054 }
1055
1056 if (Found) {
1057 if (FoundTag && FoundNonTag)
1058 R.setAmbiguousQualifiedTagHiding();
1059 else
1060 R.resolveKind();
1061 }
1062
1063 return Found;
1064}
1065
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001066/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001067///
1068/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1069/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001070/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001071///
1072/// Different lookup criteria can find different names. For example, a
1073/// particular scope can have both a struct and a function of the same
1074/// name, and each can be found by certain lookup criteria. For more
1075/// information about lookup criteria, see the documentation for the
1076/// class LookupCriteria.
1077///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001078/// \param R captures both the lookup criteria and any lookup results found.
1079///
1080/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001081/// search. If the lookup criteria permits, name lookup may also search
1082/// in the parent contexts or (for C++ classes) base classes.
1083///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001084/// \param InUnqualifiedLookup true if this is qualified name lookup that
1085/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001086///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001087/// \returns true if lookup succeeded, false if it failed.
1088bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1089 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001090 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001091
John McCalla24dc2e2009-11-17 02:14:36 +00001092 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001093 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001095 // Make sure that the declaration context is complete.
1096 assert((!isa<TagDecl>(LookupCtx) ||
1097 LookupCtx->isDependentContext() ||
1098 cast<TagDecl>(LookupCtx)->isDefinition() ||
1099 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1100 ->isBeingDefined()) &&
1101 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001103 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001104 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001105 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001106 if (isa<CXXRecordDecl>(LookupCtx))
1107 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001108 return true;
1109 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001110
John McCall6e247262009-10-10 05:48:19 +00001111 // Don't descend into implied contexts for redeclarations.
1112 // C++98 [namespace.qual]p6:
1113 // In a declaration for a namespace member in which the
1114 // declarator-id is a qualified-id, given that the qualified-id
1115 // for the namespace member has the form
1116 // nested-name-specifier unqualified-id
1117 // the unqualified-id shall name a member of the namespace
1118 // designated by the nested-name-specifier.
1119 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001120 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001121 return false;
1122
John McCalla24dc2e2009-11-17 02:14:36 +00001123 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001124 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001125 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001126
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001127 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001128 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001129 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1130 if (!LookupRec)
John McCallf36e02d2009-10-09 21:13:30 +00001131 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001132
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001133 // If we're performing qualified name lookup into a dependent class,
1134 // then we are actually looking into a current instantiation. If we have any
1135 // dependent base classes, then we either have to delay lookup until
1136 // template instantiation time (at which point all bases will be available)
1137 // or we have to fail.
1138 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1139 LookupRec->hasAnyDependentBases()) {
1140 R.setNotFoundInCurrentInstantiation();
1141 return false;
1142 }
1143
Douglas Gregor7176fff2009-01-15 00:26:24 +00001144 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001145 CXXBasePaths Paths;
1146 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001147
1148 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001149 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001150 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001151 case LookupOrdinaryName:
1152 case LookupMemberName:
1153 case LookupRedeclarationWithLinkage:
1154 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1155 break;
1156
1157 case LookupTagName:
1158 BaseCallback = &CXXRecordDecl::FindTagMember;
1159 break;
John McCall9f54ad42009-12-10 09:41:52 +00001160
1161 case LookupUsingDeclName:
1162 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001163
1164 case LookupOperatorName:
1165 case LookupNamespaceName:
1166 case LookupObjCProtocolName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001167 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001168 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001169
1170 case LookupNestedNameSpecifierName:
1171 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1172 break;
1173 }
1174
John McCalla24dc2e2009-11-17 02:14:36 +00001175 if (!LookupRec->lookupInBases(BaseCallback,
1176 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001177 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001178
John McCall92f88312010-01-23 00:46:32 +00001179 R.setNamingClass(LookupRec);
1180
Douglas Gregor7176fff2009-01-15 00:26:24 +00001181 // C++ [class.member.lookup]p2:
1182 // [...] If the resulting set of declarations are not all from
1183 // sub-objects of the same type, or the set has a nonstatic member
1184 // and includes members from distinct sub-objects, there is an
1185 // ambiguity and the program is ill-formed. Otherwise that set is
1186 // the result of the lookup.
1187 // FIXME: support using declarations!
1188 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001189 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001190 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001191 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001192 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001193 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001194
John McCall46460a62010-01-20 21:53:11 +00001195 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1196 // across all paths.
1197 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1198
Douglas Gregor7176fff2009-01-15 00:26:24 +00001199 // Determine whether we're looking at a distinct sub-object or not.
1200 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001201 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001202 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1203 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00001204 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001205 != Context.getCanonicalType(PathElement.Base->getType())) {
1206 // We found members of the given name in two subobjects of
1207 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001208 R.setAmbiguousBaseSubobjectTypes(Paths);
1209 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001210 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1211 // We have a different subobject of the same type.
1212
1213 // C++ [class.member.lookup]p5:
1214 // A static member, a nested type or an enumerator defined in
1215 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001216 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001217 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001218 if (isa<VarDecl>(FirstDecl) ||
1219 isa<TypeDecl>(FirstDecl) ||
1220 isa<EnumConstantDecl>(FirstDecl))
1221 continue;
1222
1223 if (isa<CXXMethodDecl>(FirstDecl)) {
1224 // Determine whether all of the methods are static.
1225 bool AllMethodsAreStatic = true;
1226 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1227 Func != Path->Decls.second; ++Func) {
1228 if (!isa<CXXMethodDecl>(*Func)) {
1229 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1230 break;
1231 }
1232
1233 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1234 AllMethodsAreStatic = false;
1235 break;
1236 }
1237 }
1238
1239 if (AllMethodsAreStatic)
1240 continue;
1241 }
1242
1243 // We have found a nonstatic member name in multiple, distinct
1244 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001245 R.setAmbiguousBaseSubobjects(Paths);
1246 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001247 }
1248 }
1249
1250 // Lookup in a base class succeeded; return these results.
1251
John McCallf36e02d2009-10-09 21:13:30 +00001252 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001253 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1254 NamedDecl *D = *I;
1255 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1256 D->getAccess());
1257 R.addDecl(D, AS);
1258 }
John McCallf36e02d2009-10-09 21:13:30 +00001259 R.resolveKind();
1260 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001261}
1262
1263/// @brief Performs name lookup for a name that was parsed in the
1264/// source code, and may contain a C++ scope specifier.
1265///
1266/// This routine is a convenience routine meant to be called from
1267/// contexts that receive a name and an optional C++ scope specifier
1268/// (e.g., "N::M::x"). It will then perform either qualified or
1269/// unqualified name lookup (with LookupQualifiedName or LookupName,
1270/// respectively) on the given name and return those results.
1271///
1272/// @param S The scope from which unqualified name lookup will
1273/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001274///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001275/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001276///
1277/// @param Name The name of the entity that name lookup will
1278/// search for.
1279///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001280/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001281/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001282/// C library functions (like "malloc") are implicitly declared.
1283///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001284/// @param EnteringContext Indicates whether we are going to enter the
1285/// context of the scope-specifier SS (if present).
1286///
John McCallf36e02d2009-10-09 21:13:30 +00001287/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001288bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001289 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001290 if (SS && SS->isInvalid()) {
1291 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001292 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001293 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001294 }
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Douglas Gregor495c35d2009-08-25 22:51:20 +00001296 if (SS && SS->isSet()) {
1297 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001298 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001299 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001300 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001301 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001302
John McCalla24dc2e2009-11-17 02:14:36 +00001303 R.setContextRange(SS->getRange());
1304
1305 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001306 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001307
Douglas Gregor495c35d2009-08-25 22:51:20 +00001308 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001309 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001310 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001311 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001312 }
1313
Mike Stump1eb44332009-09-09 15:08:12 +00001314 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001315 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001316}
1317
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001318
Douglas Gregor7176fff2009-01-15 00:26:24 +00001319/// @brief Produce a diagnostic describing the ambiguity that resulted
1320/// from name lookup.
1321///
1322/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001323///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001324/// @param Name The name of the entity that name lookup was
1325/// searching for.
1326///
1327/// @param NameLoc The location of the name within the source code.
1328///
1329/// @param LookupRange A source range that provides more
1330/// source-location information concerning the lookup itself. For
1331/// example, this range might highlight a nested-name-specifier that
1332/// precedes the name.
1333///
1334/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001335bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001336 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1337
John McCalla24dc2e2009-11-17 02:14:36 +00001338 DeclarationName Name = Result.getLookupName();
1339 SourceLocation NameLoc = Result.getNameLoc();
1340 SourceRange LookupRange = Result.getContextRange();
1341
John McCall6e247262009-10-10 05:48:19 +00001342 switch (Result.getAmbiguityKind()) {
1343 case LookupResult::AmbiguousBaseSubobjects: {
1344 CXXBasePaths *Paths = Result.getBasePaths();
1345 QualType SubobjectType = Paths->front().back().Base->getType();
1346 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1347 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1348 << LookupRange;
1349
1350 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1351 while (isa<CXXMethodDecl>(*Found) &&
1352 cast<CXXMethodDecl>(*Found)->isStatic())
1353 ++Found;
1354
1355 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1356
1357 return true;
1358 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001359
John McCall6e247262009-10-10 05:48:19 +00001360 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001361 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1362 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001363
1364 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001365 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001366 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1367 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001368 Path != PathEnd; ++Path) {
1369 Decl *D = *Path->Decls.first;
1370 if (DeclsPrinted.insert(D).second)
1371 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1372 }
1373
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001374 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001375 }
1376
John McCall6e247262009-10-10 05:48:19 +00001377 case LookupResult::AmbiguousTagHiding: {
1378 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001379
John McCall6e247262009-10-10 05:48:19 +00001380 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1381
1382 LookupResult::iterator DI, DE = Result.end();
1383 for (DI = Result.begin(); DI != DE; ++DI)
1384 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1385 TagDecls.insert(TD);
1386 Diag(TD->getLocation(), diag::note_hidden_tag);
1387 }
1388
1389 for (DI = Result.begin(); DI != DE; ++DI)
1390 if (!isa<TagDecl>(*DI))
1391 Diag((*DI)->getLocation(), diag::note_hiding_object);
1392
1393 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001394 LookupResult::Filter F = Result.makeFilter();
1395 while (F.hasNext()) {
1396 if (TagDecls.count(F.next()))
1397 F.erase();
1398 }
1399 F.done();
John McCall6e247262009-10-10 05:48:19 +00001400
1401 return true;
1402 }
1403
1404 case LookupResult::AmbiguousReference: {
1405 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001406
John McCall6e247262009-10-10 05:48:19 +00001407 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1408 for (; DI != DE; ++DI)
1409 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001410
John McCall6e247262009-10-10 05:48:19 +00001411 return true;
1412 }
1413 }
1414
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001415 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001416 return true;
1417}
Douglas Gregorfa047642009-02-04 00:32:51 +00001418
Mike Stump1eb44332009-09-09 15:08:12 +00001419static void
1420addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001421 ASTContext &Context,
1422 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001423 Sema::AssociatedClassSet &AssociatedClasses);
1424
Douglas Gregor54022952010-04-30 07:08:38 +00001425static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1426 DeclContext *Ctx) {
1427 // Add the associated namespace for this class.
1428
1429 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1430 // be a locally scoped record.
1431
1432 while (Ctx->isRecord() || Ctx->isTransparentContext())
1433 Ctx = Ctx->getParent();
1434
John McCall6ff07852009-08-07 22:18:02 +00001435 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001436 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001437}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001438
Mike Stump1eb44332009-09-09 15:08:12 +00001439// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001440// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001441static void
1442addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001443 ASTContext &Context,
1444 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001445 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001446 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001447 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001448 switch (Arg.getKind()) {
1449 case TemplateArgument::Null:
1450 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Douglas Gregor69be8d62009-07-08 07:51:57 +00001452 case TemplateArgument::Type:
1453 // [...] the namespaces and classes associated with the types of the
1454 // template arguments provided for template type parameters (excluding
1455 // template template parameters)
1456 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1457 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001458 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001459 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Douglas Gregor788cd062009-11-11 01:00:40 +00001461 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001462 // [...] the namespaces in which any template template arguments are
1463 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001464 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001465 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001466 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001467 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001468 DeclContext *Ctx = ClassTemplate->getDeclContext();
1469 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1470 AssociatedClasses.insert(EnclosingClass);
1471 // Add the associated namespace for this class.
Douglas Gregor54022952010-04-30 07:08:38 +00001472 CollectEnclosingNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001473 }
1474 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001475 }
1476
1477 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001478 case TemplateArgument::Integral:
1479 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001480 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001481 // associated namespaces. ]
1482 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Douglas Gregor69be8d62009-07-08 07:51:57 +00001484 case TemplateArgument::Pack:
1485 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1486 PEnd = Arg.pack_end();
1487 P != PEnd; ++P)
1488 addAssociatedClassesAndNamespaces(*P, Context,
1489 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001490 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001491 break;
1492 }
1493}
1494
Douglas Gregorfa047642009-02-04 00:32:51 +00001495// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001496// argument-dependent lookup with an argument of class type
1497// (C++ [basic.lookup.koenig]p2).
1498static void
1499addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregorfa047642009-02-04 00:32:51 +00001500 ASTContext &Context,
1501 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001502 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001503 // C++ [basic.lookup.koenig]p2:
1504 // [...]
1505 // -- If T is a class type (including unions), its associated
1506 // classes are: the class itself; the class of which it is a
1507 // member, if any; and its direct and indirect base
1508 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001509 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001510
1511 // Add the class of which it is a member, if any.
1512 DeclContext *Ctx = Class->getDeclContext();
1513 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1514 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001515 // Add the associated namespace for this class.
Douglas Gregor54022952010-04-30 07:08:38 +00001516 CollectEnclosingNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Douglas Gregorfa047642009-02-04 00:32:51 +00001518 // Add the class itself. If we've already seen this class, we don't
1519 // need to visit base classes.
1520 if (!AssociatedClasses.insert(Class))
1521 return;
1522
Mike Stump1eb44332009-09-09 15:08:12 +00001523 // -- If T is a template-id, its associated namespaces and classes are
1524 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001525 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001526 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001527 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001528 // namespaces in which any template template arguments are defined; and
1529 // the classes in which any member templates used as template template
1530 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001531 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001532 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001533 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1534 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1535 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1536 AssociatedClasses.insert(EnclosingClass);
1537 // Add the associated namespace for this class.
Douglas Gregor54022952010-04-30 07:08:38 +00001538 CollectEnclosingNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Douglas Gregor69be8d62009-07-08 07:51:57 +00001540 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1541 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1542 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1543 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001544 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001545 }
Mike Stump1eb44332009-09-09 15:08:12 +00001546
John McCall86ff3082010-02-04 22:26:26 +00001547 // Only recurse into base classes for complete types.
1548 if (!Class->hasDefinition()) {
1549 // FIXME: we might need to instantiate templates here
1550 return;
1551 }
1552
Douglas Gregorfa047642009-02-04 00:32:51 +00001553 // Add direct and indirect base classes along with their associated
1554 // namespaces.
1555 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1556 Bases.push_back(Class);
1557 while (!Bases.empty()) {
1558 // Pop this class off the stack.
1559 Class = Bases.back();
1560 Bases.pop_back();
1561
1562 // Visit the base classes.
1563 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1564 BaseEnd = Class->bases_end();
1565 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001566 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001567 // In dependent contexts, we do ADL twice, and the first time around,
1568 // the base type might be a dependent TemplateSpecializationType, or a
1569 // TemplateTypeParmType. If that happens, simply ignore it.
1570 // FIXME: If we want to support export, we probably need to add the
1571 // namespace of the template in a TemplateSpecializationType, or even
1572 // the classes and namespaces of known non-dependent arguments.
1573 if (!BaseType)
1574 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001575 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1576 if (AssociatedClasses.insert(BaseDecl)) {
1577 // Find the associated namespace for this base class.
1578 DeclContext *BaseCtx = BaseDecl->getDeclContext();
Douglas Gregor54022952010-04-30 07:08:38 +00001579 CollectEnclosingNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001580
1581 // Make sure we visit the bases of this base class.
1582 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1583 Bases.push_back(BaseDecl);
1584 }
1585 }
1586 }
1587}
1588
1589// \brief Add the associated classes and namespaces for
1590// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001591// (C++ [basic.lookup.koenig]p2).
1592static void
1593addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregorfa047642009-02-04 00:32:51 +00001594 ASTContext &Context,
1595 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001596 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001597 // C++ [basic.lookup.koenig]p2:
1598 //
1599 // For each argument type T in the function call, there is a set
1600 // of zero or more associated namespaces and a set of zero or more
1601 // associated classes to be considered. The sets of namespaces and
1602 // classes is determined entirely by the types of the function
1603 // arguments (and the namespace of any template template
1604 // argument). Typedef names and using-declarations used to specify
1605 // the types do not contribute to this set. The sets of namespaces
1606 // and classes are determined in the following way:
1607 T = Context.getCanonicalType(T).getUnqualifiedType();
1608
1609 // -- If T is a pointer to U or an array of U, its associated
Mike Stump1eb44332009-09-09 15:08:12 +00001610 // namespaces and classes are those associated with U.
Douglas Gregorfa047642009-02-04 00:32:51 +00001611 //
1612 // We handle this by unwrapping pointer and array types immediately,
1613 // to avoid unnecessary recursion.
1614 while (true) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001615 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001616 T = Ptr->getPointeeType();
1617 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1618 T = Ptr->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001619 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001620 break;
1621 }
1622
1623 // -- If T is a fundamental type, its associated sets of
1624 // namespaces and classes are both empty.
John McCall183700f2009-09-21 23:43:11 +00001625 if (T->getAs<BuiltinType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001626 return;
1627
1628 // -- If T is a class type (including unions), its associated
1629 // classes are: the class itself; the class of which it is a
1630 // member, if any; and its direct and indirect base
1631 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001632 // which its associated classes are defined.
Douglas Gregor4e58c252010-05-20 02:26:51 +00001633 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001634 if (CXXRecordDecl *ClassDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001635 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001636 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1637 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001638 AssociatedClasses);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001639 return;
1640 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001641
Douglas Gregorfa047642009-02-04 00:32:51 +00001642 // -- If T is an enumeration type, its associated namespace is
1643 // the namespace in which it is defined. If it is class
1644 // member, its associated class is the member’s class; else
Mike Stump1eb44332009-09-09 15:08:12 +00001645 // it has no associated class.
John McCall183700f2009-09-21 23:43:11 +00001646 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001647 EnumDecl *Enum = EnumT->getDecl();
1648
1649 DeclContext *Ctx = Enum->getDeclContext();
1650 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1651 AssociatedClasses.insert(EnclosingClass);
1652
1653 // Add the associated namespace for this class.
Douglas Gregor54022952010-04-30 07:08:38 +00001654 CollectEnclosingNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001655
1656 return;
1657 }
1658
1659 // -- If T is a function type, its associated namespaces and
1660 // classes are those associated with the function parameter
1661 // types and those associated with the return type.
John McCall183700f2009-09-21 23:43:11 +00001662 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001663 // Return type
John McCall183700f2009-09-21 23:43:11 +00001664 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001665 Context,
John McCall6ff07852009-08-07 22:18:02 +00001666 AssociatedNamespaces, AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001667
John McCall183700f2009-09-21 23:43:11 +00001668 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001669 if (!Proto)
1670 return;
1671
1672 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001673 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001674 ArgEnd = Proto->arg_type_end();
Douglas Gregorfa047642009-02-04 00:32:51 +00001675 Arg != ArgEnd; ++Arg)
1676 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCall6ff07852009-08-07 22:18:02 +00001677 AssociatedNamespaces, AssociatedClasses);
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Douglas Gregorfa047642009-02-04 00:32:51 +00001679 return;
1680 }
1681
1682 // -- If T is a pointer to a member function of a class X, its
1683 // associated namespaces and classes are those associated
1684 // with the function parameter types and return type,
Mike Stump1eb44332009-09-09 15:08:12 +00001685 // together with those associated with X.
Douglas Gregorfa047642009-02-04 00:32:51 +00001686 //
1687 // -- If T is a pointer to a data member of class X, its
1688 // associated namespaces and classes are those associated
1689 // with the member type together with those associated with
Mike Stump1eb44332009-09-09 15:08:12 +00001690 // X.
Ted Kremenek6217b802009-07-29 21:53:49 +00001691 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001692 // Handle the type that the pointer to member points to.
1693 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1694 Context,
John McCall6ff07852009-08-07 22:18:02 +00001695 AssociatedNamespaces,
1696 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001697
1698 // Handle the class type into which this points.
Ted Kremenek6217b802009-07-29 21:53:49 +00001699 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001700 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1701 Context,
John McCall6ff07852009-08-07 22:18:02 +00001702 AssociatedNamespaces,
1703 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001704
1705 return;
1706 }
1707
1708 // FIXME: What about block pointers?
1709 // FIXME: What about Objective-C message sends?
1710}
1711
1712/// \brief Find the associated classes and namespaces for
1713/// argument-dependent lookup for a call with the given set of
1714/// arguments.
1715///
1716/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001717/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001718/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001719void
Douglas Gregorfa047642009-02-04 00:32:51 +00001720Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1721 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001722 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001723 AssociatedNamespaces.clear();
1724 AssociatedClasses.clear();
1725
1726 // C++ [basic.lookup.koenig]p2:
1727 // For each argument type T in the function call, there is a set
1728 // of zero or more associated namespaces and a set of zero or more
1729 // associated classes to be considered. The sets of namespaces and
1730 // classes is determined entirely by the types of the function
1731 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001732 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001733 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1734 Expr *Arg = Args[ArgIdx];
1735
1736 if (Arg->getType() != Context.OverloadTy) {
1737 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001738 AssociatedNamespaces,
1739 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001740 continue;
1741 }
1742
1743 // [...] In addition, if the argument is the name or address of a
1744 // set of overloaded functions and/or function templates, its
1745 // associated classes and namespaces are the union of those
1746 // associated with each of the members of the set: the namespace
1747 // in which the function or function template is defined and the
1748 // classes and namespaces associated with its (non-dependent)
1749 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001750 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001751 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1752 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1753 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001754
John McCallba135432009-11-21 08:51:07 +00001755 // TODO: avoid the copies. This should be easy when the cases
1756 // share a storage implementation.
1757 llvm::SmallVector<NamedDecl*, 8> Functions;
1758
1759 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1760 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00001761 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001762 continue;
1763
John McCallba135432009-11-21 08:51:07 +00001764 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1765 E = Functions.end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001766 // Look through any using declarations to find the underlying function.
1767 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001768
Chandler Carruthbd647292009-12-29 06:17:27 +00001769 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1770 if (!FDecl)
1771 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001772
1773 // Add the classes and namespaces associated with the parameter
1774 // types and return type of this function.
1775 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001776 AssociatedNamespaces,
1777 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001778 }
1779 }
1780}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001781
1782/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1783/// an acceptable non-member overloaded operator for a call whose
1784/// arguments have types T1 (and, if non-empty, T2). This routine
1785/// implements the check in C++ [over.match.oper]p3b2 concerning
1786/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001787static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001788IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1789 QualType T1, QualType T2,
1790 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001791 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1792 return true;
1793
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001794 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1795 return true;
1796
John McCall183700f2009-09-21 23:43:11 +00001797 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001798 if (Proto->getNumArgs() < 1)
1799 return false;
1800
1801 if (T1->isEnumeralType()) {
1802 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001803 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001804 return true;
1805 }
1806
1807 if (Proto->getNumArgs() < 2)
1808 return false;
1809
1810 if (!T2.isNull() && T2->isEnumeralType()) {
1811 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001812 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001813 return true;
1814 }
1815
1816 return false;
1817}
1818
John McCall7d384dd2009-11-18 07:57:50 +00001819NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00001820 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00001821 LookupNameKind NameKind,
1822 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00001823 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00001824 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00001825 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00001826}
1827
Douglas Gregor6e378de2009-04-23 23:18:26 +00001828/// \brief Find the protocol with the given name, if any.
Douglas Gregorc83c6872010-04-15 22:33:43 +00001829ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
1830 SourceLocation IdLoc) {
1831 Decl *D = LookupSingleName(TUScope, II, IdLoc,
1832 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001833 return cast_or_null<ObjCProtocolDecl>(D);
1834}
1835
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001836void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001837 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00001838 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001839 // C++ [over.match.oper]p3:
1840 // -- The set of non-member candidates is the result of the
1841 // unqualified lookup of operator@ in the context of the
1842 // expression according to the usual rules for name lookup in
1843 // unqualified function calls (3.4.2) except that all member
1844 // functions are ignored. However, if no operand has a class
1845 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00001846 // that have a first parameter of type T1 or "reference to
1847 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001848 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00001849 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001850 // when T2 is an enumeration type, are candidate functions.
1851 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00001852 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1853 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001855 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1856
John McCallf36e02d2009-10-09 21:13:30 +00001857 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001858 return;
1859
1860 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1861 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001862 NamedDecl *Found = (*Op)->getUnderlyingDecl();
1863 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001864 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001865 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00001866 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001867 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001868 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00001869 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00001870 // later?
1871 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001872 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00001873 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001874 }
1875}
1876
John McCall7edb5fd2010-01-26 07:16:45 +00001877void ADLResult::insert(NamedDecl *New) {
1878 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1879
1880 // If we haven't yet seen a decl for this key, or the last decl
1881 // was exactly this one, we're done.
1882 if (Old == 0 || Old == New) {
1883 Old = New;
1884 return;
1885 }
1886
1887 // Otherwise, decide which is a more recent redeclaration.
1888 FunctionDecl *OldFD, *NewFD;
1889 if (isa<FunctionTemplateDecl>(New)) {
1890 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1891 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1892 } else {
1893 OldFD = cast<FunctionDecl>(Old);
1894 NewFD = cast<FunctionDecl>(New);
1895 }
1896
1897 FunctionDecl *Cursor = NewFD;
1898 while (true) {
1899 Cursor = Cursor->getPreviousDeclaration();
1900
1901 // If we got to the end without finding OldFD, OldFD is the newer
1902 // declaration; leave things as they are.
1903 if (!Cursor) return;
1904
1905 // If we do find OldFD, then NewFD is newer.
1906 if (Cursor == OldFD) break;
1907
1908 // Otherwise, keep looking.
1909 }
1910
1911 Old = New;
1912}
1913
Sebastian Redl644be852009-10-23 19:23:15 +00001914void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001915 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00001916 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001917 // Find all of the associated namespaces and classes based on the
1918 // arguments we have.
1919 AssociatedNamespaceSet AssociatedNamespaces;
1920 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00001921 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00001922 AssociatedNamespaces,
1923 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001924
Sebastian Redl644be852009-10-23 19:23:15 +00001925 QualType T1, T2;
1926 if (Operator) {
1927 T1 = Args[0]->getType();
1928 if (NumArgs >= 2)
1929 T2 = Args[1]->getType();
1930 }
1931
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001932 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001933 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1934 // and let Y be the lookup set produced by argument dependent
1935 // lookup (defined as follows). If X contains [...] then Y is
1936 // empty. Otherwise Y is the set of declarations found in the
1937 // namespaces associated with the argument types as described
1938 // below. The set of declarations found by the lookup of the name
1939 // is the union of X and Y.
1940 //
1941 // Here, we compute Y and add its members to the overloaded
1942 // candidate set.
1943 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001944 NSEnd = AssociatedNamespaces.end();
1945 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001946 // When considering an associated namespace, the lookup is the
1947 // same as the lookup performed when the associated namespace is
1948 // used as a qualifier (3.4.3.2) except that:
1949 //
1950 // -- Any using-directives in the associated namespace are
1951 // ignored.
1952 //
John McCall6ff07852009-08-07 22:18:02 +00001953 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001954 // associated classes are visible within their respective
1955 // namespaces even if they are not visible during an ordinary
1956 // lookup (11.4).
1957 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00001958 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00001959 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00001960 // If the only declaration here is an ordinary friend, consider
1961 // it only if it was declared in an associated classes.
1962 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00001963 DeclContext *LexDC = D->getLexicalDeclContext();
1964 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1965 continue;
1966 }
Mike Stump1eb44332009-09-09 15:08:12 +00001967
John McCalla113e722010-01-26 06:04:06 +00001968 if (isa<UsingShadowDecl>(D))
1969 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00001970
John McCalla113e722010-01-26 06:04:06 +00001971 if (isa<FunctionDecl>(D)) {
1972 if (Operator &&
1973 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
1974 T1, T2, Context))
1975 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00001976 } else if (!isa<FunctionTemplateDecl>(D))
1977 continue;
1978
1979 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001980 }
1981 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001982}
Douglas Gregor546be3c2009-12-30 17:04:44 +00001983
1984//----------------------------------------------------------------------------
1985// Search for all visible declarations.
1986//----------------------------------------------------------------------------
1987VisibleDeclConsumer::~VisibleDeclConsumer() { }
1988
1989namespace {
1990
1991class ShadowContextRAII;
1992
1993class VisibleDeclsRecord {
1994public:
1995 /// \brief An entry in the shadow map, which is optimized to store a
1996 /// single declaration (the common case) but can also store a list
1997 /// of declarations.
1998 class ShadowMapEntry {
1999 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2000
2001 /// \brief Contains either the solitary NamedDecl * or a vector
2002 /// of declarations.
2003 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2004
2005 public:
2006 ShadowMapEntry() : DeclOrVector() { }
2007
2008 void Add(NamedDecl *ND);
2009 void Destroy();
2010
2011 // Iteration.
2012 typedef NamedDecl **iterator;
2013 iterator begin();
2014 iterator end();
2015 };
2016
2017private:
2018 /// \brief A mapping from declaration names to the declarations that have
2019 /// this name within a particular scope.
2020 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2021
2022 /// \brief A list of shadow maps, which is used to model name hiding.
2023 std::list<ShadowMap> ShadowMaps;
2024
2025 /// \brief The declaration contexts we have already visited.
2026 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2027
2028 friend class ShadowContextRAII;
2029
2030public:
2031 /// \brief Determine whether we have already visited this context
2032 /// (and, if not, note that we are going to visit that context now).
2033 bool visitedContext(DeclContext *Ctx) {
2034 return !VisitedContexts.insert(Ctx);
2035 }
2036
2037 /// \brief Determine whether the given declaration is hidden in the
2038 /// current scope.
2039 ///
2040 /// \returns the declaration that hides the given declaration, or
2041 /// NULL if no such declaration exists.
2042 NamedDecl *checkHidden(NamedDecl *ND);
2043
2044 /// \brief Add a declaration to the current shadow map.
2045 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2046};
2047
2048/// \brief RAII object that records when we've entered a shadow context.
2049class ShadowContextRAII {
2050 VisibleDeclsRecord &Visible;
2051
2052 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2053
2054public:
2055 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2056 Visible.ShadowMaps.push_back(ShadowMap());
2057 }
2058
2059 ~ShadowContextRAII() {
2060 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2061 EEnd = Visible.ShadowMaps.back().end();
2062 E != EEnd;
2063 ++E)
2064 E->second.Destroy();
2065
2066 Visible.ShadowMaps.pop_back();
2067 }
2068};
2069
2070} // end anonymous namespace
2071
2072void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2073 if (DeclOrVector.isNull()) {
2074 // 0 - > 1 elements: just set the single element information.
2075 DeclOrVector = ND;
2076 return;
2077 }
2078
2079 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2080 // 1 -> 2 elements: create the vector of results and push in the
2081 // existing declaration.
2082 DeclVector *Vec = new DeclVector;
2083 Vec->push_back(PrevND);
2084 DeclOrVector = Vec;
2085 }
2086
2087 // Add the new element to the end of the vector.
2088 DeclOrVector.get<DeclVector*>()->push_back(ND);
2089}
2090
2091void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2092 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2093 delete Vec;
2094 DeclOrVector = ((NamedDecl *)0);
2095 }
2096}
2097
2098VisibleDeclsRecord::ShadowMapEntry::iterator
2099VisibleDeclsRecord::ShadowMapEntry::begin() {
2100 if (DeclOrVector.isNull())
2101 return 0;
2102
2103 if (DeclOrVector.dyn_cast<NamedDecl *>())
2104 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2105
2106 return DeclOrVector.get<DeclVector *>()->begin();
2107}
2108
2109VisibleDeclsRecord::ShadowMapEntry::iterator
2110VisibleDeclsRecord::ShadowMapEntry::end() {
2111 if (DeclOrVector.isNull())
2112 return 0;
2113
2114 if (DeclOrVector.dyn_cast<NamedDecl *>())
2115 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2116
2117 return DeclOrVector.get<DeclVector *>()->end();
2118}
2119
2120NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002121 // Look through using declarations.
2122 ND = ND->getUnderlyingDecl();
2123
Douglas Gregor546be3c2009-12-30 17:04:44 +00002124 unsigned IDNS = ND->getIdentifierNamespace();
2125 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2126 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2127 SM != SMEnd; ++SM) {
2128 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2129 if (Pos == SM->end())
2130 continue;
2131
2132 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2133 IEnd = Pos->second.end();
2134 I != IEnd; ++I) {
2135 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002136 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor546be3c2009-12-30 17:04:44 +00002137 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2138 Decl::IDNS_ObjCProtocol)))
2139 continue;
2140
2141 // Protocols are in distinct namespaces from everything else.
2142 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2143 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2144 (*I)->getIdentifierNamespace() != IDNS)
2145 continue;
2146
Douglas Gregor0cc84042010-01-14 15:47:35 +00002147 // Functions and function templates in the same scope overload
2148 // rather than hide. FIXME: Look for hiding based on function
2149 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002150 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002151 ND->isFunctionOrFunctionTemplate() &&
2152 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002153 continue;
2154
Douglas Gregor546be3c2009-12-30 17:04:44 +00002155 // We've found a declaration that hides this one.
2156 return *I;
2157 }
2158 }
2159
2160 return 0;
2161}
2162
2163static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2164 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002165 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002166 VisibleDeclConsumer &Consumer,
2167 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002168 if (!Ctx)
2169 return;
2170
Douglas Gregor546be3c2009-12-30 17:04:44 +00002171 // Make sure we don't visit the same context twice.
2172 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2173 return;
2174
2175 // Enumerate all of the results in this context.
2176 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2177 CurCtx = CurCtx->getNextContext()) {
2178 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2179 DEnd = CurCtx->decls_end();
2180 D != DEnd; ++D) {
2181 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2182 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002183 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002184 Visited.add(ND);
2185 }
2186
2187 // Visit transparent contexts inside this context.
2188 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2189 if (InnerCtx->isTransparentContext())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002190 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002191 Consumer, Visited);
2192 }
2193 }
2194 }
2195
2196 // Traverse using directives for qualified name lookup.
2197 if (QualifiedNameLookup) {
2198 ShadowContextRAII Shadow(Visited);
2199 DeclContext::udir_iterator I, E;
2200 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2201 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002202 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002203 }
2204 }
2205
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002206 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002207 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002208 if (!Record->hasDefinition())
2209 return;
2210
Douglas Gregor546be3c2009-12-30 17:04:44 +00002211 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2212 BEnd = Record->bases_end();
2213 B != BEnd; ++B) {
2214 QualType BaseType = B->getType();
2215
2216 // Don't look into dependent bases, because name lookup can't look
2217 // there anyway.
2218 if (BaseType->isDependentType())
2219 continue;
2220
2221 const RecordType *Record = BaseType->getAs<RecordType>();
2222 if (!Record)
2223 continue;
2224
2225 // FIXME: It would be nice to be able to determine whether referencing
2226 // a particular member would be ambiguous. For example, given
2227 //
2228 // struct A { int member; };
2229 // struct B { int member; };
2230 // struct C : A, B { };
2231 //
2232 // void f(C *c) { c->### }
2233 //
2234 // accessing 'member' would result in an ambiguity. However, we
2235 // could be smart enough to qualify the member with the base
2236 // class, e.g.,
2237 //
2238 // c->B::member
2239 //
2240 // or
2241 //
2242 // c->A::member
2243
2244 // Find results in this base class (and its bases).
2245 ShadowContextRAII Shadow(Visited);
2246 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002247 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002248 }
2249 }
2250
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002251 // Traverse the contexts of Objective-C classes.
2252 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2253 // Traverse categories.
2254 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2255 Category; Category = Category->getNextClassCategory()) {
2256 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002257 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2258 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002259 }
2260
2261 // Traverse protocols.
2262 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2263 E = IFace->protocol_end(); I != E; ++I) {
2264 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002265 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2266 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002267 }
2268
2269 // Traverse the superclass.
2270 if (IFace->getSuperClass()) {
2271 ShadowContextRAII Shadow(Visited);
2272 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002273 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002274 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002275
2276 // If there is an implementation, traverse it. We do this to find
2277 // synthesized ivars.
2278 if (IFace->getImplementation()) {
2279 ShadowContextRAII Shadow(Visited);
2280 LookupVisibleDecls(IFace->getImplementation(), Result,
2281 QualifiedNameLookup, true, Consumer, Visited);
2282 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002283 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2284 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2285 E = Protocol->protocol_end(); I != E; ++I) {
2286 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002287 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2288 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002289 }
2290 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2291 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2292 E = Category->protocol_end(); I != E; ++I) {
2293 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002294 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2295 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002296 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002297
2298 // If there is an implementation, traverse it.
2299 if (Category->getImplementation()) {
2300 ShadowContextRAII Shadow(Visited);
2301 LookupVisibleDecls(Category->getImplementation(), Result,
2302 QualifiedNameLookup, true, Consumer, Visited);
2303 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002304 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002305}
2306
2307static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2308 UnqualUsingDirectiveSet &UDirs,
2309 VisibleDeclConsumer &Consumer,
2310 VisibleDeclsRecord &Visited) {
2311 if (!S)
2312 return;
2313
Douglas Gregor539c5c32010-01-07 00:31:29 +00002314 if (!S->getEntity() || !S->getParent() ||
2315 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2316 // Walk through the declarations in this Scope.
2317 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2318 D != DEnd; ++D) {
2319 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2320 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002321 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002322 Visited.add(ND);
2323 }
2324 }
2325 }
2326
Douglas Gregor711be1e2010-03-15 14:33:29 +00002327 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002328 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002329 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002330 // Look into this scope's declaration context, along with any of its
2331 // parent lookup contexts (e.g., enclosing classes), up to the point
2332 // where we hit the context stored in the next outer scope.
2333 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002334 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor546be3c2009-12-30 17:04:44 +00002335
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002336 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002337 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002338 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2339 if (Method->isInstanceMethod()) {
2340 // For instance methods, look for ivars in the method's interface.
2341 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2342 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor62021192010-02-04 23:42:48 +00002343 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2344 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2345 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002346 }
2347
2348 // We've already performed all of the name lookup that we need
2349 // to for Objective-C methods; the next context will be the
2350 // outer scope.
2351 break;
2352 }
2353
Douglas Gregor546be3c2009-12-30 17:04:44 +00002354 if (Ctx->isFunctionOrMethod())
2355 continue;
2356
2357 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002358 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002359 }
2360 } else if (!S->getParent()) {
2361 // Look into the translation unit scope. We walk through the translation
2362 // unit's declaration context, because the Scope itself won't have all of
2363 // the declarations if we loaded a precompiled header.
2364 // FIXME: We would like the translation unit's Scope object to point to the
2365 // translation unit, so we don't need this special "if" branch. However,
2366 // doing so would force the normal C++ name-lookup code to look into the
2367 // translation unit decl when the IdentifierInfo chains would suffice.
2368 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002369 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002370 Entity = Result.getSema().Context.getTranslationUnitDecl();
2371 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002372 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002373 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002374
2375 if (Entity) {
2376 // Lookup visible declarations in any namespaces found by using
2377 // directives.
2378 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2379 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2380 for (; UI != UEnd; ++UI)
2381 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002382 Result, /*QualifiedNameLookup=*/false,
2383 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002384 }
2385
2386 // Lookup names in the parent scope.
2387 ShadowContextRAII Shadow(Visited);
2388 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2389}
2390
2391void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2392 VisibleDeclConsumer &Consumer) {
2393 // Determine the set of using directives available during
2394 // unqualified name lookup.
2395 Scope *Initial = S;
2396 UnqualUsingDirectiveSet UDirs;
2397 if (getLangOptions().CPlusPlus) {
2398 // Find the first namespace or translation-unit scope.
2399 while (S && !isNamespaceOrTranslationUnitScope(S))
2400 S = S->getParent();
2401
2402 UDirs.visitScopeChain(Initial, S);
2403 }
2404 UDirs.done();
2405
2406 // Look for visible declarations.
2407 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2408 VisibleDeclsRecord Visited;
2409 ShadowContextRAII Shadow(Visited);
2410 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2411}
2412
2413void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2414 VisibleDeclConsumer &Consumer) {
2415 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2416 VisibleDeclsRecord Visited;
2417 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002418 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2419 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002420}
2421
2422//----------------------------------------------------------------------------
2423// Typo correction
2424//----------------------------------------------------------------------------
2425
2426namespace {
2427class TypoCorrectionConsumer : public VisibleDeclConsumer {
2428 /// \brief The name written that is a typo in the source.
2429 llvm::StringRef Typo;
2430
2431 /// \brief The results found that have the smallest edit distance
2432 /// found (so far) with the typo name.
2433 llvm::SmallVector<NamedDecl *, 4> BestResults;
2434
Douglas Gregoraaf87162010-04-14 20:04:41 +00002435 /// \brief The keywords that have the smallest edit distance.
2436 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2437
Douglas Gregor546be3c2009-12-30 17:04:44 +00002438 /// \brief The best edit distance found so far.
2439 unsigned BestEditDistance;
2440
2441public:
2442 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2443 : Typo(Typo->getName()) { }
2444
Douglas Gregor0cc84042010-01-14 15:47:35 +00002445 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002446 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002447
2448 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2449 iterator begin() const { return BestResults.begin(); }
2450 iterator end() const { return BestResults.end(); }
Douglas Gregoraaf87162010-04-14 20:04:41 +00002451 void clear_decls() { BestResults.clear(); }
2452
2453 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002454
Douglas Gregoraaf87162010-04-14 20:04:41 +00002455 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2456 keyword_iterator;
2457 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2458 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2459 bool keyword_empty() const { return BestKeywords.empty(); }
2460 unsigned keyword_size() const { return BestKeywords.size(); }
2461
2462 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002463};
2464
2465}
2466
Douglas Gregor0cc84042010-01-14 15:47:35 +00002467void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2468 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002469 // Don't consider hidden names for typo correction.
2470 if (Hiding)
2471 return;
2472
2473 // Only consider entities with identifiers for names, ignoring
2474 // special names (constructors, overloaded operators, selectors,
2475 // etc.).
2476 IdentifierInfo *Name = ND->getIdentifier();
2477 if (!Name)
2478 return;
2479
2480 // Compute the edit distance between the typo and the name of this
2481 // entity. If this edit distance is not worse than the best edit
2482 // distance we've seen so far, add it to the list of results.
2483 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregoraaf87162010-04-14 20:04:41 +00002484 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002485 if (ED < BestEditDistance) {
2486 // This result is better than any we've seen before; clear out
2487 // the previous results.
2488 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002489 BestKeywords.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002490 BestEditDistance = ED;
2491 } else if (ED > BestEditDistance) {
2492 // This result is worse than the best results we've seen so far;
2493 // ignore it.
2494 return;
2495 }
2496 } else
2497 BestEditDistance = ED;
2498
2499 BestResults.push_back(ND);
2500}
2501
Douglas Gregoraaf87162010-04-14 20:04:41 +00002502void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2503 llvm::StringRef Keyword) {
2504 // Compute the edit distance between the typo and this keyword.
2505 // If this edit distance is not worse than the best edit
2506 // distance we've seen so far, add it to the list of results.
2507 unsigned ED = Typo.edit_distance(Keyword);
2508 if (!BestResults.empty() || !BestKeywords.empty()) {
2509 if (ED < BestEditDistance) {
2510 BestResults.clear();
2511 BestKeywords.clear();
2512 BestEditDistance = ED;
2513 } else if (ED > BestEditDistance) {
2514 // This result is worse than the best results we've seen so far;
2515 // ignore it.
2516 return;
2517 }
2518 } else
2519 BestEditDistance = ED;
2520
2521 BestKeywords.push_back(&Context.Idents.get(Keyword));
2522}
2523
Douglas Gregor546be3c2009-12-30 17:04:44 +00002524/// \brief Try to "correct" a typo in the source code by finding
2525/// visible declarations whose names are similar to the name that was
2526/// present in the source code.
2527///
2528/// \param Res the \c LookupResult structure that contains the name
2529/// that was present in the source code along with the name-lookup
2530/// criteria used to search for the name. On success, this structure
2531/// will contain the results of name lookup.
2532///
2533/// \param S the scope in which name lookup occurs.
2534///
2535/// \param SS the nested-name-specifier that precedes the name we're
2536/// looking for, if present.
2537///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002538/// \param MemberContext if non-NULL, the context in which to look for
2539/// a member access expression.
2540///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002541/// \param EnteringContext whether we're entering the context described by
2542/// the nested-name-specifier SS.
2543///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002544/// \param CTC The context in which typo correction occurs, which impacts the
2545/// set of keywords permitted.
2546///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002547/// \param OPT when non-NULL, the search for visible declarations will
2548/// also walk the protocols in the qualified interfaces of \p OPT.
2549///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002550/// \returns the corrected name if the typo was corrected, otherwise returns an
2551/// empty \c DeclarationName. When a typo was corrected, the result structure
2552/// may contain the results of name lookup for the correct name or it may be
2553/// empty.
2554DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002555 DeclContext *MemberContext,
2556 bool EnteringContext,
2557 CorrectTypoContext CTC,
2558 const ObjCObjectPointerType *OPT) {
Ted Kremenek1dac3412010-01-06 00:23:04 +00002559 if (Diags.hasFatalErrorOccurred())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002560 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002561
2562 // Provide a stop gap for files that are just seriously broken. Trying
2563 // to correct all typos can turn into a HUGE performance penalty, causing
2564 // some files to take minutes to get rejected by the parser.
2565 // FIXME: Is this the right solution?
2566 if (TyposCorrected == 20)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002567 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002568 ++TyposCorrected;
Ted Kremenek1dac3412010-01-06 00:23:04 +00002569
Douglas Gregor546be3c2009-12-30 17:04:44 +00002570 // We only attempt to correct typos for identifiers.
2571 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2572 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002573 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002574
2575 // If the scope specifier itself was invalid, don't try to correct
2576 // typos.
2577 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002578 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002579
2580 // Never try to correct typos during template deduction or
2581 // instantiation.
2582 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002583 return DeclarationName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002584
Douglas Gregor546be3c2009-12-30 17:04:44 +00002585 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002586
2587 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002588 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002589 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002590
2591 // Look in qualified interfaces.
2592 if (OPT) {
2593 for (ObjCObjectPointerType::qual_iterator
2594 I = OPT->qual_begin(), E = OPT->qual_end();
2595 I != E; ++I)
2596 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2597 }
2598 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002599 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2600 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002601 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002602
2603 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2604 } else {
2605 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2606 }
2607
Douglas Gregoraaf87162010-04-14 20:04:41 +00002608 // Add context-dependent keywords.
2609 bool WantTypeSpecifiers = false;
2610 bool WantExpressionKeywords = false;
2611 bool WantCXXNamedCasts = false;
2612 bool WantRemainingKeywords = false;
2613 switch (CTC) {
2614 case CTC_Unknown:
2615 WantTypeSpecifiers = true;
2616 WantExpressionKeywords = true;
2617 WantCXXNamedCasts = true;
2618 WantRemainingKeywords = true;
Douglas Gregor91f7ac72010-05-18 16:14:23 +00002619
2620 if (ObjCMethodDecl *Method = getCurMethodDecl())
2621 if (Method->getClassInterface() &&
2622 Method->getClassInterface()->getSuperClass())
2623 Consumer.addKeywordResult(Context, "super");
2624
Douglas Gregoraaf87162010-04-14 20:04:41 +00002625 break;
2626
2627 case CTC_NoKeywords:
2628 break;
2629
2630 case CTC_Type:
2631 WantTypeSpecifiers = true;
2632 break;
2633
2634 case CTC_ObjCMessageReceiver:
2635 Consumer.addKeywordResult(Context, "super");
2636 // Fall through to handle message receivers like expressions.
2637
2638 case CTC_Expression:
2639 if (getLangOptions().CPlusPlus)
2640 WantTypeSpecifiers = true;
2641 WantExpressionKeywords = true;
2642 // Fall through to get C++ named casts.
2643
2644 case CTC_CXXCasts:
2645 WantCXXNamedCasts = true;
2646 break;
2647
2648 case CTC_MemberLookup:
2649 if (getLangOptions().CPlusPlus)
2650 Consumer.addKeywordResult(Context, "template");
2651 break;
2652 }
2653
2654 if (WantTypeSpecifiers) {
2655 // Add type-specifier keywords to the set of results.
2656 const char *CTypeSpecs[] = {
2657 "char", "const", "double", "enum", "float", "int", "long", "short",
2658 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2659 "_Complex", "_Imaginary",
2660 // storage-specifiers as well
2661 "extern", "inline", "static", "typedef"
2662 };
2663
2664 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2665 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2666 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2667
2668 if (getLangOptions().C99)
2669 Consumer.addKeywordResult(Context, "restrict");
2670 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2671 Consumer.addKeywordResult(Context, "bool");
2672
2673 if (getLangOptions().CPlusPlus) {
2674 Consumer.addKeywordResult(Context, "class");
2675 Consumer.addKeywordResult(Context, "typename");
2676 Consumer.addKeywordResult(Context, "wchar_t");
2677
2678 if (getLangOptions().CPlusPlus0x) {
2679 Consumer.addKeywordResult(Context, "char16_t");
2680 Consumer.addKeywordResult(Context, "char32_t");
2681 Consumer.addKeywordResult(Context, "constexpr");
2682 Consumer.addKeywordResult(Context, "decltype");
2683 Consumer.addKeywordResult(Context, "thread_local");
2684 }
2685 }
2686
2687 if (getLangOptions().GNUMode)
2688 Consumer.addKeywordResult(Context, "typeof");
2689 }
2690
Douglas Gregord0785ea2010-05-18 16:30:22 +00002691 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00002692 Consumer.addKeywordResult(Context, "const_cast");
2693 Consumer.addKeywordResult(Context, "dynamic_cast");
2694 Consumer.addKeywordResult(Context, "reinterpret_cast");
2695 Consumer.addKeywordResult(Context, "static_cast");
2696 }
2697
2698 if (WantExpressionKeywords) {
2699 Consumer.addKeywordResult(Context, "sizeof");
2700 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2701 Consumer.addKeywordResult(Context, "false");
2702 Consumer.addKeywordResult(Context, "true");
2703 }
2704
2705 if (getLangOptions().CPlusPlus) {
2706 const char *CXXExprs[] = {
2707 "delete", "new", "operator", "throw", "typeid"
2708 };
2709 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2710 for (unsigned I = 0; I != NumCXXExprs; ++I)
2711 Consumer.addKeywordResult(Context, CXXExprs[I]);
2712
2713 if (isa<CXXMethodDecl>(CurContext) &&
2714 cast<CXXMethodDecl>(CurContext)->isInstance())
2715 Consumer.addKeywordResult(Context, "this");
2716
2717 if (getLangOptions().CPlusPlus0x) {
2718 Consumer.addKeywordResult(Context, "alignof");
2719 Consumer.addKeywordResult(Context, "nullptr");
2720 }
2721 }
2722 }
2723
2724 if (WantRemainingKeywords) {
2725 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2726 // Statements.
2727 const char *CStmts[] = {
2728 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2729 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2730 for (unsigned I = 0; I != NumCStmts; ++I)
2731 Consumer.addKeywordResult(Context, CStmts[I]);
2732
2733 if (getLangOptions().CPlusPlus) {
2734 Consumer.addKeywordResult(Context, "catch");
2735 Consumer.addKeywordResult(Context, "try");
2736 }
2737
2738 if (S && S->getBreakParent())
2739 Consumer.addKeywordResult(Context, "break");
2740
2741 if (S && S->getContinueParent())
2742 Consumer.addKeywordResult(Context, "continue");
2743
2744 if (!getSwitchStack().empty()) {
2745 Consumer.addKeywordResult(Context, "case");
2746 Consumer.addKeywordResult(Context, "default");
2747 }
2748 } else {
2749 if (getLangOptions().CPlusPlus) {
2750 Consumer.addKeywordResult(Context, "namespace");
2751 Consumer.addKeywordResult(Context, "template");
2752 }
2753
2754 if (S && S->isClassScope()) {
2755 Consumer.addKeywordResult(Context, "explicit");
2756 Consumer.addKeywordResult(Context, "friend");
2757 Consumer.addKeywordResult(Context, "mutable");
2758 Consumer.addKeywordResult(Context, "private");
2759 Consumer.addKeywordResult(Context, "protected");
2760 Consumer.addKeywordResult(Context, "public");
2761 Consumer.addKeywordResult(Context, "virtual");
2762 }
2763 }
2764
2765 if (getLangOptions().CPlusPlus) {
2766 Consumer.addKeywordResult(Context, "using");
2767
2768 if (getLangOptions().CPlusPlus0x)
2769 Consumer.addKeywordResult(Context, "static_assert");
2770 }
2771 }
2772
2773 // If we haven't found anything, we're done.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002774 if (Consumer.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002775 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002776
2777 // Only allow a single, closest name in the result set (it's okay to
2778 // have overloads of that name, though).
Douglas Gregoraaf87162010-04-14 20:04:41 +00002779 DeclarationName BestName;
2780 NamedDecl *BestIvarOrPropertyDecl = 0;
2781 bool FoundIvarOrPropertyDecl = false;
2782
2783 // Check all of the declaration results to find the best name so far.
2784 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2785 IEnd = Consumer.end();
2786 I != IEnd; ++I) {
2787 if (!BestName)
2788 BestName = (*I)->getDeclName();
2789 else if (BestName != (*I)->getDeclName())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002790 return DeclarationName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002791
Douglas Gregoraaf87162010-04-14 20:04:41 +00002792 // \brief Keep track of either an Objective-C ivar or a property, but not
2793 // both.
2794 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
2795 if (FoundIvarOrPropertyDecl)
2796 BestIvarOrPropertyDecl = 0;
2797 else {
2798 BestIvarOrPropertyDecl = *I;
2799 FoundIvarOrPropertyDecl = true;
2800 }
2801 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002802 }
2803
Douglas Gregoraaf87162010-04-14 20:04:41 +00002804 // Now check all of the keyword results to find the best name.
2805 switch (Consumer.keyword_size()) {
2806 case 0:
2807 // No keywords matched.
2808 break;
2809
2810 case 1:
2811 // If we already have a name
2812 if (!BestName) {
2813 // We did not have anything previously,
2814 BestName = *Consumer.keyword_begin();
2815 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
2816 // We have a declaration with the same name as a context-sensitive
2817 // keyword. The keyword takes precedence.
2818 BestIvarOrPropertyDecl = 0;
2819 FoundIvarOrPropertyDecl = false;
2820 Consumer.clear_decls();
Douglas Gregord0785ea2010-05-18 16:30:22 +00002821 } else if (CTC == CTC_ObjCMessageReceiver &&
2822 (*Consumer.keyword_begin())->isStr("super")) {
2823 // In an Objective-C message send, give the "super" keyword a slight
2824 // edge over entities not in function or method scope.
2825 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2826 IEnd = Consumer.end();
2827 I != IEnd; ++I) {
2828 if ((*I)->getDeclName() == BestName) {
2829 if ((*I)->getDeclContext()->isFunctionOrMethod())
2830 return DeclarationName();
2831 }
2832 }
2833
2834 // Everything found was outside a function or method; the 'super'
2835 // keyword takes precedence.
2836 BestIvarOrPropertyDecl = 0;
2837 FoundIvarOrPropertyDecl = false;
2838 Consumer.clear_decls();
2839 BestName = *Consumer.keyword_begin();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002840 } else {
2841 // Name collision; we will not correct typos.
2842 return DeclarationName();
2843 }
2844 break;
2845
2846 default:
2847 // Name collision; we will not correct typos.
2848 return DeclarationName();
2849 }
2850
Douglas Gregor546be3c2009-12-30 17:04:44 +00002851 // BestName is the closest viable name to what the user
2852 // typed. However, to make sure that we don't pick something that's
2853 // way off, make sure that the user typed at least 3 characters for
2854 // each correction.
2855 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002856 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
2857 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002858 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002859
2860 // Perform name lookup again with the name we chose, and declare
2861 // success if we found something that was not ambiguous.
2862 Res.clear();
2863 Res.setLookupName(BestName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002864
2865 // If we found an ivar or property, add that result; no further
2866 // lookup is required.
Douglas Gregoraaf87162010-04-14 20:04:41 +00002867 if (BestIvarOrPropertyDecl)
2868 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002869 // If we're looking into the context of a member, perform qualified
2870 // name lookup on the best name.
Douglas Gregoraaf87162010-04-14 20:04:41 +00002871 else if (!Consumer.keyword_empty()) {
2872 // The best match was a keyword. Return it.
2873 return BestName;
2874 } else if (MemberContext)
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002875 LookupQualifiedName(Res, MemberContext);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002876 // Perform lookup as if we had just parsed the best name.
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002877 else
2878 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2879 EnteringContext);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002880
2881 if (Res.isAmbiguous()) {
2882 Res.suppressDiagnostics();
Douglas Gregor931f98a2010-04-14 17:09:22 +00002883 return DeclarationName();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002884 }
2885
Douglas Gregor931f98a2010-04-14 17:09:22 +00002886 if (Res.getResultKind() != LookupResult::NotFound)
2887 return BestName;
2888
2889 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002890}