blob: 0609eef3c9eaaafb9d6b5339279bbacbf6bfdf26 [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 McCallf88b0d62010-04-23 21:37:18 +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) {
John McCalleec51cf2010-01-20 00:46:10 +0000302 if (isa<FunctionTemplateDecl>(*Decls.begin()))
John McCall7453ed42009-11-22 00:44:51 +0000303 ResultKind = FoundOverloaded;
John McCalleec51cf2010-01-20 00:46:10 +0000304 else if (isa<UnresolvedUsingValueDecl>(*Decls.begin()))
John McCall7ba107a2009-11-18 02:36:19 +0000305 ResultKind = FoundUnresolvedValue;
306 return;
307 }
John McCallf36e02d2009-10-09 21:13:30 +0000308
John McCall6e247262009-10-10 05:48:19 +0000309 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000310 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000311
John McCallf36e02d2009-10-09 21:13:30 +0000312 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
313
314 bool Ambiguous = false;
315 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000316 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000317
318 unsigned UniqueTagIndex = 0;
319
320 unsigned I = 0;
321 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000322 NamedDecl *D = Decls[I]->getUnderlyingDecl();
323 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000324
John McCall314be4e2009-11-17 07:50:12 +0000325 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000326 // If it's not unique, pull something off the back (and
327 // continue at this index).
328 Decls[I] = Decls[--N];
John McCallf36e02d2009-10-09 21:13:30 +0000329 } else {
330 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000331
332 if (isa<UnresolvedUsingValueDecl>(D)) {
333 HasUnresolved = true;
334 } else if (isa<TagDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000335 if (HasTag)
336 Ambiguous = true;
337 UniqueTagIndex = I;
338 HasTag = true;
John McCall7453ed42009-11-22 00:44:51 +0000339 } else if (isa<FunctionTemplateDecl>(D)) {
340 HasFunction = true;
341 HasFunctionTemplate = true;
342 } else if (isa<FunctionDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000343 HasFunction = true;
344 } else {
345 if (HasNonFunction)
346 Ambiguous = true;
347 HasNonFunction = true;
348 }
349 I++;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000350 }
Mike Stump1eb44332009-09-09 15:08:12 +0000351 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000352
John McCallf36e02d2009-10-09 21:13:30 +0000353 // C++ [basic.scope.hiding]p2:
354 // A class name or enumeration name can be hidden by the name of
355 // an object, function, or enumerator declared in the same
356 // scope. If a class or enumeration name and an object, function,
357 // or enumerator are declared in the same scope (in any order)
358 // with the same name, the class or enumeration name is hidden
359 // wherever the object, function, or enumerator name is visible.
360 // But it's still an error if there are distinct tag types found,
361 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000362 if (HideTags && HasTag && !Ambiguous &&
363 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000364 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000365
John McCallf36e02d2009-10-09 21:13:30 +0000366 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000367
John McCallfda8e122009-12-03 00:58:24 +0000368 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000369 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000370
John McCallf36e02d2009-10-09 21:13:30 +0000371 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000372 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000373 else if (HasUnresolved)
374 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000375 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000376 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000377 else
John McCalla24dc2e2009-11-17 02:14:36 +0000378 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000379}
380
John McCall7d384dd2009-11-18 07:57:50 +0000381void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000382 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000383 DeclContext::lookup_iterator DI, DE;
384 for (I = P.begin(), E = P.end(); I != E; ++I)
385 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
386 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000387}
388
John McCall7d384dd2009-11-18 07:57:50 +0000389void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000390 Paths = new CXXBasePaths;
391 Paths->swap(P);
392 addDeclsFromBasePaths(*Paths);
393 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000394 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000395}
396
John McCall7d384dd2009-11-18 07:57:50 +0000397void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000398 Paths = new CXXBasePaths;
399 Paths->swap(P);
400 addDeclsFromBasePaths(*Paths);
401 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000402 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000403}
404
John McCall7d384dd2009-11-18 07:57:50 +0000405void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000406 Out << Decls.size() << " result(s)";
407 if (isAmbiguous()) Out << ", ambiguous";
408 if (Paths) Out << ", base paths present";
409
410 for (iterator I = begin(), E = end(); I != E; ++I) {
411 Out << "\n";
412 (*I)->print(Out, 2);
413 }
414}
415
Douglas Gregor85910982010-02-12 05:48:04 +0000416/// \brief Lookup a builtin function, when name lookup would otherwise
417/// fail.
418static bool LookupBuiltin(Sema &S, LookupResult &R) {
419 Sema::LookupNameKind NameKind = R.getLookupKind();
420
421 // If we didn't find a use of this identifier, and if the identifier
422 // corresponds to a compiler builtin, create the decl object for the builtin
423 // now, injecting it into translation unit scope, and return it.
424 if (NameKind == Sema::LookupOrdinaryName ||
425 NameKind == Sema::LookupRedeclarationWithLinkage) {
426 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
427 if (II) {
428 // If this is a builtin on this (or all) targets, create the decl.
429 if (unsigned BuiltinID = II->getBuiltinID()) {
430 // In C++, we don't have any predefined library functions like
431 // 'malloc'. Instead, we'll just error.
432 if (S.getLangOptions().CPlusPlus &&
433 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
434 return false;
435
436 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
437 S.TUScope, R.isForRedeclaration(),
438 R.getNameLoc());
439 if (D)
440 R.addDecl(D);
441 return (D != NULL);
442 }
443 }
444 }
445
446 return false;
447}
448
John McCallf36e02d2009-10-09 21:13:30 +0000449// Adds all qualifying matches for a name within a decl context to the
450// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000451static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000452 bool Found = false;
453
John McCalld7be78a2009-11-10 07:01:13 +0000454 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000455 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000456 NamedDecl *D = *I;
457 if (R.isAcceptableDecl(D)) {
458 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000459 Found = true;
460 }
461 }
John McCallf36e02d2009-10-09 21:13:30 +0000462
Douglas Gregor85910982010-02-12 05:48:04 +0000463 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
464 return true;
465
Douglas Gregor48026d22010-01-11 18:40:55 +0000466 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000467 != DeclarationName::CXXConversionFunctionName ||
468 R.getLookupName().getCXXNameType()->isDependentType() ||
469 !isa<CXXRecordDecl>(DC))
470 return Found;
471
472 // C++ [temp.mem]p6:
473 // A specialization of a conversion function template is not found by
474 // name lookup. Instead, any conversion function templates visible in the
475 // context of the use are considered. [...]
476 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
477 if (!Record->isDefinition())
478 return Found;
479
480 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
481 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
482 UEnd = Unresolved->end(); U != UEnd; ++U) {
483 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
484 if (!ConvTemplate)
485 continue;
486
487 // When we're performing lookup for the purposes of redeclaration, just
488 // add the conversion function template. When we deduce template
489 // arguments for specializations, we'll end up unifying the return
490 // type of the new declaration with the type of the function template.
491 if (R.isForRedeclaration()) {
492 R.addDecl(ConvTemplate);
493 Found = true;
494 continue;
495 }
496
Douglas Gregor48026d22010-01-11 18:40:55 +0000497 // C++ [temp.mem]p6:
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000498 // [...] For each such operator, if argument deduction succeeds
499 // (14.9.2.3), the resulting specialization is used as if found by
500 // name lookup.
501 //
502 // When referencing a conversion function for any purpose other than
503 // a redeclaration (such that we'll be building an expression with the
504 // result), perform template argument deduction and place the
505 // specialization into the result set. We do this to avoid forcing all
506 // callers to perform special deduction for conversion functions.
John McCall5769d612010-02-08 23:07:23 +0000507 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000508 FunctionDecl *Specialization = 0;
509
510 const FunctionProtoType *ConvProto
511 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
512 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000513
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000514 // Compute the type of the function that we would expect the conversion
515 // function to have, if it were to match the name given.
516 // FIXME: Calling convention!
Rafael Espindola264ba482010-03-30 20:24:48 +0000517 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000518 QualType ExpectedType
519 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
520 0, 0, ConvProto->isVariadic(),
521 ConvProto->getTypeQuals(),
522 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000523 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000524
525 // Perform template argument deduction against the type that we would
526 // expect the function to have.
527 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
528 Specialization, Info)
529 == Sema::TDK_Success) {
530 R.addDecl(Specialization);
531 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000532 }
533 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000534
John McCallf36e02d2009-10-09 21:13:30 +0000535 return Found;
536}
537
John McCalld7be78a2009-11-10 07:01:13 +0000538// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000539static bool
Douglas Gregor85910982010-02-12 05:48:04 +0000540CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
541 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000542
543 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
544
John McCalld7be78a2009-11-10 07:01:13 +0000545 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000546 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000547
John McCalld7be78a2009-11-10 07:01:13 +0000548 // Perform direct name lookup into the namespaces nominated by the
549 // using directives whose common ancestor is this namespace.
550 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
551 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000552
John McCalld7be78a2009-11-10 07:01:13 +0000553 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000554 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000555 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000556
557 R.resolveKind();
558
559 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000560}
561
562static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000563 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000564 return Ctx->isFileContext();
565 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000566}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000567
Douglas Gregor711be1e2010-03-15 14:33:29 +0000568// Find the next outer declaration context from this scope. This
569// routine actually returns the semantic outer context, which may
570// differ from the lexical context (encoded directly in the Scope
571// stack) when we are parsing a member of a class template. In this
572// case, the second element of the pair will be true, to indicate that
573// name lookup should continue searching in this semantic context when
574// it leaves the current template parameter scope.
575static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
576 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
577 DeclContext *Lexical = 0;
578 for (Scope *OuterS = S->getParent(); OuterS;
579 OuterS = OuterS->getParent()) {
580 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000581 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000582 break;
583 }
584 }
585
586 // C++ [temp.local]p8:
587 // In the definition of a member of a class template that appears
588 // outside of the namespace containing the class template
589 // definition, the name of a template-parameter hides the name of
590 // a member of this namespace.
591 //
592 // Example:
593 //
594 // namespace N {
595 // class C { };
596 //
597 // template<class T> class B {
598 // void f(T);
599 // };
600 // }
601 //
602 // template<class C> void N::B<C>::f(C) {
603 // C b; // C is the template parameter, not N::C
604 // }
605 //
606 // In this example, the lexical context we return is the
607 // TranslationUnit, while the semantic context is the namespace N.
608 if (!Lexical || !DC || !S->getParent() ||
609 !S->getParent()->isTemplateParamScope())
610 return std::make_pair(Lexical, false);
611
612 // Find the outermost template parameter scope.
613 // For the example, this is the scope for the template parameters of
614 // template<class C>.
615 Scope *OutermostTemplateScope = S->getParent();
616 while (OutermostTemplateScope->getParent() &&
617 OutermostTemplateScope->getParent()->isTemplateParamScope())
618 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregore942bbe2009-09-10 16:57:35 +0000619
Douglas Gregor711be1e2010-03-15 14:33:29 +0000620 // Find the namespace context in which the original scope occurs. In
621 // the example, this is namespace N.
622 DeclContext *Semantic = DC;
623 while (!Semantic->isFileContext())
624 Semantic = Semantic->getParent();
625
626 // Find the declaration context just outside of the template
627 // parameter scope. This is the context in which the template is
628 // being lexically declaration (a namespace context). In the
629 // example, this is the global scope.
630 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
631 Lexical->Encloses(Semantic))
632 return std::make_pair(Semantic, true);
633
634 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000635}
636
John McCalla24dc2e2009-11-17 02:14:36 +0000637bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000638 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000639
640 DeclarationName Name = R.getLookupName();
641
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000642 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000643 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000644 I = IdResolver.begin(Name),
645 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000646
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000647 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000648 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000649 // ...During unqualified name lookup (3.4.1), the names appear as if
650 // they were declared in the nearest enclosing namespace which contains
651 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000652 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000653 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000654 //
655 // For example:
656 // namespace A { int i; }
657 // void foo() {
658 // int i;
659 // {
660 // using namespace A;
661 // ++i; // finds local 'i', A::i appears at global scope
662 // }
663 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000664 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000665 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000666 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000667 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000668 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000669 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000670 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000671 Found = true;
672 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000673 }
674 }
John McCallf36e02d2009-10-09 21:13:30 +0000675 if (Found) {
676 R.resolveKind();
677 return true;
678 }
679
Douglas Gregor711be1e2010-03-15 14:33:29 +0000680 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
681 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
682 S->getParent() && !S->getParent()->isTemplateParamScope()) {
683 // We've just searched the last template parameter scope and
684 // found nothing, so look into the the contexts between the
685 // lexical and semantic declaration contexts returned by
686 // findOuterContext(). This implements the name lookup behavior
687 // of C++ [temp.local]p8.
688 Ctx = OutsideOfTemplateParamDC;
689 OutsideOfTemplateParamDC = 0;
690 }
691
692 if (Ctx) {
693 DeclContext *OuterCtx;
694 bool SearchAfterTemplateScope;
695 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
696 if (SearchAfterTemplateScope)
697 OutsideOfTemplateParamDC = OuterCtx;
698
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000699 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000700 // We do not directly look into transparent contexts, since
701 // those entities will be found in the nearest enclosing
702 // non-transparent context.
703 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000704 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000705
706 // We do not look directly into function or method contexts,
707 // since all of the local variables and parameters of the
708 // function/method are present within the Scope.
709 if (Ctx->isFunctionOrMethod()) {
710 // If we have an Objective-C instance method, look for ivars
711 // in the corresponding interface.
712 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
713 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
714 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
715 ObjCInterfaceDecl *ClassDeclared;
716 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
717 Name.getAsIdentifierInfo(),
718 ClassDeclared)) {
719 if (R.isAcceptableDecl(Ivar)) {
720 R.addDecl(Ivar);
721 R.resolveKind();
722 return true;
723 }
724 }
725 }
726 }
727
728 continue;
729 }
730
Douglas Gregore942bbe2009-09-10 16:57:35 +0000731 // Perform qualified name lookup into this context.
732 // FIXME: In some cases, we know that every name that could be found by
733 // this qualified name lookup will also be on the identifier chain. For
734 // example, inside a class without any base classes, we never need to
735 // perform qualified lookup because all of the members are on top of the
736 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000737 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000738 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000739 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000740 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000741 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000742
John McCalld7be78a2009-11-10 07:01:13 +0000743 // Stop if we ran out of scopes.
744 // FIXME: This really, really shouldn't be happening.
745 if (!S) return false;
746
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000747 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000748 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000749 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000750 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
751 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000752
John McCalld7be78a2009-11-10 07:01:13 +0000753 UnqualUsingDirectiveSet UDirs;
754 UDirs.visitScopeChain(Initial, S);
755 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000756
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000757 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000758 // Unqualified name lookup in C++ requires looking into scopes
759 // that aren't strictly lexical, and therefore we walk through the
760 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000761
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000762 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000763 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000764 if (Ctx && Ctx->isTransparentContext())
Douglas Gregora24eb4e2009-08-24 18:55:03 +0000765 continue;
766
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000767 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000768 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000769 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000770 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000771 // We found something. Look for anything else in our scope
772 // with this same name and in an acceptable identifier
773 // namespace, so that we can construct an overload set if we
774 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000775 Found = true;
776 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000777 }
778 }
779
Douglas Gregor711be1e2010-03-15 14:33:29 +0000780 // If we have a context, and it's not a context stashed in the
781 // template parameter scope for an out-of-line definition, also
782 // look into that context.
783 if (Ctx && !(Found && S && S->isTemplateParamScope())) {
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000784 assert(Ctx->isFileContext() &&
785 "We should have been looking only at file context here already.");
786
787 // Look into context considering using-directives.
Douglas Gregor85910982010-02-12 05:48:04 +0000788 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000789 Found = true;
790 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000791
John McCallf36e02d2009-10-09 21:13:30 +0000792 if (Found) {
793 R.resolveKind();
794 return true;
795 }
796
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000797 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000798 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000799 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000800
John McCallf36e02d2009-10-09 21:13:30 +0000801 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000802}
803
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000804/// @brief Perform unqualified name lookup starting from a given
805/// scope.
806///
807/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
808/// used to find names within the current scope. For example, 'x' in
809/// @code
810/// int x;
811/// int f() {
812/// return x; // unqualified name look finds 'x' in the global scope
813/// }
814/// @endcode
815///
816/// Different lookup criteria can find different names. For example, a
817/// particular scope can have both a struct and a function of the same
818/// name, and each can be found by certain lookup criteria. For more
819/// information about lookup criteria, see the documentation for the
820/// class LookupCriteria.
821///
822/// @param S The scope from which unqualified name lookup will
823/// begin. If the lookup criteria permits, name lookup may also search
824/// in the parent scopes.
825///
826/// @param Name The name of the entity that we are searching for.
827///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000828/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +0000829/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +0000830/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000831///
832/// @returns The result of name lookup, which includes zero or more
833/// declarations and possibly additional information used to diagnose
834/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000835bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
836 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +0000837 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000838
John McCalla24dc2e2009-11-17 02:14:36 +0000839 LookupNameKind NameKind = R.getLookupKind();
840
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000841 if (!getLangOptions().CPlusPlus) {
842 // Unqualified name lookup in C/Objective-C is purely lexical, so
843 // search in the declarations attached to the name.
844
John McCall1d7c5282009-12-18 10:40:03 +0000845 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000846 // Find the nearest non-transparent declaration scope.
847 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000848 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000849 static_cast<DeclContext *>(S->getEntity())
850 ->isTransparentContext()))
851 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000852 }
853
John McCall1d7c5282009-12-18 10:40:03 +0000854 unsigned IDNS = R.getIdentifierNamespace();
855
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000856 // Scan up the scope chain looking for a decl that matches this
857 // identifier that is in the appropriate namespace. This search
858 // should not take long, as shadowing of names is uncommon, and
859 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000860 bool LeftStartingScope = false;
861
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000862 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +0000863 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000864 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000865 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000866 if (NameKind == LookupRedeclarationWithLinkage) {
867 // Determine whether this (or a previous) declaration is
868 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000869 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000870 LeftStartingScope = true;
871
872 // If we found something outside of our starting scope that
873 // does not have linkage, skip it.
874 if (LeftStartingScope && !((*I)->hasLinkage()))
875 continue;
876 }
877
John McCallf36e02d2009-10-09 21:13:30 +0000878 R.addDecl(*I);
879
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000880 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000881 // If this declaration has the "overloadable" attribute, we
882 // might have a set of overloaded functions.
883
884 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000885 while (!(S->getFlags() & Scope::DeclScope) ||
886 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000887 S = S->getParent();
888
889 // Find the last declaration in this scope (with the same
890 // name, naturally).
891 IdentifierResolver::iterator LastI = I;
892 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000893 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000894 break;
John McCallf36e02d2009-10-09 21:13:30 +0000895 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000896 }
Douglas Gregorf9201e02009-02-11 23:02:49 +0000897 }
898
John McCallf36e02d2009-10-09 21:13:30 +0000899 R.resolveKind();
900
901 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000902 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000903 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000904 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000905 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +0000906 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000907 }
908
909 // If we didn't find a use of this identifier, and if the identifier
910 // corresponds to a compiler builtin, create the decl object for the builtin
911 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +0000912 if (AllowBuiltinCreation)
913 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000914
John McCallf36e02d2009-10-09 21:13:30 +0000915 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000916}
917
John McCall6e247262009-10-10 05:48:19 +0000918/// @brief Perform qualified name lookup in the namespaces nominated by
919/// using directives by the given context.
920///
921/// C++98 [namespace.qual]p2:
922/// Given X::m (where X is a user-declared namespace), or given ::m
923/// (where X is the global namespace), let S be the set of all
924/// declarations of m in X and in the transitive closure of all
925/// namespaces nominated by using-directives in X and its used
926/// namespaces, except that using-directives are ignored in any
927/// namespace, including X, directly containing one or more
928/// declarations of m. No namespace is searched more than once in
929/// the lookup of a name. If S is the empty set, the program is
930/// ill-formed. Otherwise, if S has exactly one member, or if the
931/// context of the reference is a using-declaration
932/// (namespace.udecl), S is the required set of declarations of
933/// m. Otherwise if the use of m is not one that allows a unique
934/// declaration to be chosen from S, the program is ill-formed.
935/// C++98 [namespace.qual]p5:
936/// During the lookup of a qualified namespace member name, if the
937/// lookup finds more than one declaration of the member, and if one
938/// declaration introduces a class name or enumeration name and the
939/// other declarations either introduce the same object, the same
940/// enumerator or a set of functions, the non-type name hides the
941/// class or enumeration name if and only if the declarations are
942/// from the same namespace; otherwise (the declarations are from
943/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +0000944static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +0000945 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +0000946 assert(StartDC->isFileContext() && "start context is not a file context");
947
948 DeclContext::udir_iterator I = StartDC->using_directives_begin();
949 DeclContext::udir_iterator E = StartDC->using_directives_end();
950
951 if (I == E) return false;
952
953 // We have at least added all these contexts to the queue.
954 llvm::DenseSet<DeclContext*> Visited;
955 Visited.insert(StartDC);
956
957 // We have not yet looked into these namespaces, much less added
958 // their "using-children" to the queue.
959 llvm::SmallVector<NamespaceDecl*, 8> Queue;
960
961 // We have already looked into the initial namespace; seed the queue
962 // with its using-children.
963 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +0000964 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +0000965 if (Visited.insert(ND).second)
966 Queue.push_back(ND);
967 }
968
969 // The easiest way to implement the restriction in [namespace.qual]p5
970 // is to check whether any of the individual results found a tag
971 // and, if so, to declare an ambiguity if the final result is not
972 // a tag.
973 bool FoundTag = false;
974 bool FoundNonTag = false;
975
John McCall7d384dd2009-11-18 07:57:50 +0000976 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +0000977
978 bool Found = false;
979 while (!Queue.empty()) {
980 NamespaceDecl *ND = Queue.back();
981 Queue.pop_back();
982
983 // We go through some convolutions here to avoid copying results
984 // between LookupResults.
985 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +0000986 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +0000987 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +0000988
989 if (FoundDirect) {
990 // First do any local hiding.
991 DirectR.resolveKind();
992
993 // If the local result is a tag, remember that.
994 if (DirectR.isSingleTagDecl())
995 FoundTag = true;
996 else
997 FoundNonTag = true;
998
999 // Append the local results to the total results if necessary.
1000 if (UseLocal) {
1001 R.addAllDecls(LocalR);
1002 LocalR.clear();
1003 }
1004 }
1005
1006 // If we find names in this namespace, ignore its using directives.
1007 if (FoundDirect) {
1008 Found = true;
1009 continue;
1010 }
1011
1012 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1013 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1014 if (Visited.insert(Nom).second)
1015 Queue.push_back(Nom);
1016 }
1017 }
1018
1019 if (Found) {
1020 if (FoundTag && FoundNonTag)
1021 R.setAmbiguousQualifiedTagHiding();
1022 else
1023 R.resolveKind();
1024 }
1025
1026 return Found;
1027}
1028
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001029/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001030///
1031/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1032/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001033/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001034///
1035/// Different lookup criteria can find different names. For example, a
1036/// particular scope can have both a struct and a function of the same
1037/// name, and each can be found by certain lookup criteria. For more
1038/// information about lookup criteria, see the documentation for the
1039/// class LookupCriteria.
1040///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001041/// \param R captures both the lookup criteria and any lookup results found.
1042///
1043/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001044/// search. If the lookup criteria permits, name lookup may also search
1045/// in the parent contexts or (for C++ classes) base classes.
1046///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001047/// \param InUnqualifiedLookup true if this is qualified name lookup that
1048/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001049///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001050/// \returns true if lookup succeeded, false if it failed.
1051bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1052 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001053 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001054
John McCalla24dc2e2009-11-17 02:14:36 +00001055 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001056 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001058 // Make sure that the declaration context is complete.
1059 assert((!isa<TagDecl>(LookupCtx) ||
1060 LookupCtx->isDependentContext() ||
1061 cast<TagDecl>(LookupCtx)->isDefinition() ||
1062 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1063 ->isBeingDefined()) &&
1064 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001066 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001067 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001068 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001069 if (isa<CXXRecordDecl>(LookupCtx))
1070 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001071 return true;
1072 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001073
John McCall6e247262009-10-10 05:48:19 +00001074 // Don't descend into implied contexts for redeclarations.
1075 // C++98 [namespace.qual]p6:
1076 // In a declaration for a namespace member in which the
1077 // declarator-id is a qualified-id, given that the qualified-id
1078 // for the namespace member has the form
1079 // nested-name-specifier unqualified-id
1080 // the unqualified-id shall name a member of the namespace
1081 // designated by the nested-name-specifier.
1082 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001083 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001084 return false;
1085
John McCalla24dc2e2009-11-17 02:14:36 +00001086 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001087 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001088 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001089
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001090 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001091 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001092 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1093 if (!LookupRec)
John McCallf36e02d2009-10-09 21:13:30 +00001094 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001095
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001096 // If we're performing qualified name lookup into a dependent class,
1097 // then we are actually looking into a current instantiation. If we have any
1098 // dependent base classes, then we either have to delay lookup until
1099 // template instantiation time (at which point all bases will be available)
1100 // or we have to fail.
1101 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1102 LookupRec->hasAnyDependentBases()) {
1103 R.setNotFoundInCurrentInstantiation();
1104 return false;
1105 }
1106
Douglas Gregor7176fff2009-01-15 00:26:24 +00001107 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001108 CXXBasePaths Paths;
1109 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001110
1111 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001112 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001113 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001114 case LookupOrdinaryName:
1115 case LookupMemberName:
1116 case LookupRedeclarationWithLinkage:
1117 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1118 break;
1119
1120 case LookupTagName:
1121 BaseCallback = &CXXRecordDecl::FindTagMember;
1122 break;
John McCall9f54ad42009-12-10 09:41:52 +00001123
1124 case LookupUsingDeclName:
1125 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001126
1127 case LookupOperatorName:
1128 case LookupNamespaceName:
1129 case LookupObjCProtocolName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001130 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001131 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001132
1133 case LookupNestedNameSpecifierName:
1134 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1135 break;
1136 }
1137
John McCalla24dc2e2009-11-17 02:14:36 +00001138 if (!LookupRec->lookupInBases(BaseCallback,
1139 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001140 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001141
John McCall92f88312010-01-23 00:46:32 +00001142 R.setNamingClass(LookupRec);
1143
Douglas Gregor7176fff2009-01-15 00:26:24 +00001144 // C++ [class.member.lookup]p2:
1145 // [...] If the resulting set of declarations are not all from
1146 // sub-objects of the same type, or the set has a nonstatic member
1147 // and includes members from distinct sub-objects, there is an
1148 // ambiguity and the program is ill-formed. Otherwise that set is
1149 // the result of the lookup.
1150 // FIXME: support using declarations!
1151 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001152 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001153 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001154 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001155 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001156 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001157
John McCall46460a62010-01-20 21:53:11 +00001158 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1159 // across all paths.
1160 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1161
Douglas Gregor7176fff2009-01-15 00:26:24 +00001162 // Determine whether we're looking at a distinct sub-object or not.
1163 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001164 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001165 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1166 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00001167 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001168 != Context.getCanonicalType(PathElement.Base->getType())) {
1169 // We found members of the given name in two subobjects of
1170 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001171 R.setAmbiguousBaseSubobjectTypes(Paths);
1172 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001173 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1174 // We have a different subobject of the same type.
1175
1176 // C++ [class.member.lookup]p5:
1177 // A static member, a nested type or an enumerator defined in
1178 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001179 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001180 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001181 if (isa<VarDecl>(FirstDecl) ||
1182 isa<TypeDecl>(FirstDecl) ||
1183 isa<EnumConstantDecl>(FirstDecl))
1184 continue;
1185
1186 if (isa<CXXMethodDecl>(FirstDecl)) {
1187 // Determine whether all of the methods are static.
1188 bool AllMethodsAreStatic = true;
1189 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1190 Func != Path->Decls.second; ++Func) {
1191 if (!isa<CXXMethodDecl>(*Func)) {
1192 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1193 break;
1194 }
1195
1196 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1197 AllMethodsAreStatic = false;
1198 break;
1199 }
1200 }
1201
1202 if (AllMethodsAreStatic)
1203 continue;
1204 }
1205
1206 // We have found a nonstatic member name in multiple, distinct
1207 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001208 R.setAmbiguousBaseSubobjects(Paths);
1209 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001210 }
1211 }
1212
1213 // Lookup in a base class succeeded; return these results.
1214
John McCallf36e02d2009-10-09 21:13:30 +00001215 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001216 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1217 NamedDecl *D = *I;
1218 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1219 D->getAccess());
1220 R.addDecl(D, AS);
1221 }
John McCallf36e02d2009-10-09 21:13:30 +00001222 R.resolveKind();
1223 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001224}
1225
1226/// @brief Performs name lookup for a name that was parsed in the
1227/// source code, and may contain a C++ scope specifier.
1228///
1229/// This routine is a convenience routine meant to be called from
1230/// contexts that receive a name and an optional C++ scope specifier
1231/// (e.g., "N::M::x"). It will then perform either qualified or
1232/// unqualified name lookup (with LookupQualifiedName or LookupName,
1233/// respectively) on the given name and return those results.
1234///
1235/// @param S The scope from which unqualified name lookup will
1236/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001237///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001238/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001239///
1240/// @param Name The name of the entity that name lookup will
1241/// search for.
1242///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001243/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001244/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001245/// C library functions (like "malloc") are implicitly declared.
1246///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001247/// @param EnteringContext Indicates whether we are going to enter the
1248/// context of the scope-specifier SS (if present).
1249///
John McCallf36e02d2009-10-09 21:13:30 +00001250/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001251bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001252 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001253 if (SS && SS->isInvalid()) {
1254 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001255 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001256 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001257 }
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Douglas Gregor495c35d2009-08-25 22:51:20 +00001259 if (SS && SS->isSet()) {
1260 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001261 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001262 // contex, and will perform name lookup in that context.
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001263 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCallf36e02d2009-10-09 21:13:30 +00001264 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001265
John McCalla24dc2e2009-11-17 02:14:36 +00001266 R.setContextRange(SS->getRange());
1267
1268 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001269 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001270
Douglas Gregor495c35d2009-08-25 22:51:20 +00001271 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001272 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001273 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001274 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001275 }
1276
Mike Stump1eb44332009-09-09 15:08:12 +00001277 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001278 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001279}
1280
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001281
Douglas Gregor7176fff2009-01-15 00:26:24 +00001282/// @brief Produce a diagnostic describing the ambiguity that resulted
1283/// from name lookup.
1284///
1285/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001286///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001287/// @param Name The name of the entity that name lookup was
1288/// searching for.
1289///
1290/// @param NameLoc The location of the name within the source code.
1291///
1292/// @param LookupRange A source range that provides more
1293/// source-location information concerning the lookup itself. For
1294/// example, this range might highlight a nested-name-specifier that
1295/// precedes the name.
1296///
1297/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001298bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001299 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1300
John McCalla24dc2e2009-11-17 02:14:36 +00001301 DeclarationName Name = Result.getLookupName();
1302 SourceLocation NameLoc = Result.getNameLoc();
1303 SourceRange LookupRange = Result.getContextRange();
1304
John McCall6e247262009-10-10 05:48:19 +00001305 switch (Result.getAmbiguityKind()) {
1306 case LookupResult::AmbiguousBaseSubobjects: {
1307 CXXBasePaths *Paths = Result.getBasePaths();
1308 QualType SubobjectType = Paths->front().back().Base->getType();
1309 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1310 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1311 << LookupRange;
1312
1313 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1314 while (isa<CXXMethodDecl>(*Found) &&
1315 cast<CXXMethodDecl>(*Found)->isStatic())
1316 ++Found;
1317
1318 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1319
1320 return true;
1321 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001322
John McCall6e247262009-10-10 05:48:19 +00001323 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001324 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1325 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001326
1327 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001328 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001329 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1330 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001331 Path != PathEnd; ++Path) {
1332 Decl *D = *Path->Decls.first;
1333 if (DeclsPrinted.insert(D).second)
1334 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1335 }
1336
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001337 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001338 }
1339
John McCall6e247262009-10-10 05:48:19 +00001340 case LookupResult::AmbiguousTagHiding: {
1341 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001342
John McCall6e247262009-10-10 05:48:19 +00001343 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1344
1345 LookupResult::iterator DI, DE = Result.end();
1346 for (DI = Result.begin(); DI != DE; ++DI)
1347 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1348 TagDecls.insert(TD);
1349 Diag(TD->getLocation(), diag::note_hidden_tag);
1350 }
1351
1352 for (DI = Result.begin(); DI != DE; ++DI)
1353 if (!isa<TagDecl>(*DI))
1354 Diag((*DI)->getLocation(), diag::note_hiding_object);
1355
1356 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001357 LookupResult::Filter F = Result.makeFilter();
1358 while (F.hasNext()) {
1359 if (TagDecls.count(F.next()))
1360 F.erase();
1361 }
1362 F.done();
John McCall6e247262009-10-10 05:48:19 +00001363
1364 return true;
1365 }
1366
1367 case LookupResult::AmbiguousReference: {
1368 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001369
John McCall6e247262009-10-10 05:48:19 +00001370 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1371 for (; DI != DE; ++DI)
1372 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001373
John McCall6e247262009-10-10 05:48:19 +00001374 return true;
1375 }
1376 }
1377
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001378 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001379 return true;
1380}
Douglas Gregorfa047642009-02-04 00:32:51 +00001381
Mike Stump1eb44332009-09-09 15:08:12 +00001382static void
1383addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001384 ASTContext &Context,
1385 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001386 Sema::AssociatedClassSet &AssociatedClasses);
1387
1388static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1389 DeclContext *Ctx) {
1390 if (Ctx->isFileContext())
1391 Namespaces.insert(Ctx);
1392}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001393
Mike Stump1eb44332009-09-09 15:08:12 +00001394// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001395// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001396static void
1397addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001398 ASTContext &Context,
1399 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001400 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001401 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001402 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001403 switch (Arg.getKind()) {
1404 case TemplateArgument::Null:
1405 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Douglas Gregor69be8d62009-07-08 07:51:57 +00001407 case TemplateArgument::Type:
1408 // [...] the namespaces and classes associated with the types of the
1409 // template arguments provided for template type parameters (excluding
1410 // template template parameters)
1411 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1412 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001413 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001414 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Douglas Gregor788cd062009-11-11 01:00:40 +00001416 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001417 // [...] the namespaces in which any template template arguments are
1418 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001419 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001420 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001421 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001422 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001423 DeclContext *Ctx = ClassTemplate->getDeclContext();
1424 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1425 AssociatedClasses.insert(EnclosingClass);
1426 // Add the associated namespace for this class.
1427 while (Ctx->isRecord())
1428 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001429 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001430 }
1431 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001432 }
1433
1434 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001435 case TemplateArgument::Integral:
1436 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001437 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001438 // associated namespaces. ]
1439 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Douglas Gregor69be8d62009-07-08 07:51:57 +00001441 case TemplateArgument::Pack:
1442 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1443 PEnd = Arg.pack_end();
1444 P != PEnd; ++P)
1445 addAssociatedClassesAndNamespaces(*P, Context,
1446 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001447 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001448 break;
1449 }
1450}
1451
Douglas Gregorfa047642009-02-04 00:32:51 +00001452// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001453// argument-dependent lookup with an argument of class type
1454// (C++ [basic.lookup.koenig]p2).
1455static void
1456addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregorfa047642009-02-04 00:32:51 +00001457 ASTContext &Context,
1458 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001459 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001460 // C++ [basic.lookup.koenig]p2:
1461 // [...]
1462 // -- If T is a class type (including unions), its associated
1463 // classes are: the class itself; the class of which it is a
1464 // member, if any; and its direct and indirect base
1465 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001466 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001467
1468 // Add the class of which it is a member, if any.
1469 DeclContext *Ctx = Class->getDeclContext();
1470 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1471 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001472 // Add the associated namespace for this class.
1473 while (Ctx->isRecord())
1474 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001475 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Douglas Gregorfa047642009-02-04 00:32:51 +00001477 // Add the class itself. If we've already seen this class, we don't
1478 // need to visit base classes.
1479 if (!AssociatedClasses.insert(Class))
1480 return;
1481
Mike Stump1eb44332009-09-09 15:08:12 +00001482 // -- If T is a template-id, its associated namespaces and classes are
1483 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001484 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001485 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001486 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001487 // namespaces in which any template template arguments are defined; and
1488 // the classes in which any member templates used as template template
1489 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001490 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001491 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001492 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1493 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1494 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1495 AssociatedClasses.insert(EnclosingClass);
1496 // Add the associated namespace for this class.
1497 while (Ctx->isRecord())
1498 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001499 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Douglas Gregor69be8d62009-07-08 07:51:57 +00001501 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1502 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1503 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1504 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001505 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001506 }
Mike Stump1eb44332009-09-09 15:08:12 +00001507
John McCall86ff3082010-02-04 22:26:26 +00001508 // Only recurse into base classes for complete types.
1509 if (!Class->hasDefinition()) {
1510 // FIXME: we might need to instantiate templates here
1511 return;
1512 }
1513
Douglas Gregorfa047642009-02-04 00:32:51 +00001514 // Add direct and indirect base classes along with their associated
1515 // namespaces.
1516 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1517 Bases.push_back(Class);
1518 while (!Bases.empty()) {
1519 // Pop this class off the stack.
1520 Class = Bases.back();
1521 Bases.pop_back();
1522
1523 // Visit the base classes.
1524 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1525 BaseEnd = Class->bases_end();
1526 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001527 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001528 // In dependent contexts, we do ADL twice, and the first time around,
1529 // the base type might be a dependent TemplateSpecializationType, or a
1530 // TemplateTypeParmType. If that happens, simply ignore it.
1531 // FIXME: If we want to support export, we probably need to add the
1532 // namespace of the template in a TemplateSpecializationType, or even
1533 // the classes and namespaces of known non-dependent arguments.
1534 if (!BaseType)
1535 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001536 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1537 if (AssociatedClasses.insert(BaseDecl)) {
1538 // Find the associated namespace for this base class.
1539 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1540 while (BaseCtx->isRecord())
1541 BaseCtx = BaseCtx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001542 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001543
1544 // Make sure we visit the bases of this base class.
1545 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1546 Bases.push_back(BaseDecl);
1547 }
1548 }
1549 }
1550}
1551
1552// \brief Add the associated classes and namespaces for
1553// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001554// (C++ [basic.lookup.koenig]p2).
1555static void
1556addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregorfa047642009-02-04 00:32:51 +00001557 ASTContext &Context,
1558 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001559 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001560 // C++ [basic.lookup.koenig]p2:
1561 //
1562 // For each argument type T in the function call, there is a set
1563 // of zero or more associated namespaces and a set of zero or more
1564 // associated classes to be considered. The sets of namespaces and
1565 // classes is determined entirely by the types of the function
1566 // arguments (and the namespace of any template template
1567 // argument). Typedef names and using-declarations used to specify
1568 // the types do not contribute to this set. The sets of namespaces
1569 // and classes are determined in the following way:
1570 T = Context.getCanonicalType(T).getUnqualifiedType();
1571
1572 // -- If T is a pointer to U or an array of U, its associated
Mike Stump1eb44332009-09-09 15:08:12 +00001573 // namespaces and classes are those associated with U.
Douglas Gregorfa047642009-02-04 00:32:51 +00001574 //
1575 // We handle this by unwrapping pointer and array types immediately,
1576 // to avoid unnecessary recursion.
1577 while (true) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001578 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001579 T = Ptr->getPointeeType();
1580 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1581 T = Ptr->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001582 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001583 break;
1584 }
1585
1586 // -- If T is a fundamental type, its associated sets of
1587 // namespaces and classes are both empty.
John McCall183700f2009-09-21 23:43:11 +00001588 if (T->getAs<BuiltinType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001589 return;
1590
1591 // -- If T is a class type (including unions), its associated
1592 // classes are: the class itself; the class of which it is a
1593 // member, if any; and its direct and indirect base
1594 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001595 // which its associated classes are defined.
Ted Kremenek6217b802009-07-29 21:53:49 +00001596 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001597 if (CXXRecordDecl *ClassDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001598 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001599 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1600 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001601 AssociatedClasses);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001602 return;
1603 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001604
1605 // -- If T is an enumeration type, its associated namespace is
1606 // the namespace in which it is defined. If it is class
1607 // member, its associated class is the member’s class; else
Mike Stump1eb44332009-09-09 15:08:12 +00001608 // it has no associated class.
John McCall183700f2009-09-21 23:43:11 +00001609 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001610 EnumDecl *Enum = EnumT->getDecl();
1611
1612 DeclContext *Ctx = Enum->getDeclContext();
1613 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1614 AssociatedClasses.insert(EnclosingClass);
1615
1616 // Add the associated namespace for this class.
1617 while (Ctx->isRecord())
1618 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001619 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001620
1621 return;
1622 }
1623
1624 // -- If T is a function type, its associated namespaces and
1625 // classes are those associated with the function parameter
1626 // types and those associated with the return type.
John McCall183700f2009-09-21 23:43:11 +00001627 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001628 // Return type
John McCall183700f2009-09-21 23:43:11 +00001629 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001630 Context,
John McCall6ff07852009-08-07 22:18:02 +00001631 AssociatedNamespaces, AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001632
John McCall183700f2009-09-21 23:43:11 +00001633 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001634 if (!Proto)
1635 return;
1636
1637 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001638 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001639 ArgEnd = Proto->arg_type_end();
Douglas Gregorfa047642009-02-04 00:32:51 +00001640 Arg != ArgEnd; ++Arg)
1641 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCall6ff07852009-08-07 22:18:02 +00001642 AssociatedNamespaces, AssociatedClasses);
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Douglas Gregorfa047642009-02-04 00:32:51 +00001644 return;
1645 }
1646
1647 // -- If T is a pointer to a member function of a class X, its
1648 // associated namespaces and classes are those associated
1649 // with the function parameter types and return type,
Mike Stump1eb44332009-09-09 15:08:12 +00001650 // together with those associated with X.
Douglas Gregorfa047642009-02-04 00:32:51 +00001651 //
1652 // -- If T is a pointer to a data member of class X, its
1653 // associated namespaces and classes are those associated
1654 // with the member type together with those associated with
Mike Stump1eb44332009-09-09 15:08:12 +00001655 // X.
Ted Kremenek6217b802009-07-29 21:53:49 +00001656 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001657 // Handle the type that the pointer to member points to.
1658 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1659 Context,
John McCall6ff07852009-08-07 22:18:02 +00001660 AssociatedNamespaces,
1661 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001662
1663 // Handle the class type into which this points.
Ted Kremenek6217b802009-07-29 21:53:49 +00001664 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001665 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1666 Context,
John McCall6ff07852009-08-07 22:18:02 +00001667 AssociatedNamespaces,
1668 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001669
1670 return;
1671 }
1672
1673 // FIXME: What about block pointers?
1674 // FIXME: What about Objective-C message sends?
1675}
1676
1677/// \brief Find the associated classes and namespaces for
1678/// argument-dependent lookup for a call with the given set of
1679/// arguments.
1680///
1681/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001682/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001683/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001684void
Douglas Gregorfa047642009-02-04 00:32:51 +00001685Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1686 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001687 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001688 AssociatedNamespaces.clear();
1689 AssociatedClasses.clear();
1690
1691 // C++ [basic.lookup.koenig]p2:
1692 // For each argument type T in the function call, there is a set
1693 // of zero or more associated namespaces and a set of zero or more
1694 // associated classes to be considered. The sets of namespaces and
1695 // classes is determined entirely by the types of the function
1696 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001697 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001698 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1699 Expr *Arg = Args[ArgIdx];
1700
1701 if (Arg->getType() != Context.OverloadTy) {
1702 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001703 AssociatedNamespaces,
1704 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001705 continue;
1706 }
1707
1708 // [...] In addition, if the argument is the name or address of a
1709 // set of overloaded functions and/or function templates, its
1710 // associated classes and namespaces are the union of those
1711 // associated with each of the members of the set: the namespace
1712 // in which the function or function template is defined and the
1713 // classes and namespaces associated with its (non-dependent)
1714 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001715 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001716 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1717 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1718 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001719
John McCallba135432009-11-21 08:51:07 +00001720 // TODO: avoid the copies. This should be easy when the cases
1721 // share a storage implementation.
1722 llvm::SmallVector<NamedDecl*, 8> Functions;
1723
1724 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1725 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00001726 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001727 continue;
1728
John McCallba135432009-11-21 08:51:07 +00001729 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1730 E = Functions.end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001731 // Look through any using declarations to find the underlying function.
1732 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001733
Chandler Carruthbd647292009-12-29 06:17:27 +00001734 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1735 if (!FDecl)
1736 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001737
1738 // Add the classes and namespaces associated with the parameter
1739 // types and return type of this function.
1740 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001741 AssociatedNamespaces,
1742 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001743 }
1744 }
1745}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001746
1747/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1748/// an acceptable non-member overloaded operator for a call whose
1749/// arguments have types T1 (and, if non-empty, T2). This routine
1750/// implements the check in C++ [over.match.oper]p3b2 concerning
1751/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001752static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001753IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1754 QualType T1, QualType T2,
1755 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001756 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1757 return true;
1758
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001759 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1760 return true;
1761
John McCall183700f2009-09-21 23:43:11 +00001762 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001763 if (Proto->getNumArgs() < 1)
1764 return false;
1765
1766 if (T1->isEnumeralType()) {
1767 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001768 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001769 return true;
1770 }
1771
1772 if (Proto->getNumArgs() < 2)
1773 return false;
1774
1775 if (!T2.isNull() && T2->isEnumeralType()) {
1776 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001777 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001778 return true;
1779 }
1780
1781 return false;
1782}
1783
John McCall7d384dd2009-11-18 07:57:50 +00001784NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00001785 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00001786 LookupNameKind NameKind,
1787 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00001788 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00001789 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00001790 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00001791}
1792
Douglas Gregor6e378de2009-04-23 23:18:26 +00001793/// \brief Find the protocol with the given name, if any.
Douglas Gregorc83c6872010-04-15 22:33:43 +00001794ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
1795 SourceLocation IdLoc) {
1796 Decl *D = LookupSingleName(TUScope, II, IdLoc,
1797 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001798 return cast_or_null<ObjCProtocolDecl>(D);
1799}
1800
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001801void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001802 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00001803 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001804 // C++ [over.match.oper]p3:
1805 // -- The set of non-member candidates is the result of the
1806 // unqualified lookup of operator@ in the context of the
1807 // expression according to the usual rules for name lookup in
1808 // unqualified function calls (3.4.2) except that all member
1809 // functions are ignored. However, if no operand has a class
1810 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00001811 // that have a first parameter of type T1 or "reference to
1812 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001813 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00001814 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001815 // when T2 is an enumeration type, are candidate functions.
1816 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00001817 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1818 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001820 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1821
John McCallf36e02d2009-10-09 21:13:30 +00001822 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001823 return;
1824
1825 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1826 Op != OpEnd; ++Op) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001827 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001828 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
John McCall6e266892010-01-26 03:27:55 +00001829 Functions.addDecl(FD, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00001830 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor364e0212009-06-27 21:05:07 +00001831 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1832 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00001833 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00001834 // later?
1835 if (!FunTmpl->getDeclContext()->isRecord())
John McCall6e266892010-01-26 03:27:55 +00001836 Functions.addDecl(FunTmpl, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00001837 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001838 }
1839}
1840
John McCall7edb5fd2010-01-26 07:16:45 +00001841void ADLResult::insert(NamedDecl *New) {
1842 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1843
1844 // If we haven't yet seen a decl for this key, or the last decl
1845 // was exactly this one, we're done.
1846 if (Old == 0 || Old == New) {
1847 Old = New;
1848 return;
1849 }
1850
1851 // Otherwise, decide which is a more recent redeclaration.
1852 FunctionDecl *OldFD, *NewFD;
1853 if (isa<FunctionTemplateDecl>(New)) {
1854 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1855 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1856 } else {
1857 OldFD = cast<FunctionDecl>(Old);
1858 NewFD = cast<FunctionDecl>(New);
1859 }
1860
1861 FunctionDecl *Cursor = NewFD;
1862 while (true) {
1863 Cursor = Cursor->getPreviousDeclaration();
1864
1865 // If we got to the end without finding OldFD, OldFD is the newer
1866 // declaration; leave things as they are.
1867 if (!Cursor) return;
1868
1869 // If we do find OldFD, then NewFD is newer.
1870 if (Cursor == OldFD) break;
1871
1872 // Otherwise, keep looking.
1873 }
1874
1875 Old = New;
1876}
1877
Sebastian Redl644be852009-10-23 19:23:15 +00001878void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001879 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00001880 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001881 // Find all of the associated namespaces and classes based on the
1882 // arguments we have.
1883 AssociatedNamespaceSet AssociatedNamespaces;
1884 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00001885 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00001886 AssociatedNamespaces,
1887 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001888
Sebastian Redl644be852009-10-23 19:23:15 +00001889 QualType T1, T2;
1890 if (Operator) {
1891 T1 = Args[0]->getType();
1892 if (NumArgs >= 2)
1893 T2 = Args[1]->getType();
1894 }
1895
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001896 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001897 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1898 // and let Y be the lookup set produced by argument dependent
1899 // lookup (defined as follows). If X contains [...] then Y is
1900 // empty. Otherwise Y is the set of declarations found in the
1901 // namespaces associated with the argument types as described
1902 // below. The set of declarations found by the lookup of the name
1903 // is the union of X and Y.
1904 //
1905 // Here, we compute Y and add its members to the overloaded
1906 // candidate set.
1907 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001908 NSEnd = AssociatedNamespaces.end();
1909 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001910 // When considering an associated namespace, the lookup is the
1911 // same as the lookup performed when the associated namespace is
1912 // used as a qualifier (3.4.3.2) except that:
1913 //
1914 // -- Any using-directives in the associated namespace are
1915 // ignored.
1916 //
John McCall6ff07852009-08-07 22:18:02 +00001917 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001918 // associated classes are visible within their respective
1919 // namespaces even if they are not visible during an ordinary
1920 // lookup (11.4).
1921 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00001922 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00001923 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00001924 // If the only declaration here is an ordinary friend, consider
1925 // it only if it was declared in an associated classes.
1926 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00001927 DeclContext *LexDC = D->getLexicalDeclContext();
1928 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1929 continue;
1930 }
Mike Stump1eb44332009-09-09 15:08:12 +00001931
John McCalla113e722010-01-26 06:04:06 +00001932 if (isa<UsingShadowDecl>(D))
1933 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00001934
John McCalla113e722010-01-26 06:04:06 +00001935 if (isa<FunctionDecl>(D)) {
1936 if (Operator &&
1937 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
1938 T1, T2, Context))
1939 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00001940 } else if (!isa<FunctionTemplateDecl>(D))
1941 continue;
1942
1943 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001944 }
1945 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001946}
Douglas Gregor546be3c2009-12-30 17:04:44 +00001947
1948//----------------------------------------------------------------------------
1949// Search for all visible declarations.
1950//----------------------------------------------------------------------------
1951VisibleDeclConsumer::~VisibleDeclConsumer() { }
1952
1953namespace {
1954
1955class ShadowContextRAII;
1956
1957class VisibleDeclsRecord {
1958public:
1959 /// \brief An entry in the shadow map, which is optimized to store a
1960 /// single declaration (the common case) but can also store a list
1961 /// of declarations.
1962 class ShadowMapEntry {
1963 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1964
1965 /// \brief Contains either the solitary NamedDecl * or a vector
1966 /// of declarations.
1967 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1968
1969 public:
1970 ShadowMapEntry() : DeclOrVector() { }
1971
1972 void Add(NamedDecl *ND);
1973 void Destroy();
1974
1975 // Iteration.
1976 typedef NamedDecl **iterator;
1977 iterator begin();
1978 iterator end();
1979 };
1980
1981private:
1982 /// \brief A mapping from declaration names to the declarations that have
1983 /// this name within a particular scope.
1984 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
1985
1986 /// \brief A list of shadow maps, which is used to model name hiding.
1987 std::list<ShadowMap> ShadowMaps;
1988
1989 /// \brief The declaration contexts we have already visited.
1990 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
1991
1992 friend class ShadowContextRAII;
1993
1994public:
1995 /// \brief Determine whether we have already visited this context
1996 /// (and, if not, note that we are going to visit that context now).
1997 bool visitedContext(DeclContext *Ctx) {
1998 return !VisitedContexts.insert(Ctx);
1999 }
2000
2001 /// \brief Determine whether the given declaration is hidden in the
2002 /// current scope.
2003 ///
2004 /// \returns the declaration that hides the given declaration, or
2005 /// NULL if no such declaration exists.
2006 NamedDecl *checkHidden(NamedDecl *ND);
2007
2008 /// \brief Add a declaration to the current shadow map.
2009 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2010};
2011
2012/// \brief RAII object that records when we've entered a shadow context.
2013class ShadowContextRAII {
2014 VisibleDeclsRecord &Visible;
2015
2016 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2017
2018public:
2019 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2020 Visible.ShadowMaps.push_back(ShadowMap());
2021 }
2022
2023 ~ShadowContextRAII() {
2024 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2025 EEnd = Visible.ShadowMaps.back().end();
2026 E != EEnd;
2027 ++E)
2028 E->second.Destroy();
2029
2030 Visible.ShadowMaps.pop_back();
2031 }
2032};
2033
2034} // end anonymous namespace
2035
2036void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2037 if (DeclOrVector.isNull()) {
2038 // 0 - > 1 elements: just set the single element information.
2039 DeclOrVector = ND;
2040 return;
2041 }
2042
2043 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2044 // 1 -> 2 elements: create the vector of results and push in the
2045 // existing declaration.
2046 DeclVector *Vec = new DeclVector;
2047 Vec->push_back(PrevND);
2048 DeclOrVector = Vec;
2049 }
2050
2051 // Add the new element to the end of the vector.
2052 DeclOrVector.get<DeclVector*>()->push_back(ND);
2053}
2054
2055void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2056 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2057 delete Vec;
2058 DeclOrVector = ((NamedDecl *)0);
2059 }
2060}
2061
2062VisibleDeclsRecord::ShadowMapEntry::iterator
2063VisibleDeclsRecord::ShadowMapEntry::begin() {
2064 if (DeclOrVector.isNull())
2065 return 0;
2066
2067 if (DeclOrVector.dyn_cast<NamedDecl *>())
2068 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2069
2070 return DeclOrVector.get<DeclVector *>()->begin();
2071}
2072
2073VisibleDeclsRecord::ShadowMapEntry::iterator
2074VisibleDeclsRecord::ShadowMapEntry::end() {
2075 if (DeclOrVector.isNull())
2076 return 0;
2077
2078 if (DeclOrVector.dyn_cast<NamedDecl *>())
2079 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2080
2081 return DeclOrVector.get<DeclVector *>()->end();
2082}
2083
2084NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002085 // Look through using declarations.
2086 ND = ND->getUnderlyingDecl();
2087
Douglas Gregor546be3c2009-12-30 17:04:44 +00002088 unsigned IDNS = ND->getIdentifierNamespace();
2089 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2090 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2091 SM != SMEnd; ++SM) {
2092 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2093 if (Pos == SM->end())
2094 continue;
2095
2096 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2097 IEnd = Pos->second.end();
2098 I != IEnd; ++I) {
2099 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002100 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor546be3c2009-12-30 17:04:44 +00002101 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2102 Decl::IDNS_ObjCProtocol)))
2103 continue;
2104
2105 // Protocols are in distinct namespaces from everything else.
2106 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2107 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2108 (*I)->getIdentifierNamespace() != IDNS)
2109 continue;
2110
Douglas Gregor0cc84042010-01-14 15:47:35 +00002111 // Functions and function templates in the same scope overload
2112 // rather than hide. FIXME: Look for hiding based on function
2113 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002114 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002115 ND->isFunctionOrFunctionTemplate() &&
2116 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002117 continue;
2118
Douglas Gregor546be3c2009-12-30 17:04:44 +00002119 // We've found a declaration that hides this one.
2120 return *I;
2121 }
2122 }
2123
2124 return 0;
2125}
2126
2127static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2128 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002129 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002130 VisibleDeclConsumer &Consumer,
2131 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002132 if (!Ctx)
2133 return;
2134
Douglas Gregor546be3c2009-12-30 17:04:44 +00002135 // Make sure we don't visit the same context twice.
2136 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2137 return;
2138
2139 // Enumerate all of the results in this context.
2140 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2141 CurCtx = CurCtx->getNextContext()) {
2142 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2143 DEnd = CurCtx->decls_end();
2144 D != DEnd; ++D) {
2145 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2146 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002147 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002148 Visited.add(ND);
2149 }
2150
2151 // Visit transparent contexts inside this context.
2152 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2153 if (InnerCtx->isTransparentContext())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002154 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002155 Consumer, Visited);
2156 }
2157 }
2158 }
2159
2160 // Traverse using directives for qualified name lookup.
2161 if (QualifiedNameLookup) {
2162 ShadowContextRAII Shadow(Visited);
2163 DeclContext::udir_iterator I, E;
2164 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2165 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002166 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002167 }
2168 }
2169
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002170 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002171 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002172 if (!Record->hasDefinition())
2173 return;
2174
Douglas Gregor546be3c2009-12-30 17:04:44 +00002175 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2176 BEnd = Record->bases_end();
2177 B != BEnd; ++B) {
2178 QualType BaseType = B->getType();
2179
2180 // Don't look into dependent bases, because name lookup can't look
2181 // there anyway.
2182 if (BaseType->isDependentType())
2183 continue;
2184
2185 const RecordType *Record = BaseType->getAs<RecordType>();
2186 if (!Record)
2187 continue;
2188
2189 // FIXME: It would be nice to be able to determine whether referencing
2190 // a particular member would be ambiguous. For example, given
2191 //
2192 // struct A { int member; };
2193 // struct B { int member; };
2194 // struct C : A, B { };
2195 //
2196 // void f(C *c) { c->### }
2197 //
2198 // accessing 'member' would result in an ambiguity. However, we
2199 // could be smart enough to qualify the member with the base
2200 // class, e.g.,
2201 //
2202 // c->B::member
2203 //
2204 // or
2205 //
2206 // c->A::member
2207
2208 // Find results in this base class (and its bases).
2209 ShadowContextRAII Shadow(Visited);
2210 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002211 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002212 }
2213 }
2214
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002215 // Traverse the contexts of Objective-C classes.
2216 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2217 // Traverse categories.
2218 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2219 Category; Category = Category->getNextClassCategory()) {
2220 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002221 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2222 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002223 }
2224
2225 // Traverse protocols.
2226 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2227 E = IFace->protocol_end(); I != E; ++I) {
2228 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002229 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2230 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002231 }
2232
2233 // Traverse the superclass.
2234 if (IFace->getSuperClass()) {
2235 ShadowContextRAII Shadow(Visited);
2236 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002237 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002238 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002239
2240 // If there is an implementation, traverse it. We do this to find
2241 // synthesized ivars.
2242 if (IFace->getImplementation()) {
2243 ShadowContextRAII Shadow(Visited);
2244 LookupVisibleDecls(IFace->getImplementation(), Result,
2245 QualifiedNameLookup, true, Consumer, Visited);
2246 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002247 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2248 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2249 E = Protocol->protocol_end(); I != E; ++I) {
2250 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002251 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2252 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002253 }
2254 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2255 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2256 E = Category->protocol_end(); I != E; ++I) {
2257 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002258 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2259 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002260 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002261
2262 // If there is an implementation, traverse it.
2263 if (Category->getImplementation()) {
2264 ShadowContextRAII Shadow(Visited);
2265 LookupVisibleDecls(Category->getImplementation(), Result,
2266 QualifiedNameLookup, true, Consumer, Visited);
2267 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002268 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002269}
2270
2271static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2272 UnqualUsingDirectiveSet &UDirs,
2273 VisibleDeclConsumer &Consumer,
2274 VisibleDeclsRecord &Visited) {
2275 if (!S)
2276 return;
2277
Douglas Gregor539c5c32010-01-07 00:31:29 +00002278 if (!S->getEntity() || !S->getParent() ||
2279 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2280 // Walk through the declarations in this Scope.
2281 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2282 D != DEnd; ++D) {
2283 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2284 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002285 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002286 Visited.add(ND);
2287 }
2288 }
2289 }
2290
Douglas Gregor711be1e2010-03-15 14:33:29 +00002291 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002292 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002293 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002294 // Look into this scope's declaration context, along with any of its
2295 // parent lookup contexts (e.g., enclosing classes), up to the point
2296 // where we hit the context stored in the next outer scope.
2297 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002298 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor546be3c2009-12-30 17:04:44 +00002299
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002300 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002301 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002302 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2303 if (Method->isInstanceMethod()) {
2304 // For instance methods, look for ivars in the method's interface.
2305 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2306 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor62021192010-02-04 23:42:48 +00002307 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2308 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2309 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002310 }
2311
2312 // We've already performed all of the name lookup that we need
2313 // to for Objective-C methods; the next context will be the
2314 // outer scope.
2315 break;
2316 }
2317
Douglas Gregor546be3c2009-12-30 17:04:44 +00002318 if (Ctx->isFunctionOrMethod())
2319 continue;
2320
2321 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002322 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002323 }
2324 } else if (!S->getParent()) {
2325 // Look into the translation unit scope. We walk through the translation
2326 // unit's declaration context, because the Scope itself won't have all of
2327 // the declarations if we loaded a precompiled header.
2328 // FIXME: We would like the translation unit's Scope object to point to the
2329 // translation unit, so we don't need this special "if" branch. However,
2330 // doing so would force the normal C++ name-lookup code to look into the
2331 // translation unit decl when the IdentifierInfo chains would suffice.
2332 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002333 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002334 Entity = Result.getSema().Context.getTranslationUnitDecl();
2335 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002336 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002337 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002338
2339 if (Entity) {
2340 // Lookup visible declarations in any namespaces found by using
2341 // directives.
2342 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2343 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2344 for (; UI != UEnd; ++UI)
2345 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002346 Result, /*QualifiedNameLookup=*/false,
2347 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002348 }
2349
2350 // Lookup names in the parent scope.
2351 ShadowContextRAII Shadow(Visited);
2352 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2353}
2354
2355void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2356 VisibleDeclConsumer &Consumer) {
2357 // Determine the set of using directives available during
2358 // unqualified name lookup.
2359 Scope *Initial = S;
2360 UnqualUsingDirectiveSet UDirs;
2361 if (getLangOptions().CPlusPlus) {
2362 // Find the first namespace or translation-unit scope.
2363 while (S && !isNamespaceOrTranslationUnitScope(S))
2364 S = S->getParent();
2365
2366 UDirs.visitScopeChain(Initial, S);
2367 }
2368 UDirs.done();
2369
2370 // Look for visible declarations.
2371 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2372 VisibleDeclsRecord Visited;
2373 ShadowContextRAII Shadow(Visited);
2374 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2375}
2376
2377void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2378 VisibleDeclConsumer &Consumer) {
2379 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2380 VisibleDeclsRecord Visited;
2381 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002382 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2383 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002384}
2385
2386//----------------------------------------------------------------------------
2387// Typo correction
2388//----------------------------------------------------------------------------
2389
2390namespace {
2391class TypoCorrectionConsumer : public VisibleDeclConsumer {
2392 /// \brief The name written that is a typo in the source.
2393 llvm::StringRef Typo;
2394
2395 /// \brief The results found that have the smallest edit distance
2396 /// found (so far) with the typo name.
2397 llvm::SmallVector<NamedDecl *, 4> BestResults;
2398
Douglas Gregoraaf87162010-04-14 20:04:41 +00002399 /// \brief The keywords that have the smallest edit distance.
2400 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2401
Douglas Gregor546be3c2009-12-30 17:04:44 +00002402 /// \brief The best edit distance found so far.
2403 unsigned BestEditDistance;
2404
2405public:
2406 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2407 : Typo(Typo->getName()) { }
2408
Douglas Gregor0cc84042010-01-14 15:47:35 +00002409 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002410 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002411
2412 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2413 iterator begin() const { return BestResults.begin(); }
2414 iterator end() const { return BestResults.end(); }
Douglas Gregoraaf87162010-04-14 20:04:41 +00002415 void clear_decls() { BestResults.clear(); }
2416
2417 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002418
Douglas Gregoraaf87162010-04-14 20:04:41 +00002419 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2420 keyword_iterator;
2421 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2422 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2423 bool keyword_empty() const { return BestKeywords.empty(); }
2424 unsigned keyword_size() const { return BestKeywords.size(); }
2425
2426 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002427};
2428
2429}
2430
Douglas Gregor0cc84042010-01-14 15:47:35 +00002431void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2432 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002433 // Don't consider hidden names for typo correction.
2434 if (Hiding)
2435 return;
2436
2437 // Only consider entities with identifiers for names, ignoring
2438 // special names (constructors, overloaded operators, selectors,
2439 // etc.).
2440 IdentifierInfo *Name = ND->getIdentifier();
2441 if (!Name)
2442 return;
2443
2444 // Compute the edit distance between the typo and the name of this
2445 // entity. If this edit distance is not worse than the best edit
2446 // distance we've seen so far, add it to the list of results.
2447 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregoraaf87162010-04-14 20:04:41 +00002448 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002449 if (ED < BestEditDistance) {
2450 // This result is better than any we've seen before; clear out
2451 // the previous results.
2452 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002453 BestKeywords.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002454 BestEditDistance = ED;
2455 } else if (ED > BestEditDistance) {
2456 // This result is worse than the best results we've seen so far;
2457 // ignore it.
2458 return;
2459 }
2460 } else
2461 BestEditDistance = ED;
2462
2463 BestResults.push_back(ND);
2464}
2465
Douglas Gregoraaf87162010-04-14 20:04:41 +00002466void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2467 llvm::StringRef Keyword) {
2468 // Compute the edit distance between the typo and this keyword.
2469 // If this edit distance is not worse than the best edit
2470 // distance we've seen so far, add it to the list of results.
2471 unsigned ED = Typo.edit_distance(Keyword);
2472 if (!BestResults.empty() || !BestKeywords.empty()) {
2473 if (ED < BestEditDistance) {
2474 BestResults.clear();
2475 BestKeywords.clear();
2476 BestEditDistance = ED;
2477 } else if (ED > BestEditDistance) {
2478 // This result is worse than the best results we've seen so far;
2479 // ignore it.
2480 return;
2481 }
2482 } else
2483 BestEditDistance = ED;
2484
2485 BestKeywords.push_back(&Context.Idents.get(Keyword));
2486}
2487
Douglas Gregor546be3c2009-12-30 17:04:44 +00002488/// \brief Try to "correct" a typo in the source code by finding
2489/// visible declarations whose names are similar to the name that was
2490/// present in the source code.
2491///
2492/// \param Res the \c LookupResult structure that contains the name
2493/// that was present in the source code along with the name-lookup
2494/// criteria used to search for the name. On success, this structure
2495/// will contain the results of name lookup.
2496///
2497/// \param S the scope in which name lookup occurs.
2498///
2499/// \param SS the nested-name-specifier that precedes the name we're
2500/// looking for, if present.
2501///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002502/// \param MemberContext if non-NULL, the context in which to look for
2503/// a member access expression.
2504///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002505/// \param EnteringContext whether we're entering the context described by
2506/// the nested-name-specifier SS.
2507///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002508/// \param CTC The context in which typo correction occurs, which impacts the
2509/// set of keywords permitted.
2510///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002511/// \param OPT when non-NULL, the search for visible declarations will
2512/// also walk the protocols in the qualified interfaces of \p OPT.
2513///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002514/// \returns the corrected name if the typo was corrected, otherwise returns an
2515/// empty \c DeclarationName. When a typo was corrected, the result structure
2516/// may contain the results of name lookup for the correct name or it may be
2517/// empty.
2518DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002519 DeclContext *MemberContext,
2520 bool EnteringContext,
2521 CorrectTypoContext CTC,
2522 const ObjCObjectPointerType *OPT) {
Ted Kremenek1dac3412010-01-06 00:23:04 +00002523 if (Diags.hasFatalErrorOccurred())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002524 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002525
2526 // Provide a stop gap for files that are just seriously broken. Trying
2527 // to correct all typos can turn into a HUGE performance penalty, causing
2528 // some files to take minutes to get rejected by the parser.
2529 // FIXME: Is this the right solution?
2530 if (TyposCorrected == 20)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002531 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002532 ++TyposCorrected;
Ted Kremenek1dac3412010-01-06 00:23:04 +00002533
Douglas Gregor546be3c2009-12-30 17:04:44 +00002534 // We only attempt to correct typos for identifiers.
2535 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2536 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002537 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002538
2539 // If the scope specifier itself was invalid, don't try to correct
2540 // typos.
2541 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002542 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002543
2544 // Never try to correct typos during template deduction or
2545 // instantiation.
2546 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002547 return DeclarationName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002548
Douglas Gregor546be3c2009-12-30 17:04:44 +00002549 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002550
2551 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002552 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002553 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002554
2555 // Look in qualified interfaces.
2556 if (OPT) {
2557 for (ObjCObjectPointerType::qual_iterator
2558 I = OPT->qual_begin(), E = OPT->qual_end();
2559 I != E; ++I)
2560 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2561 }
2562 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002563 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2564 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002565 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002566
2567 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2568 } else {
2569 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2570 }
2571
Douglas Gregoraaf87162010-04-14 20:04:41 +00002572 // Add context-dependent keywords.
2573 bool WantTypeSpecifiers = false;
2574 bool WantExpressionKeywords = false;
2575 bool WantCXXNamedCasts = false;
2576 bool WantRemainingKeywords = false;
2577 switch (CTC) {
2578 case CTC_Unknown:
2579 WantTypeSpecifiers = true;
2580 WantExpressionKeywords = true;
2581 WantCXXNamedCasts = true;
2582 WantRemainingKeywords = true;
2583 break;
2584
2585 case CTC_NoKeywords:
2586 break;
2587
2588 case CTC_Type:
2589 WantTypeSpecifiers = true;
2590 break;
2591
2592 case CTC_ObjCMessageReceiver:
2593 Consumer.addKeywordResult(Context, "super");
2594 // Fall through to handle message receivers like expressions.
2595
2596 case CTC_Expression:
2597 if (getLangOptions().CPlusPlus)
2598 WantTypeSpecifiers = true;
2599 WantExpressionKeywords = true;
2600 // Fall through to get C++ named casts.
2601
2602 case CTC_CXXCasts:
2603 WantCXXNamedCasts = true;
2604 break;
2605
2606 case CTC_MemberLookup:
2607 if (getLangOptions().CPlusPlus)
2608 Consumer.addKeywordResult(Context, "template");
2609 break;
2610 }
2611
2612 if (WantTypeSpecifiers) {
2613 // Add type-specifier keywords to the set of results.
2614 const char *CTypeSpecs[] = {
2615 "char", "const", "double", "enum", "float", "int", "long", "short",
2616 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2617 "_Complex", "_Imaginary",
2618 // storage-specifiers as well
2619 "extern", "inline", "static", "typedef"
2620 };
2621
2622 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2623 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2624 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2625
2626 if (getLangOptions().C99)
2627 Consumer.addKeywordResult(Context, "restrict");
2628 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2629 Consumer.addKeywordResult(Context, "bool");
2630
2631 if (getLangOptions().CPlusPlus) {
2632 Consumer.addKeywordResult(Context, "class");
2633 Consumer.addKeywordResult(Context, "typename");
2634 Consumer.addKeywordResult(Context, "wchar_t");
2635
2636 if (getLangOptions().CPlusPlus0x) {
2637 Consumer.addKeywordResult(Context, "char16_t");
2638 Consumer.addKeywordResult(Context, "char32_t");
2639 Consumer.addKeywordResult(Context, "constexpr");
2640 Consumer.addKeywordResult(Context, "decltype");
2641 Consumer.addKeywordResult(Context, "thread_local");
2642 }
2643 }
2644
2645 if (getLangOptions().GNUMode)
2646 Consumer.addKeywordResult(Context, "typeof");
2647 }
2648
2649 if (WantCXXNamedCasts) {
2650 Consumer.addKeywordResult(Context, "const_cast");
2651 Consumer.addKeywordResult(Context, "dynamic_cast");
2652 Consumer.addKeywordResult(Context, "reinterpret_cast");
2653 Consumer.addKeywordResult(Context, "static_cast");
2654 }
2655
2656 if (WantExpressionKeywords) {
2657 Consumer.addKeywordResult(Context, "sizeof");
2658 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2659 Consumer.addKeywordResult(Context, "false");
2660 Consumer.addKeywordResult(Context, "true");
2661 }
2662
2663 if (getLangOptions().CPlusPlus) {
2664 const char *CXXExprs[] = {
2665 "delete", "new", "operator", "throw", "typeid"
2666 };
2667 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2668 for (unsigned I = 0; I != NumCXXExprs; ++I)
2669 Consumer.addKeywordResult(Context, CXXExprs[I]);
2670
2671 if (isa<CXXMethodDecl>(CurContext) &&
2672 cast<CXXMethodDecl>(CurContext)->isInstance())
2673 Consumer.addKeywordResult(Context, "this");
2674
2675 if (getLangOptions().CPlusPlus0x) {
2676 Consumer.addKeywordResult(Context, "alignof");
2677 Consumer.addKeywordResult(Context, "nullptr");
2678 }
2679 }
2680 }
2681
2682 if (WantRemainingKeywords) {
2683 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2684 // Statements.
2685 const char *CStmts[] = {
2686 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2687 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2688 for (unsigned I = 0; I != NumCStmts; ++I)
2689 Consumer.addKeywordResult(Context, CStmts[I]);
2690
2691 if (getLangOptions().CPlusPlus) {
2692 Consumer.addKeywordResult(Context, "catch");
2693 Consumer.addKeywordResult(Context, "try");
2694 }
2695
2696 if (S && S->getBreakParent())
2697 Consumer.addKeywordResult(Context, "break");
2698
2699 if (S && S->getContinueParent())
2700 Consumer.addKeywordResult(Context, "continue");
2701
2702 if (!getSwitchStack().empty()) {
2703 Consumer.addKeywordResult(Context, "case");
2704 Consumer.addKeywordResult(Context, "default");
2705 }
2706 } else {
2707 if (getLangOptions().CPlusPlus) {
2708 Consumer.addKeywordResult(Context, "namespace");
2709 Consumer.addKeywordResult(Context, "template");
2710 }
2711
2712 if (S && S->isClassScope()) {
2713 Consumer.addKeywordResult(Context, "explicit");
2714 Consumer.addKeywordResult(Context, "friend");
2715 Consumer.addKeywordResult(Context, "mutable");
2716 Consumer.addKeywordResult(Context, "private");
2717 Consumer.addKeywordResult(Context, "protected");
2718 Consumer.addKeywordResult(Context, "public");
2719 Consumer.addKeywordResult(Context, "virtual");
2720 }
2721 }
2722
2723 if (getLangOptions().CPlusPlus) {
2724 Consumer.addKeywordResult(Context, "using");
2725
2726 if (getLangOptions().CPlusPlus0x)
2727 Consumer.addKeywordResult(Context, "static_assert");
2728 }
2729 }
2730
2731 // If we haven't found anything, we're done.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002732 if (Consumer.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002733 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002734
2735 // Only allow a single, closest name in the result set (it's okay to
2736 // have overloads of that name, though).
Douglas Gregoraaf87162010-04-14 20:04:41 +00002737 DeclarationName BestName;
2738 NamedDecl *BestIvarOrPropertyDecl = 0;
2739 bool FoundIvarOrPropertyDecl = false;
2740
2741 // Check all of the declaration results to find the best name so far.
2742 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2743 IEnd = Consumer.end();
2744 I != IEnd; ++I) {
2745 if (!BestName)
2746 BestName = (*I)->getDeclName();
2747 else if (BestName != (*I)->getDeclName())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002748 return DeclarationName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002749
Douglas Gregoraaf87162010-04-14 20:04:41 +00002750 // \brief Keep track of either an Objective-C ivar or a property, but not
2751 // both.
2752 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
2753 if (FoundIvarOrPropertyDecl)
2754 BestIvarOrPropertyDecl = 0;
2755 else {
2756 BestIvarOrPropertyDecl = *I;
2757 FoundIvarOrPropertyDecl = true;
2758 }
2759 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002760 }
2761
Douglas Gregoraaf87162010-04-14 20:04:41 +00002762 // Now check all of the keyword results to find the best name.
2763 switch (Consumer.keyword_size()) {
2764 case 0:
2765 // No keywords matched.
2766 break;
2767
2768 case 1:
2769 // If we already have a name
2770 if (!BestName) {
2771 // We did not have anything previously,
2772 BestName = *Consumer.keyword_begin();
2773 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
2774 // We have a declaration with the same name as a context-sensitive
2775 // keyword. The keyword takes precedence.
2776 BestIvarOrPropertyDecl = 0;
2777 FoundIvarOrPropertyDecl = false;
2778 Consumer.clear_decls();
2779 } else {
2780 // Name collision; we will not correct typos.
2781 return DeclarationName();
2782 }
2783 break;
2784
2785 default:
2786 // Name collision; we will not correct typos.
2787 return DeclarationName();
2788 }
2789
Douglas Gregor546be3c2009-12-30 17:04:44 +00002790 // BestName is the closest viable name to what the user
2791 // typed. However, to make sure that we don't pick something that's
2792 // way off, make sure that the user typed at least 3 characters for
2793 // each correction.
2794 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002795 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
2796 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002797 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002798
2799 // Perform name lookup again with the name we chose, and declare
2800 // success if we found something that was not ambiguous.
2801 Res.clear();
2802 Res.setLookupName(BestName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002803
2804 // If we found an ivar or property, add that result; no further
2805 // lookup is required.
Douglas Gregoraaf87162010-04-14 20:04:41 +00002806 if (BestIvarOrPropertyDecl)
2807 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002808 // If we're looking into the context of a member, perform qualified
2809 // name lookup on the best name.
Douglas Gregoraaf87162010-04-14 20:04:41 +00002810 else if (!Consumer.keyword_empty()) {
2811 // The best match was a keyword. Return it.
2812 return BestName;
2813 } else if (MemberContext)
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002814 LookupQualifiedName(Res, MemberContext);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002815 // Perform lookup as if we had just parsed the best name.
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002816 else
2817 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2818 EnteringContext);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002819
2820 if (Res.isAmbiguous()) {
2821 Res.suppressDiagnostics();
Douglas Gregor931f98a2010-04-14 17:09:22 +00002822 return DeclarationName();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002823 }
2824
Douglas Gregor931f98a2010-04-14 17:09:22 +00002825 if (Res.getResultKind() != LookupResult::NotFound)
2826 return BestName;
2827
2828 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002829}