blob: 1b2401a80cb083e274614cd1e9775b7ec572c12e [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6e247262009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor546be3c2009-12-30 17:04:44 +000030#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000031#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000032#include <vector>
33#include <iterator>
34#include <utility>
35#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000036
37using namespace clang;
38
John McCalld7be78a2009-11-10 07:01:13 +000039namespace {
40 class UnqualUsingEntry {
41 const DeclContext *Nominated;
42 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000043
John McCalld7be78a2009-11-10 07:01:13 +000044 public:
45 UnqualUsingEntry(const DeclContext *Nominated,
46 const DeclContext *CommonAncestor)
47 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
48 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000049
John McCalld7be78a2009-11-10 07:01:13 +000050 const DeclContext *getCommonAncestor() const {
51 return CommonAncestor;
52 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000053
John McCalld7be78a2009-11-10 07:01:13 +000054 const DeclContext *getNominatedNamespace() const {
55 return Nominated;
56 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000057
John McCalld7be78a2009-11-10 07:01:13 +000058 // Sort by the pointer value of the common ancestor.
59 struct Comparator {
60 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
61 return L.getCommonAncestor() < R.getCommonAncestor();
62 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000063
John McCalld7be78a2009-11-10 07:01:13 +000064 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
65 return E.getCommonAncestor() < DC;
66 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000067
John McCalld7be78a2009-11-10 07:01:13 +000068 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
69 return DC < E.getCommonAncestor();
70 }
71 };
72 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000073
John McCalld7be78a2009-11-10 07:01:13 +000074 /// A collection of using directives, as used by C++ unqualified
75 /// lookup.
76 class UnqualUsingDirectiveSet {
77 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000078
John McCalld7be78a2009-11-10 07:01:13 +000079 ListTy list;
80 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000081
John McCalld7be78a2009-11-10 07:01:13 +000082 public:
83 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000084
John McCalld7be78a2009-11-10 07:01:13 +000085 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
86 // C++ [namespace.udir]p1:
87 // During unqualified name lookup, the names appear as if they
88 // were declared in the nearest enclosing namespace which contains
89 // both the using-directive and the nominated namespace.
90 DeclContext *InnermostFileDC
91 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
92 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +000093
John McCalld7be78a2009-11-10 07:01:13 +000094 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +000095 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
96 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
97 visit(Ctx, EffectiveDC);
98 } else {
99 Scope::udir_iterator I = S->using_directives_begin(),
100 End = S->using_directives_end();
101
102 for (; I != End; ++I)
103 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
104 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000105 }
106 }
John McCalld7be78a2009-11-10 07:01:13 +0000107
108 // Visits a context and collect all of its using directives
109 // recursively. Treats all using directives as if they were
110 // declared in the context.
111 //
112 // A given context is only every visited once, so it is important
113 // that contexts be visited from the inside out in order to get
114 // the effective DCs right.
115 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
116 if (!visited.insert(DC))
117 return;
118
119 addUsingDirectives(DC, EffectiveDC);
120 }
121
122 // Visits a using directive and collects all of its using
123 // directives recursively. Treats all using directives as if they
124 // were declared in the effective DC.
125 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
126 DeclContext *NS = UD->getNominatedNamespace();
127 if (!visited.insert(NS))
128 return;
129
130 addUsingDirective(UD, EffectiveDC);
131 addUsingDirectives(NS, EffectiveDC);
132 }
133
134 // Adds all the using directives in a context (and those nominated
135 // by its using directives, transitively) as if they appeared in
136 // the given effective context.
137 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
138 llvm::SmallVector<DeclContext*,4> queue;
139 while (true) {
140 DeclContext::udir_iterator I, End;
141 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
142 UsingDirectiveDecl *UD = *I;
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (visited.insert(NS)) {
145 addUsingDirective(UD, EffectiveDC);
146 queue.push_back(NS);
147 }
148 }
149
150 if (queue.empty())
151 return;
152
153 DC = queue.back();
154 queue.pop_back();
155 }
156 }
157
158 // Add a using directive as if it had been declared in the given
159 // context. This helps implement C++ [namespace.udir]p3:
160 // The using-directive is transitive: if a scope contains a
161 // using-directive that nominates a second namespace that itself
162 // contains using-directives, the effect is as if the
163 // using-directives from the second namespace also appeared in
164 // the first.
165 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
166 // Find the common ancestor between the effective context and
167 // the nominated namespace.
168 DeclContext *Common = UD->getNominatedNamespace();
169 while (!Common->Encloses(EffectiveDC))
170 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000171 Common = Common->getPrimaryContext();
John McCalld7be78a2009-11-10 07:01:13 +0000172
173 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
174 }
175
176 void done() {
177 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
178 }
179
180 typedef ListTy::iterator iterator;
181 typedef ListTy::const_iterator const_iterator;
182
183 iterator begin() { return list.begin(); }
184 iterator end() { return list.end(); }
185 const_iterator begin() const { return list.begin(); }
186 const_iterator end() const { return list.end(); }
187
188 std::pair<const_iterator,const_iterator>
189 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000190 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000191 UnqualUsingEntry::Comparator());
192 }
193 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000194}
195
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000196// Retrieve the set of identifier namespaces that correspond to a
197// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000198static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
199 bool CPlusPlus,
200 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000201 unsigned IDNS = 0;
202 switch (NameKind) {
203 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000204 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000205 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000206 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCall1d7c5282009-12-18 10:40:03 +0000208 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
209 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000210 break;
211
John McCall76d32642010-04-24 01:30:58 +0000212 case Sema::LookupOperatorName:
213 // Operator lookup is its own crazy thing; it is not the same
214 // as (e.g.) looking up an operator name for redeclaration.
215 assert(!Redeclaration && "cannot do redeclaration operator lookup");
216 IDNS = Decl::IDNS_NonMemberOperator;
217 break;
218
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000219 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000220 if (CPlusPlus) {
221 IDNS = Decl::IDNS_Type;
222
223 // When looking for a redeclaration of a tag name, we add:
224 // 1) TagFriend to find undeclared friend decls
225 // 2) Namespace because they can't "overload" with tag decls.
226 // 3) Tag because it includes class templates, which can't
227 // "overload" with tag decls.
228 if (Redeclaration)
229 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
230 } else {
231 IDNS = Decl::IDNS_Tag;
232 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000233 break;
234
235 case Sema::LookupMemberName:
236 IDNS = Decl::IDNS_Member;
237 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000238 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000239 break;
240
241 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000242 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
243 break;
244
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000245 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000246 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000247 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000248
John McCall9f54ad42009-12-10 09:41:52 +0000249 case Sema::LookupUsingDeclName:
250 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
251 | Decl::IDNS_Member | Decl::IDNS_Using;
252 break;
253
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000254 case Sema::LookupObjCProtocolName:
255 IDNS = Decl::IDNS_ObjCProtocol;
256 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000257 }
258 return IDNS;
259}
260
John McCall1d7c5282009-12-18 10:40:03 +0000261void LookupResult::configure() {
262 IDNS = getIDNS(LookupKind,
263 SemaRef.getLangOptions().CPlusPlus,
264 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000265
266 // If we're looking for one of the allocation or deallocation
267 // operators, make sure that the implicitly-declared new and delete
268 // operators can be found.
269 if (!isForRedeclaration()) {
270 switch (Name.getCXXOverloadedOperator()) {
271 case OO_New:
272 case OO_Delete:
273 case OO_Array_New:
274 case OO_Array_Delete:
275 SemaRef.DeclareGlobalNewDelete();
276 break;
277
278 default:
279 break;
280 }
281 }
John McCall1d7c5282009-12-18 10:40:03 +0000282}
283
John McCallf36e02d2009-10-09 21:13:30 +0000284// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000285void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000286 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000287}
288
John McCall7453ed42009-11-22 00:44:51 +0000289/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000290void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000291 unsigned N = Decls.size();
John McCall9f54ad42009-12-10 09:41:52 +0000292
John McCallf36e02d2009-10-09 21:13:30 +0000293 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000294 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000295 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000296 return;
297 }
298
John McCall7453ed42009-11-22 00:44:51 +0000299 // If there's a single decl, we need to examine it to decide what
300 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000301 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000302 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
303 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000304 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000305 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000306 ResultKind = FoundUnresolvedValue;
307 return;
308 }
John McCallf36e02d2009-10-09 21:13:30 +0000309
John McCall6e247262009-10-10 05:48:19 +0000310 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000311 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000312
John McCallf36e02d2009-10-09 21:13:30 +0000313 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
314
315 bool Ambiguous = false;
316 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000317 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000318
319 unsigned UniqueTagIndex = 0;
320
321 unsigned I = 0;
322 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000323 NamedDecl *D = Decls[I]->getUnderlyingDecl();
324 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000325
John McCall314be4e2009-11-17 07:50:12 +0000326 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000327 // If it's not unique, pull something off the back (and
328 // continue at this index).
329 Decls[I] = Decls[--N];
John McCallf36e02d2009-10-09 21:13:30 +0000330 } else {
331 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000332
333 if (isa<UnresolvedUsingValueDecl>(D)) {
334 HasUnresolved = true;
335 } else if (isa<TagDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000336 if (HasTag)
337 Ambiguous = true;
338 UniqueTagIndex = I;
339 HasTag = true;
John McCall7453ed42009-11-22 00:44:51 +0000340 } else if (isa<FunctionTemplateDecl>(D)) {
341 HasFunction = true;
342 HasFunctionTemplate = true;
343 } else if (isa<FunctionDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000344 HasFunction = true;
345 } else {
346 if (HasNonFunction)
347 Ambiguous = true;
348 HasNonFunction = true;
349 }
350 I++;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000351 }
Mike Stump1eb44332009-09-09 15:08:12 +0000352 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000353
John McCallf36e02d2009-10-09 21:13:30 +0000354 // C++ [basic.scope.hiding]p2:
355 // A class name or enumeration name can be hidden by the name of
356 // an object, function, or enumerator declared in the same
357 // scope. If a class or enumeration name and an object, function,
358 // or enumerator are declared in the same scope (in any order)
359 // with the same name, the class or enumeration name is hidden
360 // wherever the object, function, or enumerator name is visible.
361 // But it's still an error if there are distinct tag types found,
362 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000363 if (HideTags && HasTag && !Ambiguous &&
364 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000365 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000366
John McCallf36e02d2009-10-09 21:13:30 +0000367 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000368
John McCallfda8e122009-12-03 00:58:24 +0000369 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000370 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000371
John McCallf36e02d2009-10-09 21:13:30 +0000372 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000373 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000374 else if (HasUnresolved)
375 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000376 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000377 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000378 else
John McCalla24dc2e2009-11-17 02:14:36 +0000379 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000380}
381
John McCall7d384dd2009-11-18 07:57:50 +0000382void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000383 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000384 DeclContext::lookup_iterator DI, DE;
385 for (I = P.begin(), E = P.end(); I != E; ++I)
386 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
387 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000388}
389
John McCall7d384dd2009-11-18 07:57:50 +0000390void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000391 Paths = new CXXBasePaths;
392 Paths->swap(P);
393 addDeclsFromBasePaths(*Paths);
394 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000395 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000396}
397
John McCall7d384dd2009-11-18 07:57:50 +0000398void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000399 Paths = new CXXBasePaths;
400 Paths->swap(P);
401 addDeclsFromBasePaths(*Paths);
402 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000403 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000404}
405
John McCall7d384dd2009-11-18 07:57:50 +0000406void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000407 Out << Decls.size() << " result(s)";
408 if (isAmbiguous()) Out << ", ambiguous";
409 if (Paths) Out << ", base paths present";
410
411 for (iterator I = begin(), E = end(); I != E; ++I) {
412 Out << "\n";
413 (*I)->print(Out, 2);
414 }
415}
416
Douglas Gregor85910982010-02-12 05:48:04 +0000417/// \brief Lookup a builtin function, when name lookup would otherwise
418/// fail.
419static bool LookupBuiltin(Sema &S, LookupResult &R) {
420 Sema::LookupNameKind NameKind = R.getLookupKind();
421
422 // If we didn't find a use of this identifier, and if the identifier
423 // corresponds to a compiler builtin, create the decl object for the builtin
424 // now, injecting it into translation unit scope, and return it.
425 if (NameKind == Sema::LookupOrdinaryName ||
426 NameKind == Sema::LookupRedeclarationWithLinkage) {
427 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
428 if (II) {
429 // If this is a builtin on this (or all) targets, create the decl.
430 if (unsigned BuiltinID = II->getBuiltinID()) {
431 // In C++, we don't have any predefined library functions like
432 // 'malloc'. Instead, we'll just error.
433 if (S.getLangOptions().CPlusPlus &&
434 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
435 return false;
436
437 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
438 S.TUScope, R.isForRedeclaration(),
439 R.getNameLoc());
440 if (D)
441 R.addDecl(D);
442 return (D != NULL);
443 }
444 }
445 }
446
447 return false;
448}
449
John McCallf36e02d2009-10-09 21:13:30 +0000450// Adds all qualifying matches for a name within a decl context to the
451// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000452static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000453 bool Found = false;
454
John McCalld7be78a2009-11-10 07:01:13 +0000455 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000456 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000457 NamedDecl *D = *I;
458 if (R.isAcceptableDecl(D)) {
459 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000460 Found = true;
461 }
462 }
John McCallf36e02d2009-10-09 21:13:30 +0000463
Douglas Gregor85910982010-02-12 05:48:04 +0000464 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
465 return true;
466
Douglas Gregor48026d22010-01-11 18:40:55 +0000467 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000468 != DeclarationName::CXXConversionFunctionName ||
469 R.getLookupName().getCXXNameType()->isDependentType() ||
470 !isa<CXXRecordDecl>(DC))
471 return Found;
472
473 // C++ [temp.mem]p6:
474 // A specialization of a conversion function template is not found by
475 // name lookup. Instead, any conversion function templates visible in the
476 // context of the use are considered. [...]
477 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
478 if (!Record->isDefinition())
479 return Found;
480
481 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
482 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
483 UEnd = Unresolved->end(); U != UEnd; ++U) {
484 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
485 if (!ConvTemplate)
486 continue;
487
488 // When we're performing lookup for the purposes of redeclaration, just
489 // add the conversion function template. When we deduce template
490 // arguments for specializations, we'll end up unifying the return
491 // type of the new declaration with the type of the function template.
492 if (R.isForRedeclaration()) {
493 R.addDecl(ConvTemplate);
494 Found = true;
495 continue;
496 }
497
Douglas Gregor48026d22010-01-11 18:40:55 +0000498 // C++ [temp.mem]p6:
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000499 // [...] For each such operator, if argument deduction succeeds
500 // (14.9.2.3), the resulting specialization is used as if found by
501 // name lookup.
502 //
503 // When referencing a conversion function for any purpose other than
504 // a redeclaration (such that we'll be building an expression with the
505 // result), perform template argument deduction and place the
506 // specialization into the result set. We do this to avoid forcing all
507 // callers to perform special deduction for conversion functions.
John McCall5769d612010-02-08 23:07:23 +0000508 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000509 FunctionDecl *Specialization = 0;
510
511 const FunctionProtoType *ConvProto
512 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
513 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000514
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000515 // Compute the type of the function that we would expect the conversion
516 // function to have, if it were to match the name given.
517 // FIXME: Calling convention!
Rafael Espindola264ba482010-03-30 20:24:48 +0000518 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000519 QualType ExpectedType
520 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
521 0, 0, ConvProto->isVariadic(),
522 ConvProto->getTypeQuals(),
523 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000524 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000525
526 // Perform template argument deduction against the type that we would
527 // expect the function to have.
528 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
529 Specialization, Info)
530 == Sema::TDK_Success) {
531 R.addDecl(Specialization);
532 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000533 }
534 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000535
John McCallf36e02d2009-10-09 21:13:30 +0000536 return Found;
537}
538
John McCalld7be78a2009-11-10 07:01:13 +0000539// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000540static bool
Douglas Gregor85910982010-02-12 05:48:04 +0000541CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
542 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000543
544 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
545
John McCalld7be78a2009-11-10 07:01:13 +0000546 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000547 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000548
John McCalld7be78a2009-11-10 07:01:13 +0000549 // Perform direct name lookup into the namespaces nominated by the
550 // using directives whose common ancestor is this namespace.
551 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
552 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000553
John McCalld7be78a2009-11-10 07:01:13 +0000554 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000555 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000556 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000557
558 R.resolveKind();
559
560 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000561}
562
563static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000564 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000565 return Ctx->isFileContext();
566 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000567}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000568
Douglas Gregor711be1e2010-03-15 14:33:29 +0000569// Find the next outer declaration context from this scope. This
570// routine actually returns the semantic outer context, which may
571// differ from the lexical context (encoded directly in the Scope
572// stack) when we are parsing a member of a class template. In this
573// case, the second element of the pair will be true, to indicate that
574// name lookup should continue searching in this semantic context when
575// it leaves the current template parameter scope.
576static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
577 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
578 DeclContext *Lexical = 0;
579 for (Scope *OuterS = S->getParent(); OuterS;
580 OuterS = OuterS->getParent()) {
581 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000582 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000583 break;
584 }
585 }
586
587 // C++ [temp.local]p8:
588 // In the definition of a member of a class template that appears
589 // outside of the namespace containing the class template
590 // definition, the name of a template-parameter hides the name of
591 // a member of this namespace.
592 //
593 // Example:
594 //
595 // namespace N {
596 // class C { };
597 //
598 // template<class T> class B {
599 // void f(T);
600 // };
601 // }
602 //
603 // template<class C> void N::B<C>::f(C) {
604 // C b; // C is the template parameter, not N::C
605 // }
606 //
607 // In this example, the lexical context we return is the
608 // TranslationUnit, while the semantic context is the namespace N.
609 if (!Lexical || !DC || !S->getParent() ||
610 !S->getParent()->isTemplateParamScope())
611 return std::make_pair(Lexical, false);
612
613 // Find the outermost template parameter scope.
614 // For the example, this is the scope for the template parameters of
615 // template<class C>.
616 Scope *OutermostTemplateScope = S->getParent();
617 while (OutermostTemplateScope->getParent() &&
618 OutermostTemplateScope->getParent()->isTemplateParamScope())
619 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregore942bbe2009-09-10 16:57:35 +0000620
Douglas Gregor711be1e2010-03-15 14:33:29 +0000621 // Find the namespace context in which the original scope occurs. In
622 // the example, this is namespace N.
623 DeclContext *Semantic = DC;
624 while (!Semantic->isFileContext())
625 Semantic = Semantic->getParent();
626
627 // Find the declaration context just outside of the template
628 // parameter scope. This is the context in which the template is
629 // being lexically declaration (a namespace context). In the
630 // example, this is the global scope.
631 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
632 Lexical->Encloses(Semantic))
633 return std::make_pair(Semantic, true);
634
635 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000636}
637
John McCalla24dc2e2009-11-17 02:14:36 +0000638bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000639 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000640
641 DeclarationName Name = R.getLookupName();
642
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000643 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000644 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000645 I = IdResolver.begin(Name),
646 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000647
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000648 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000649 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000650 // ...During unqualified name lookup (3.4.1), the names appear as if
651 // they were declared in the nearest enclosing namespace which contains
652 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000653 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000654 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000655 //
656 // For example:
657 // namespace A { int i; }
658 // void foo() {
659 // int i;
660 // {
661 // using namespace A;
662 // ++i; // finds local 'i', A::i appears at global scope
663 // }
664 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000665 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000666 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000667 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000668 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000669 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000670 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000671 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000672 Found = true;
673 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000674 }
675 }
John McCallf36e02d2009-10-09 21:13:30 +0000676 if (Found) {
677 R.resolveKind();
678 return true;
679 }
680
Douglas Gregor711be1e2010-03-15 14:33:29 +0000681 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
682 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
683 S->getParent() && !S->getParent()->isTemplateParamScope()) {
684 // We've just searched the last template parameter scope and
685 // found nothing, so look into the the contexts between the
686 // lexical and semantic declaration contexts returned by
687 // findOuterContext(). This implements the name lookup behavior
688 // of C++ [temp.local]p8.
689 Ctx = OutsideOfTemplateParamDC;
690 OutsideOfTemplateParamDC = 0;
691 }
692
693 if (Ctx) {
694 DeclContext *OuterCtx;
695 bool SearchAfterTemplateScope;
696 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
697 if (SearchAfterTemplateScope)
698 OutsideOfTemplateParamDC = OuterCtx;
699
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000700 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000701 // We do not directly look into transparent contexts, since
702 // those entities will be found in the nearest enclosing
703 // non-transparent context.
704 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000705 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000706
707 // We do not look directly into function or method contexts,
708 // since all of the local variables and parameters of the
709 // function/method are present within the Scope.
710 if (Ctx->isFunctionOrMethod()) {
711 // If we have an Objective-C instance method, look for ivars
712 // in the corresponding interface.
713 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
714 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
715 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
716 ObjCInterfaceDecl *ClassDeclared;
717 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
718 Name.getAsIdentifierInfo(),
719 ClassDeclared)) {
720 if (R.isAcceptableDecl(Ivar)) {
721 R.addDecl(Ivar);
722 R.resolveKind();
723 return true;
724 }
725 }
726 }
727 }
728
729 continue;
730 }
731
Douglas Gregore942bbe2009-09-10 16:57:35 +0000732 // Perform qualified name lookup into this context.
733 // FIXME: In some cases, we know that every name that could be found by
734 // this qualified name lookup will also be on the identifier chain. For
735 // example, inside a class without any base classes, we never need to
736 // perform qualified lookup because all of the members are on top of the
737 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000738 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000739 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000740 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000741 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000742 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000743
John McCalld7be78a2009-11-10 07:01:13 +0000744 // Stop if we ran out of scopes.
745 // FIXME: This really, really shouldn't be happening.
746 if (!S) return false;
747
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000748 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000749 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000750 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000751 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
752 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000753
John McCalld7be78a2009-11-10 07:01:13 +0000754 UnqualUsingDirectiveSet UDirs;
755 UDirs.visitScopeChain(Initial, S);
756 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000757
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000758 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000759 // Unqualified name lookup in C++ requires looking into scopes
760 // that aren't strictly lexical, and therefore we walk through the
761 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000762
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000763 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000764 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000765 if (Ctx && Ctx->isTransparentContext())
Douglas Gregora24eb4e2009-08-24 18:55:03 +0000766 continue;
767
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000768 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000769 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000770 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000771 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000772 // We found something. Look for anything else in our scope
773 // with this same name and in an acceptable identifier
774 // namespace, so that we can construct an overload set if we
775 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000776 Found = true;
777 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000778 }
779 }
780
Douglas Gregor711be1e2010-03-15 14:33:29 +0000781 // If we have a context, and it's not a context stashed in the
782 // template parameter scope for an out-of-line definition, also
783 // look into that context.
784 if (Ctx && !(Found && S && S->isTemplateParamScope())) {
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000785 assert(Ctx->isFileContext() &&
786 "We should have been looking only at file context here already.");
787
788 // Look into context considering using-directives.
Douglas Gregor85910982010-02-12 05:48:04 +0000789 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000790 Found = true;
791 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000792
John McCallf36e02d2009-10-09 21:13:30 +0000793 if (Found) {
794 R.resolveKind();
795 return true;
796 }
797
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000798 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000799 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000800 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000801
John McCallf36e02d2009-10-09 21:13:30 +0000802 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000803}
804
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000805/// @brief Perform unqualified name lookup starting from a given
806/// scope.
807///
808/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
809/// used to find names within the current scope. For example, 'x' in
810/// @code
811/// int x;
812/// int f() {
813/// return x; // unqualified name look finds 'x' in the global scope
814/// }
815/// @endcode
816///
817/// Different lookup criteria can find different names. For example, a
818/// particular scope can have both a struct and a function of the same
819/// name, and each can be found by certain lookup criteria. For more
820/// information about lookup criteria, see the documentation for the
821/// class LookupCriteria.
822///
823/// @param S The scope from which unqualified name lookup will
824/// begin. If the lookup criteria permits, name lookup may also search
825/// in the parent scopes.
826///
827/// @param Name The name of the entity that we are searching for.
828///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000829/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +0000830/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +0000831/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000832///
833/// @returns The result of name lookup, which includes zero or more
834/// declarations and possibly additional information used to diagnose
835/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000836bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
837 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +0000838 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000839
John McCalla24dc2e2009-11-17 02:14:36 +0000840 LookupNameKind NameKind = R.getLookupKind();
841
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000842 if (!getLangOptions().CPlusPlus) {
843 // Unqualified name lookup in C/Objective-C is purely lexical, so
844 // search in the declarations attached to the name.
845
John McCall1d7c5282009-12-18 10:40:03 +0000846 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000847 // Find the nearest non-transparent declaration scope.
848 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000849 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000850 static_cast<DeclContext *>(S->getEntity())
851 ->isTransparentContext()))
852 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000853 }
854
John McCall1d7c5282009-12-18 10:40:03 +0000855 unsigned IDNS = R.getIdentifierNamespace();
856
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000857 // Scan up the scope chain looking for a decl that matches this
858 // identifier that is in the appropriate namespace. This search
859 // should not take long, as shadowing of names is uncommon, and
860 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000861 bool LeftStartingScope = false;
862
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000863 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +0000864 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000865 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000866 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000867 if (NameKind == LookupRedeclarationWithLinkage) {
868 // Determine whether this (or a previous) declaration is
869 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000870 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000871 LeftStartingScope = true;
872
873 // If we found something outside of our starting scope that
874 // does not have linkage, skip it.
875 if (LeftStartingScope && !((*I)->hasLinkage()))
876 continue;
877 }
878
John McCallf36e02d2009-10-09 21:13:30 +0000879 R.addDecl(*I);
880
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000881 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000882 // If this declaration has the "overloadable" attribute, we
883 // might have a set of overloaded functions.
884
885 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000886 while (!(S->getFlags() & Scope::DeclScope) ||
887 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000888 S = S->getParent();
889
890 // Find the last declaration in this scope (with the same
891 // name, naturally).
892 IdentifierResolver::iterator LastI = I;
893 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000894 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000895 break;
John McCallf36e02d2009-10-09 21:13:30 +0000896 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000897 }
Douglas Gregorf9201e02009-02-11 23:02:49 +0000898 }
899
John McCallf36e02d2009-10-09 21:13:30 +0000900 R.resolveKind();
901
902 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000903 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000904 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000905 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000906 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +0000907 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000908 }
909
910 // If we didn't find a use of this identifier, and if the identifier
911 // corresponds to a compiler builtin, create the decl object for the builtin
912 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +0000913 if (AllowBuiltinCreation)
914 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000915
John McCallf36e02d2009-10-09 21:13:30 +0000916 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000917}
918
John McCall6e247262009-10-10 05:48:19 +0000919/// @brief Perform qualified name lookup in the namespaces nominated by
920/// using directives by the given context.
921///
922/// C++98 [namespace.qual]p2:
923/// Given X::m (where X is a user-declared namespace), or given ::m
924/// (where X is the global namespace), let S be the set of all
925/// declarations of m in X and in the transitive closure of all
926/// namespaces nominated by using-directives in X and its used
927/// namespaces, except that using-directives are ignored in any
928/// namespace, including X, directly containing one or more
929/// declarations of m. No namespace is searched more than once in
930/// the lookup of a name. If S is the empty set, the program is
931/// ill-formed. Otherwise, if S has exactly one member, or if the
932/// context of the reference is a using-declaration
933/// (namespace.udecl), S is the required set of declarations of
934/// m. Otherwise if the use of m is not one that allows a unique
935/// declaration to be chosen from S, the program is ill-formed.
936/// C++98 [namespace.qual]p5:
937/// During the lookup of a qualified namespace member name, if the
938/// lookup finds more than one declaration of the member, and if one
939/// declaration introduces a class name or enumeration name and the
940/// other declarations either introduce the same object, the same
941/// enumerator or a set of functions, the non-type name hides the
942/// class or enumeration name if and only if the declarations are
943/// from the same namespace; otherwise (the declarations are from
944/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +0000945static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +0000946 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +0000947 assert(StartDC->isFileContext() && "start context is not a file context");
948
949 DeclContext::udir_iterator I = StartDC->using_directives_begin();
950 DeclContext::udir_iterator E = StartDC->using_directives_end();
951
952 if (I == E) return false;
953
954 // We have at least added all these contexts to the queue.
955 llvm::DenseSet<DeclContext*> Visited;
956 Visited.insert(StartDC);
957
958 // We have not yet looked into these namespaces, much less added
959 // their "using-children" to the queue.
960 llvm::SmallVector<NamespaceDecl*, 8> Queue;
961
962 // We have already looked into the initial namespace; seed the queue
963 // with its using-children.
964 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +0000965 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +0000966 if (Visited.insert(ND).second)
967 Queue.push_back(ND);
968 }
969
970 // The easiest way to implement the restriction in [namespace.qual]p5
971 // is to check whether any of the individual results found a tag
972 // and, if so, to declare an ambiguity if the final result is not
973 // a tag.
974 bool FoundTag = false;
975 bool FoundNonTag = false;
976
John McCall7d384dd2009-11-18 07:57:50 +0000977 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +0000978
979 bool Found = false;
980 while (!Queue.empty()) {
981 NamespaceDecl *ND = Queue.back();
982 Queue.pop_back();
983
984 // We go through some convolutions here to avoid copying results
985 // between LookupResults.
986 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +0000987 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +0000988 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +0000989
990 if (FoundDirect) {
991 // First do any local hiding.
992 DirectR.resolveKind();
993
994 // If the local result is a tag, remember that.
995 if (DirectR.isSingleTagDecl())
996 FoundTag = true;
997 else
998 FoundNonTag = true;
999
1000 // Append the local results to the total results if necessary.
1001 if (UseLocal) {
1002 R.addAllDecls(LocalR);
1003 LocalR.clear();
1004 }
1005 }
1006
1007 // If we find names in this namespace, ignore its using directives.
1008 if (FoundDirect) {
1009 Found = true;
1010 continue;
1011 }
1012
1013 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1014 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1015 if (Visited.insert(Nom).second)
1016 Queue.push_back(Nom);
1017 }
1018 }
1019
1020 if (Found) {
1021 if (FoundTag && FoundNonTag)
1022 R.setAmbiguousQualifiedTagHiding();
1023 else
1024 R.resolveKind();
1025 }
1026
1027 return Found;
1028}
1029
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001030/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001031///
1032/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1033/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001034/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001035///
1036/// Different lookup criteria can find different names. For example, a
1037/// particular scope can have both a struct and a function of the same
1038/// name, and each can be found by certain lookup criteria. For more
1039/// information about lookup criteria, see the documentation for the
1040/// class LookupCriteria.
1041///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001042/// \param R captures both the lookup criteria and any lookup results found.
1043///
1044/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001045/// search. If the lookup criteria permits, name lookup may also search
1046/// in the parent contexts or (for C++ classes) base classes.
1047///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001048/// \param InUnqualifiedLookup true if this is qualified name lookup that
1049/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001050///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001051/// \returns true if lookup succeeded, false if it failed.
1052bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1053 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001054 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001055
John McCalla24dc2e2009-11-17 02:14:36 +00001056 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001057 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001059 // Make sure that the declaration context is complete.
1060 assert((!isa<TagDecl>(LookupCtx) ||
1061 LookupCtx->isDependentContext() ||
1062 cast<TagDecl>(LookupCtx)->isDefinition() ||
1063 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1064 ->isBeingDefined()) &&
1065 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001067 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001068 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001069 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001070 if (isa<CXXRecordDecl>(LookupCtx))
1071 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001072 return true;
1073 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001074
John McCall6e247262009-10-10 05:48:19 +00001075 // Don't descend into implied contexts for redeclarations.
1076 // C++98 [namespace.qual]p6:
1077 // In a declaration for a namespace member in which the
1078 // declarator-id is a qualified-id, given that the qualified-id
1079 // for the namespace member has the form
1080 // nested-name-specifier unqualified-id
1081 // the unqualified-id shall name a member of the namespace
1082 // designated by the nested-name-specifier.
1083 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001084 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001085 return false;
1086
John McCalla24dc2e2009-11-17 02:14:36 +00001087 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001088 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001089 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001090
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001091 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001092 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001093 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1094 if (!LookupRec)
John McCallf36e02d2009-10-09 21:13:30 +00001095 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001096
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001097 // If we're performing qualified name lookup into a dependent class,
1098 // then we are actually looking into a current instantiation. If we have any
1099 // dependent base classes, then we either have to delay lookup until
1100 // template instantiation time (at which point all bases will be available)
1101 // or we have to fail.
1102 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1103 LookupRec->hasAnyDependentBases()) {
1104 R.setNotFoundInCurrentInstantiation();
1105 return false;
1106 }
1107
Douglas Gregor7176fff2009-01-15 00:26:24 +00001108 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001109 CXXBasePaths Paths;
1110 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001111
1112 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001113 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001114 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001115 case LookupOrdinaryName:
1116 case LookupMemberName:
1117 case LookupRedeclarationWithLinkage:
1118 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1119 break;
1120
1121 case LookupTagName:
1122 BaseCallback = &CXXRecordDecl::FindTagMember;
1123 break;
John McCall9f54ad42009-12-10 09:41:52 +00001124
1125 case LookupUsingDeclName:
1126 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001127
1128 case LookupOperatorName:
1129 case LookupNamespaceName:
1130 case LookupObjCProtocolName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001131 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001132 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001133
1134 case LookupNestedNameSpecifierName:
1135 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1136 break;
1137 }
1138
John McCalla24dc2e2009-11-17 02:14:36 +00001139 if (!LookupRec->lookupInBases(BaseCallback,
1140 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001141 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001142
John McCall92f88312010-01-23 00:46:32 +00001143 R.setNamingClass(LookupRec);
1144
Douglas Gregor7176fff2009-01-15 00:26:24 +00001145 // C++ [class.member.lookup]p2:
1146 // [...] If the resulting set of declarations are not all from
1147 // sub-objects of the same type, or the set has a nonstatic member
1148 // and includes members from distinct sub-objects, there is an
1149 // ambiguity and the program is ill-formed. Otherwise that set is
1150 // the result of the lookup.
1151 // FIXME: support using declarations!
1152 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001153 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001154 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001155 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001156 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001157 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001158
John McCall46460a62010-01-20 21:53:11 +00001159 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1160 // across all paths.
1161 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1162
Douglas Gregor7176fff2009-01-15 00:26:24 +00001163 // Determine whether we're looking at a distinct sub-object or not.
1164 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001165 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001166 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1167 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00001168 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001169 != Context.getCanonicalType(PathElement.Base->getType())) {
1170 // We found members of the given name in two subobjects of
1171 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001172 R.setAmbiguousBaseSubobjectTypes(Paths);
1173 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001174 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1175 // We have a different subobject of the same type.
1176
1177 // C++ [class.member.lookup]p5:
1178 // A static member, a nested type or an enumerator defined in
1179 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001180 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001181 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001182 if (isa<VarDecl>(FirstDecl) ||
1183 isa<TypeDecl>(FirstDecl) ||
1184 isa<EnumConstantDecl>(FirstDecl))
1185 continue;
1186
1187 if (isa<CXXMethodDecl>(FirstDecl)) {
1188 // Determine whether all of the methods are static.
1189 bool AllMethodsAreStatic = true;
1190 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1191 Func != Path->Decls.second; ++Func) {
1192 if (!isa<CXXMethodDecl>(*Func)) {
1193 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1194 break;
1195 }
1196
1197 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1198 AllMethodsAreStatic = false;
1199 break;
1200 }
1201 }
1202
1203 if (AllMethodsAreStatic)
1204 continue;
1205 }
1206
1207 // We have found a nonstatic member name in multiple, distinct
1208 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001209 R.setAmbiguousBaseSubobjects(Paths);
1210 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001211 }
1212 }
1213
1214 // Lookup in a base class succeeded; return these results.
1215
John McCallf36e02d2009-10-09 21:13:30 +00001216 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001217 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1218 NamedDecl *D = *I;
1219 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1220 D->getAccess());
1221 R.addDecl(D, AS);
1222 }
John McCallf36e02d2009-10-09 21:13:30 +00001223 R.resolveKind();
1224 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001225}
1226
1227/// @brief Performs name lookup for a name that was parsed in the
1228/// source code, and may contain a C++ scope specifier.
1229///
1230/// This routine is a convenience routine meant to be called from
1231/// contexts that receive a name and an optional C++ scope specifier
1232/// (e.g., "N::M::x"). It will then perform either qualified or
1233/// unqualified name lookup (with LookupQualifiedName or LookupName,
1234/// respectively) on the given name and return those results.
1235///
1236/// @param S The scope from which unqualified name lookup will
1237/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001238///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001239/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001240///
1241/// @param Name The name of the entity that name lookup will
1242/// search for.
1243///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001244/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001245/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001246/// C library functions (like "malloc") are implicitly declared.
1247///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001248/// @param EnteringContext Indicates whether we are going to enter the
1249/// context of the scope-specifier SS (if present).
1250///
John McCallf36e02d2009-10-09 21:13:30 +00001251/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001252bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001253 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001254 if (SS && SS->isInvalid()) {
1255 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001256 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001257 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001258 }
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Douglas Gregor495c35d2009-08-25 22:51:20 +00001260 if (SS && SS->isSet()) {
1261 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001262 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001263 // contex, and will perform name lookup in that context.
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001264 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCallf36e02d2009-10-09 21:13:30 +00001265 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001266
John McCalla24dc2e2009-11-17 02:14:36 +00001267 R.setContextRange(SS->getRange());
1268
1269 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001270 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001271
Douglas Gregor495c35d2009-08-25 22:51:20 +00001272 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001273 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001274 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001275 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001276 }
1277
Mike Stump1eb44332009-09-09 15:08:12 +00001278 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001279 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001280}
1281
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001282
Douglas Gregor7176fff2009-01-15 00:26:24 +00001283/// @brief Produce a diagnostic describing the ambiguity that resulted
1284/// from name lookup.
1285///
1286/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001287///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001288/// @param Name The name of the entity that name lookup was
1289/// searching for.
1290///
1291/// @param NameLoc The location of the name within the source code.
1292///
1293/// @param LookupRange A source range that provides more
1294/// source-location information concerning the lookup itself. For
1295/// example, this range might highlight a nested-name-specifier that
1296/// precedes the name.
1297///
1298/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001299bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001300 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1301
John McCalla24dc2e2009-11-17 02:14:36 +00001302 DeclarationName Name = Result.getLookupName();
1303 SourceLocation NameLoc = Result.getNameLoc();
1304 SourceRange LookupRange = Result.getContextRange();
1305
John McCall6e247262009-10-10 05:48:19 +00001306 switch (Result.getAmbiguityKind()) {
1307 case LookupResult::AmbiguousBaseSubobjects: {
1308 CXXBasePaths *Paths = Result.getBasePaths();
1309 QualType SubobjectType = Paths->front().back().Base->getType();
1310 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1311 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1312 << LookupRange;
1313
1314 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1315 while (isa<CXXMethodDecl>(*Found) &&
1316 cast<CXXMethodDecl>(*Found)->isStatic())
1317 ++Found;
1318
1319 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1320
1321 return true;
1322 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001323
John McCall6e247262009-10-10 05:48:19 +00001324 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001325 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1326 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001327
1328 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001329 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001330 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1331 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001332 Path != PathEnd; ++Path) {
1333 Decl *D = *Path->Decls.first;
1334 if (DeclsPrinted.insert(D).second)
1335 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1336 }
1337
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001338 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001339 }
1340
John McCall6e247262009-10-10 05:48:19 +00001341 case LookupResult::AmbiguousTagHiding: {
1342 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001343
John McCall6e247262009-10-10 05:48:19 +00001344 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1345
1346 LookupResult::iterator DI, DE = Result.end();
1347 for (DI = Result.begin(); DI != DE; ++DI)
1348 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1349 TagDecls.insert(TD);
1350 Diag(TD->getLocation(), diag::note_hidden_tag);
1351 }
1352
1353 for (DI = Result.begin(); DI != DE; ++DI)
1354 if (!isa<TagDecl>(*DI))
1355 Diag((*DI)->getLocation(), diag::note_hiding_object);
1356
1357 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001358 LookupResult::Filter F = Result.makeFilter();
1359 while (F.hasNext()) {
1360 if (TagDecls.count(F.next()))
1361 F.erase();
1362 }
1363 F.done();
John McCall6e247262009-10-10 05:48:19 +00001364
1365 return true;
1366 }
1367
1368 case LookupResult::AmbiguousReference: {
1369 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001370
John McCall6e247262009-10-10 05:48:19 +00001371 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1372 for (; DI != DE; ++DI)
1373 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001374
John McCall6e247262009-10-10 05:48:19 +00001375 return true;
1376 }
1377 }
1378
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001379 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001380 return true;
1381}
Douglas Gregorfa047642009-02-04 00:32:51 +00001382
Mike Stump1eb44332009-09-09 15:08:12 +00001383static void
1384addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001385 ASTContext &Context,
1386 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001387 Sema::AssociatedClassSet &AssociatedClasses);
1388
1389static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1390 DeclContext *Ctx) {
1391 if (Ctx->isFileContext())
1392 Namespaces.insert(Ctx);
1393}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001394
Mike Stump1eb44332009-09-09 15:08:12 +00001395// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001396// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001397static void
1398addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001399 ASTContext &Context,
1400 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001401 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001402 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001403 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001404 switch (Arg.getKind()) {
1405 case TemplateArgument::Null:
1406 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Douglas Gregor69be8d62009-07-08 07:51:57 +00001408 case TemplateArgument::Type:
1409 // [...] the namespaces and classes associated with the types of the
1410 // template arguments provided for template type parameters (excluding
1411 // template template parameters)
1412 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1413 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001414 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001415 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Douglas Gregor788cd062009-11-11 01:00:40 +00001417 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001418 // [...] the namespaces in which any template template arguments are
1419 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001420 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001421 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001422 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001423 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001424 DeclContext *Ctx = ClassTemplate->getDeclContext();
1425 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1426 AssociatedClasses.insert(EnclosingClass);
1427 // Add the associated namespace for this class.
1428 while (Ctx->isRecord())
1429 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001430 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001431 }
1432 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001433 }
1434
1435 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001436 case TemplateArgument::Integral:
1437 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001438 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001439 // associated namespaces. ]
1440 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Douglas Gregor69be8d62009-07-08 07:51:57 +00001442 case TemplateArgument::Pack:
1443 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1444 PEnd = Arg.pack_end();
1445 P != PEnd; ++P)
1446 addAssociatedClassesAndNamespaces(*P, Context,
1447 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001448 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001449 break;
1450 }
1451}
1452
Douglas Gregorfa047642009-02-04 00:32:51 +00001453// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001454// argument-dependent lookup with an argument of class type
1455// (C++ [basic.lookup.koenig]p2).
1456static void
1457addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregorfa047642009-02-04 00:32:51 +00001458 ASTContext &Context,
1459 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001460 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001461 // C++ [basic.lookup.koenig]p2:
1462 // [...]
1463 // -- If T is a class type (including unions), its associated
1464 // classes are: the class itself; the class of which it is a
1465 // member, if any; and its direct and indirect base
1466 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001467 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001468
1469 // Add the class of which it is a member, if any.
1470 DeclContext *Ctx = Class->getDeclContext();
1471 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1472 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001473 // Add the associated namespace for this class.
1474 while (Ctx->isRecord())
1475 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001476 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Douglas Gregorfa047642009-02-04 00:32:51 +00001478 // Add the class itself. If we've already seen this class, we don't
1479 // need to visit base classes.
1480 if (!AssociatedClasses.insert(Class))
1481 return;
1482
Mike Stump1eb44332009-09-09 15:08:12 +00001483 // -- If T is a template-id, its associated namespaces and classes are
1484 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001485 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001486 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001487 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001488 // namespaces in which any template template arguments are defined; and
1489 // the classes in which any member templates used as template template
1490 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001491 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001492 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001493 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1494 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1495 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1496 AssociatedClasses.insert(EnclosingClass);
1497 // Add the associated namespace for this class.
1498 while (Ctx->isRecord())
1499 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001500 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Douglas Gregor69be8d62009-07-08 07:51:57 +00001502 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1503 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1504 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1505 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001506 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001507 }
Mike Stump1eb44332009-09-09 15:08:12 +00001508
John McCall86ff3082010-02-04 22:26:26 +00001509 // Only recurse into base classes for complete types.
1510 if (!Class->hasDefinition()) {
1511 // FIXME: we might need to instantiate templates here
1512 return;
1513 }
1514
Douglas Gregorfa047642009-02-04 00:32:51 +00001515 // Add direct and indirect base classes along with their associated
1516 // namespaces.
1517 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1518 Bases.push_back(Class);
1519 while (!Bases.empty()) {
1520 // Pop this class off the stack.
1521 Class = Bases.back();
1522 Bases.pop_back();
1523
1524 // Visit the base classes.
1525 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1526 BaseEnd = Class->bases_end();
1527 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001528 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001529 // In dependent contexts, we do ADL twice, and the first time around,
1530 // the base type might be a dependent TemplateSpecializationType, or a
1531 // TemplateTypeParmType. If that happens, simply ignore it.
1532 // FIXME: If we want to support export, we probably need to add the
1533 // namespace of the template in a TemplateSpecializationType, or even
1534 // the classes and namespaces of known non-dependent arguments.
1535 if (!BaseType)
1536 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001537 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1538 if (AssociatedClasses.insert(BaseDecl)) {
1539 // Find the associated namespace for this base class.
1540 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1541 while (BaseCtx->isRecord())
1542 BaseCtx = BaseCtx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001543 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001544
1545 // Make sure we visit the bases of this base class.
1546 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1547 Bases.push_back(BaseDecl);
1548 }
1549 }
1550 }
1551}
1552
1553// \brief Add the associated classes and namespaces for
1554// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001555// (C++ [basic.lookup.koenig]p2).
1556static void
1557addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregorfa047642009-02-04 00:32:51 +00001558 ASTContext &Context,
1559 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001560 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001561 // C++ [basic.lookup.koenig]p2:
1562 //
1563 // For each argument type T in the function call, there is a set
1564 // of zero or more associated namespaces and a set of zero or more
1565 // associated classes to be considered. The sets of namespaces and
1566 // classes is determined entirely by the types of the function
1567 // arguments (and the namespace of any template template
1568 // argument). Typedef names and using-declarations used to specify
1569 // the types do not contribute to this set. The sets of namespaces
1570 // and classes are determined in the following way:
1571 T = Context.getCanonicalType(T).getUnqualifiedType();
1572
1573 // -- If T is a pointer to U or an array of U, its associated
Mike Stump1eb44332009-09-09 15:08:12 +00001574 // namespaces and classes are those associated with U.
Douglas Gregorfa047642009-02-04 00:32:51 +00001575 //
1576 // We handle this by unwrapping pointer and array types immediately,
1577 // to avoid unnecessary recursion.
1578 while (true) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001579 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001580 T = Ptr->getPointeeType();
1581 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1582 T = Ptr->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001583 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001584 break;
1585 }
1586
1587 // -- If T is a fundamental type, its associated sets of
1588 // namespaces and classes are both empty.
John McCall183700f2009-09-21 23:43:11 +00001589 if (T->getAs<BuiltinType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001590 return;
1591
1592 // -- If T is a class type (including unions), its associated
1593 // classes are: the class itself; the class of which it is a
1594 // member, if any; and its direct and indirect base
1595 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001596 // which its associated classes are defined.
Ted Kremenek6217b802009-07-29 21:53:49 +00001597 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001598 if (CXXRecordDecl *ClassDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001599 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001600 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1601 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001602 AssociatedClasses);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001603 return;
1604 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001605
1606 // -- If T is an enumeration type, its associated namespace is
1607 // the namespace in which it is defined. If it is class
1608 // member, its associated class is the member’s class; else
Mike Stump1eb44332009-09-09 15:08:12 +00001609 // it has no associated class.
John McCall183700f2009-09-21 23:43:11 +00001610 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001611 EnumDecl *Enum = EnumT->getDecl();
1612
1613 DeclContext *Ctx = Enum->getDeclContext();
1614 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1615 AssociatedClasses.insert(EnclosingClass);
1616
1617 // Add the associated namespace for this class.
1618 while (Ctx->isRecord())
1619 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001620 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001621
1622 return;
1623 }
1624
1625 // -- If T is a function type, its associated namespaces and
1626 // classes are those associated with the function parameter
1627 // types and those associated with the return type.
John McCall183700f2009-09-21 23:43:11 +00001628 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001629 // Return type
John McCall183700f2009-09-21 23:43:11 +00001630 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001631 Context,
John McCall6ff07852009-08-07 22:18:02 +00001632 AssociatedNamespaces, AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001633
John McCall183700f2009-09-21 23:43:11 +00001634 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001635 if (!Proto)
1636 return;
1637
1638 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001639 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001640 ArgEnd = Proto->arg_type_end();
Douglas Gregorfa047642009-02-04 00:32:51 +00001641 Arg != ArgEnd; ++Arg)
1642 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCall6ff07852009-08-07 22:18:02 +00001643 AssociatedNamespaces, AssociatedClasses);
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Douglas Gregorfa047642009-02-04 00:32:51 +00001645 return;
1646 }
1647
1648 // -- If T is a pointer to a member function of a class X, its
1649 // associated namespaces and classes are those associated
1650 // with the function parameter types and return type,
Mike Stump1eb44332009-09-09 15:08:12 +00001651 // together with those associated with X.
Douglas Gregorfa047642009-02-04 00:32:51 +00001652 //
1653 // -- If T is a pointer to a data member of class X, its
1654 // associated namespaces and classes are those associated
1655 // with the member type together with those associated with
Mike Stump1eb44332009-09-09 15:08:12 +00001656 // X.
Ted Kremenek6217b802009-07-29 21:53:49 +00001657 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001658 // Handle the type that the pointer to member points to.
1659 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1660 Context,
John McCall6ff07852009-08-07 22:18:02 +00001661 AssociatedNamespaces,
1662 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001663
1664 // Handle the class type into which this points.
Ted Kremenek6217b802009-07-29 21:53:49 +00001665 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001666 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1667 Context,
John McCall6ff07852009-08-07 22:18:02 +00001668 AssociatedNamespaces,
1669 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001670
1671 return;
1672 }
1673
1674 // FIXME: What about block pointers?
1675 // FIXME: What about Objective-C message sends?
1676}
1677
1678/// \brief Find the associated classes and namespaces for
1679/// argument-dependent lookup for a call with the given set of
1680/// arguments.
1681///
1682/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001683/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001684/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001685void
Douglas Gregorfa047642009-02-04 00:32:51 +00001686Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1687 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001688 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001689 AssociatedNamespaces.clear();
1690 AssociatedClasses.clear();
1691
1692 // C++ [basic.lookup.koenig]p2:
1693 // For each argument type T in the function call, there is a set
1694 // of zero or more associated namespaces and a set of zero or more
1695 // associated classes to be considered. The sets of namespaces and
1696 // classes is determined entirely by the types of the function
1697 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001698 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001699 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1700 Expr *Arg = Args[ArgIdx];
1701
1702 if (Arg->getType() != Context.OverloadTy) {
1703 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001704 AssociatedNamespaces,
1705 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001706 continue;
1707 }
1708
1709 // [...] In addition, if the argument is the name or address of a
1710 // set of overloaded functions and/or function templates, its
1711 // associated classes and namespaces are the union of those
1712 // associated with each of the members of the set: the namespace
1713 // in which the function or function template is defined and the
1714 // classes and namespaces associated with its (non-dependent)
1715 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001716 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001717 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1718 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1719 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001720
John McCallba135432009-11-21 08:51:07 +00001721 // TODO: avoid the copies. This should be easy when the cases
1722 // share a storage implementation.
1723 llvm::SmallVector<NamedDecl*, 8> Functions;
1724
1725 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1726 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00001727 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001728 continue;
1729
John McCallba135432009-11-21 08:51:07 +00001730 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1731 E = Functions.end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001732 // Look through any using declarations to find the underlying function.
1733 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001734
Chandler Carruthbd647292009-12-29 06:17:27 +00001735 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1736 if (!FDecl)
1737 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001738
1739 // Add the classes and namespaces associated with the parameter
1740 // types and return type of this function.
1741 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001742 AssociatedNamespaces,
1743 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001744 }
1745 }
1746}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001747
1748/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1749/// an acceptable non-member overloaded operator for a call whose
1750/// arguments have types T1 (and, if non-empty, T2). This routine
1751/// implements the check in C++ [over.match.oper]p3b2 concerning
1752/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001753static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001754IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1755 QualType T1, QualType T2,
1756 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001757 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1758 return true;
1759
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001760 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1761 return true;
1762
John McCall183700f2009-09-21 23:43:11 +00001763 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001764 if (Proto->getNumArgs() < 1)
1765 return false;
1766
1767 if (T1->isEnumeralType()) {
1768 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001769 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001770 return true;
1771 }
1772
1773 if (Proto->getNumArgs() < 2)
1774 return false;
1775
1776 if (!T2.isNull() && T2->isEnumeralType()) {
1777 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001778 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001779 return true;
1780 }
1781
1782 return false;
1783}
1784
John McCall7d384dd2009-11-18 07:57:50 +00001785NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00001786 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00001787 LookupNameKind NameKind,
1788 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00001789 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00001790 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00001791 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00001792}
1793
Douglas Gregor6e378de2009-04-23 23:18:26 +00001794/// \brief Find the protocol with the given name, if any.
Douglas Gregorc83c6872010-04-15 22:33:43 +00001795ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
1796 SourceLocation IdLoc) {
1797 Decl *D = LookupSingleName(TUScope, II, IdLoc,
1798 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001799 return cast_or_null<ObjCProtocolDecl>(D);
1800}
1801
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001802void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001803 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00001804 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001805 // C++ [over.match.oper]p3:
1806 // -- The set of non-member candidates is the result of the
1807 // unqualified lookup of operator@ in the context of the
1808 // expression according to the usual rules for name lookup in
1809 // unqualified function calls (3.4.2) except that all member
1810 // functions are ignored. However, if no operand has a class
1811 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00001812 // that have a first parameter of type T1 or "reference to
1813 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001814 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00001815 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001816 // when T2 is an enumeration type, are candidate functions.
1817 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00001818 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1819 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001821 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1822
John McCallf36e02d2009-10-09 21:13:30 +00001823 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001824 return;
1825
1826 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1827 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001828 NamedDecl *Found = (*Op)->getUnderlyingDecl();
1829 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001830 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001831 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00001832 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001833 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001834 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00001835 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00001836 // later?
1837 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001838 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00001839 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001840 }
1841}
1842
John McCall7edb5fd2010-01-26 07:16:45 +00001843void ADLResult::insert(NamedDecl *New) {
1844 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1845
1846 // If we haven't yet seen a decl for this key, or the last decl
1847 // was exactly this one, we're done.
1848 if (Old == 0 || Old == New) {
1849 Old = New;
1850 return;
1851 }
1852
1853 // Otherwise, decide which is a more recent redeclaration.
1854 FunctionDecl *OldFD, *NewFD;
1855 if (isa<FunctionTemplateDecl>(New)) {
1856 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1857 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1858 } else {
1859 OldFD = cast<FunctionDecl>(Old);
1860 NewFD = cast<FunctionDecl>(New);
1861 }
1862
1863 FunctionDecl *Cursor = NewFD;
1864 while (true) {
1865 Cursor = Cursor->getPreviousDeclaration();
1866
1867 // If we got to the end without finding OldFD, OldFD is the newer
1868 // declaration; leave things as they are.
1869 if (!Cursor) return;
1870
1871 // If we do find OldFD, then NewFD is newer.
1872 if (Cursor == OldFD) break;
1873
1874 // Otherwise, keep looking.
1875 }
1876
1877 Old = New;
1878}
1879
Sebastian Redl644be852009-10-23 19:23:15 +00001880void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001881 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00001882 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001883 // Find all of the associated namespaces and classes based on the
1884 // arguments we have.
1885 AssociatedNamespaceSet AssociatedNamespaces;
1886 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00001887 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00001888 AssociatedNamespaces,
1889 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001890
Sebastian Redl644be852009-10-23 19:23:15 +00001891 QualType T1, T2;
1892 if (Operator) {
1893 T1 = Args[0]->getType();
1894 if (NumArgs >= 2)
1895 T2 = Args[1]->getType();
1896 }
1897
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001898 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001899 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1900 // and let Y be the lookup set produced by argument dependent
1901 // lookup (defined as follows). If X contains [...] then Y is
1902 // empty. Otherwise Y is the set of declarations found in the
1903 // namespaces associated with the argument types as described
1904 // below. The set of declarations found by the lookup of the name
1905 // is the union of X and Y.
1906 //
1907 // Here, we compute Y and add its members to the overloaded
1908 // candidate set.
1909 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001910 NSEnd = AssociatedNamespaces.end();
1911 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001912 // When considering an associated namespace, the lookup is the
1913 // same as the lookup performed when the associated namespace is
1914 // used as a qualifier (3.4.3.2) except that:
1915 //
1916 // -- Any using-directives in the associated namespace are
1917 // ignored.
1918 //
John McCall6ff07852009-08-07 22:18:02 +00001919 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001920 // associated classes are visible within their respective
1921 // namespaces even if they are not visible during an ordinary
1922 // lookup (11.4).
1923 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00001924 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00001925 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00001926 // If the only declaration here is an ordinary friend, consider
1927 // it only if it was declared in an associated classes.
1928 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00001929 DeclContext *LexDC = D->getLexicalDeclContext();
1930 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1931 continue;
1932 }
Mike Stump1eb44332009-09-09 15:08:12 +00001933
John McCalla113e722010-01-26 06:04:06 +00001934 if (isa<UsingShadowDecl>(D))
1935 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00001936
John McCalla113e722010-01-26 06:04:06 +00001937 if (isa<FunctionDecl>(D)) {
1938 if (Operator &&
1939 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
1940 T1, T2, Context))
1941 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00001942 } else if (!isa<FunctionTemplateDecl>(D))
1943 continue;
1944
1945 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001946 }
1947 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001948}
Douglas Gregor546be3c2009-12-30 17:04:44 +00001949
1950//----------------------------------------------------------------------------
1951// Search for all visible declarations.
1952//----------------------------------------------------------------------------
1953VisibleDeclConsumer::~VisibleDeclConsumer() { }
1954
1955namespace {
1956
1957class ShadowContextRAII;
1958
1959class VisibleDeclsRecord {
1960public:
1961 /// \brief An entry in the shadow map, which is optimized to store a
1962 /// single declaration (the common case) but can also store a list
1963 /// of declarations.
1964 class ShadowMapEntry {
1965 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1966
1967 /// \brief Contains either the solitary NamedDecl * or a vector
1968 /// of declarations.
1969 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1970
1971 public:
1972 ShadowMapEntry() : DeclOrVector() { }
1973
1974 void Add(NamedDecl *ND);
1975 void Destroy();
1976
1977 // Iteration.
1978 typedef NamedDecl **iterator;
1979 iterator begin();
1980 iterator end();
1981 };
1982
1983private:
1984 /// \brief A mapping from declaration names to the declarations that have
1985 /// this name within a particular scope.
1986 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
1987
1988 /// \brief A list of shadow maps, which is used to model name hiding.
1989 std::list<ShadowMap> ShadowMaps;
1990
1991 /// \brief The declaration contexts we have already visited.
1992 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
1993
1994 friend class ShadowContextRAII;
1995
1996public:
1997 /// \brief Determine whether we have already visited this context
1998 /// (and, if not, note that we are going to visit that context now).
1999 bool visitedContext(DeclContext *Ctx) {
2000 return !VisitedContexts.insert(Ctx);
2001 }
2002
2003 /// \brief Determine whether the given declaration is hidden in the
2004 /// current scope.
2005 ///
2006 /// \returns the declaration that hides the given declaration, or
2007 /// NULL if no such declaration exists.
2008 NamedDecl *checkHidden(NamedDecl *ND);
2009
2010 /// \brief Add a declaration to the current shadow map.
2011 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2012};
2013
2014/// \brief RAII object that records when we've entered a shadow context.
2015class ShadowContextRAII {
2016 VisibleDeclsRecord &Visible;
2017
2018 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2019
2020public:
2021 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2022 Visible.ShadowMaps.push_back(ShadowMap());
2023 }
2024
2025 ~ShadowContextRAII() {
2026 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2027 EEnd = Visible.ShadowMaps.back().end();
2028 E != EEnd;
2029 ++E)
2030 E->second.Destroy();
2031
2032 Visible.ShadowMaps.pop_back();
2033 }
2034};
2035
2036} // end anonymous namespace
2037
2038void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2039 if (DeclOrVector.isNull()) {
2040 // 0 - > 1 elements: just set the single element information.
2041 DeclOrVector = ND;
2042 return;
2043 }
2044
2045 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2046 // 1 -> 2 elements: create the vector of results and push in the
2047 // existing declaration.
2048 DeclVector *Vec = new DeclVector;
2049 Vec->push_back(PrevND);
2050 DeclOrVector = Vec;
2051 }
2052
2053 // Add the new element to the end of the vector.
2054 DeclOrVector.get<DeclVector*>()->push_back(ND);
2055}
2056
2057void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2058 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2059 delete Vec;
2060 DeclOrVector = ((NamedDecl *)0);
2061 }
2062}
2063
2064VisibleDeclsRecord::ShadowMapEntry::iterator
2065VisibleDeclsRecord::ShadowMapEntry::begin() {
2066 if (DeclOrVector.isNull())
2067 return 0;
2068
2069 if (DeclOrVector.dyn_cast<NamedDecl *>())
2070 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2071
2072 return DeclOrVector.get<DeclVector *>()->begin();
2073}
2074
2075VisibleDeclsRecord::ShadowMapEntry::iterator
2076VisibleDeclsRecord::ShadowMapEntry::end() {
2077 if (DeclOrVector.isNull())
2078 return 0;
2079
2080 if (DeclOrVector.dyn_cast<NamedDecl *>())
2081 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2082
2083 return DeclOrVector.get<DeclVector *>()->end();
2084}
2085
2086NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002087 // Look through using declarations.
2088 ND = ND->getUnderlyingDecl();
2089
Douglas Gregor546be3c2009-12-30 17:04:44 +00002090 unsigned IDNS = ND->getIdentifierNamespace();
2091 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2092 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2093 SM != SMEnd; ++SM) {
2094 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2095 if (Pos == SM->end())
2096 continue;
2097
2098 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2099 IEnd = Pos->second.end();
2100 I != IEnd; ++I) {
2101 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002102 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor546be3c2009-12-30 17:04:44 +00002103 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2104 Decl::IDNS_ObjCProtocol)))
2105 continue;
2106
2107 // Protocols are in distinct namespaces from everything else.
2108 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2109 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2110 (*I)->getIdentifierNamespace() != IDNS)
2111 continue;
2112
Douglas Gregor0cc84042010-01-14 15:47:35 +00002113 // Functions and function templates in the same scope overload
2114 // rather than hide. FIXME: Look for hiding based on function
2115 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002116 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002117 ND->isFunctionOrFunctionTemplate() &&
2118 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002119 continue;
2120
Douglas Gregor546be3c2009-12-30 17:04:44 +00002121 // We've found a declaration that hides this one.
2122 return *I;
2123 }
2124 }
2125
2126 return 0;
2127}
2128
2129static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2130 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002131 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002132 VisibleDeclConsumer &Consumer,
2133 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002134 if (!Ctx)
2135 return;
2136
Douglas Gregor546be3c2009-12-30 17:04:44 +00002137 // Make sure we don't visit the same context twice.
2138 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2139 return;
2140
2141 // Enumerate all of the results in this context.
2142 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2143 CurCtx = CurCtx->getNextContext()) {
2144 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2145 DEnd = CurCtx->decls_end();
2146 D != DEnd; ++D) {
2147 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2148 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002149 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002150 Visited.add(ND);
2151 }
2152
2153 // Visit transparent contexts inside this context.
2154 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2155 if (InnerCtx->isTransparentContext())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002156 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002157 Consumer, Visited);
2158 }
2159 }
2160 }
2161
2162 // Traverse using directives for qualified name lookup.
2163 if (QualifiedNameLookup) {
2164 ShadowContextRAII Shadow(Visited);
2165 DeclContext::udir_iterator I, E;
2166 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2167 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002168 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002169 }
2170 }
2171
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002172 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002173 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002174 if (!Record->hasDefinition())
2175 return;
2176
Douglas Gregor546be3c2009-12-30 17:04:44 +00002177 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2178 BEnd = Record->bases_end();
2179 B != BEnd; ++B) {
2180 QualType BaseType = B->getType();
2181
2182 // Don't look into dependent bases, because name lookup can't look
2183 // there anyway.
2184 if (BaseType->isDependentType())
2185 continue;
2186
2187 const RecordType *Record = BaseType->getAs<RecordType>();
2188 if (!Record)
2189 continue;
2190
2191 // FIXME: It would be nice to be able to determine whether referencing
2192 // a particular member would be ambiguous. For example, given
2193 //
2194 // struct A { int member; };
2195 // struct B { int member; };
2196 // struct C : A, B { };
2197 //
2198 // void f(C *c) { c->### }
2199 //
2200 // accessing 'member' would result in an ambiguity. However, we
2201 // could be smart enough to qualify the member with the base
2202 // class, e.g.,
2203 //
2204 // c->B::member
2205 //
2206 // or
2207 //
2208 // c->A::member
2209
2210 // Find results in this base class (and its bases).
2211 ShadowContextRAII Shadow(Visited);
2212 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002213 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002214 }
2215 }
2216
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002217 // Traverse the contexts of Objective-C classes.
2218 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2219 // Traverse categories.
2220 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2221 Category; Category = Category->getNextClassCategory()) {
2222 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002223 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2224 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002225 }
2226
2227 // Traverse protocols.
2228 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2229 E = IFace->protocol_end(); I != E; ++I) {
2230 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002231 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2232 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002233 }
2234
2235 // Traverse the superclass.
2236 if (IFace->getSuperClass()) {
2237 ShadowContextRAII Shadow(Visited);
2238 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002239 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002240 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002241
2242 // If there is an implementation, traverse it. We do this to find
2243 // synthesized ivars.
2244 if (IFace->getImplementation()) {
2245 ShadowContextRAII Shadow(Visited);
2246 LookupVisibleDecls(IFace->getImplementation(), Result,
2247 QualifiedNameLookup, true, Consumer, Visited);
2248 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002249 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2250 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2251 E = Protocol->protocol_end(); I != E; ++I) {
2252 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002253 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2254 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002255 }
2256 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2257 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2258 E = Category->protocol_end(); I != E; ++I) {
2259 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002260 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2261 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002262 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002263
2264 // If there is an implementation, traverse it.
2265 if (Category->getImplementation()) {
2266 ShadowContextRAII Shadow(Visited);
2267 LookupVisibleDecls(Category->getImplementation(), Result,
2268 QualifiedNameLookup, true, Consumer, Visited);
2269 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002270 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002271}
2272
2273static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2274 UnqualUsingDirectiveSet &UDirs,
2275 VisibleDeclConsumer &Consumer,
2276 VisibleDeclsRecord &Visited) {
2277 if (!S)
2278 return;
2279
Douglas Gregor539c5c32010-01-07 00:31:29 +00002280 if (!S->getEntity() || !S->getParent() ||
2281 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2282 // Walk through the declarations in this Scope.
2283 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2284 D != DEnd; ++D) {
2285 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2286 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002287 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002288 Visited.add(ND);
2289 }
2290 }
2291 }
2292
Douglas Gregor711be1e2010-03-15 14:33:29 +00002293 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002294 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002295 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002296 // Look into this scope's declaration context, along with any of its
2297 // parent lookup contexts (e.g., enclosing classes), up to the point
2298 // where we hit the context stored in the next outer scope.
2299 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002300 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor546be3c2009-12-30 17:04:44 +00002301
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002302 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002303 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002304 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2305 if (Method->isInstanceMethod()) {
2306 // For instance methods, look for ivars in the method's interface.
2307 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2308 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor62021192010-02-04 23:42:48 +00002309 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2310 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2311 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002312 }
2313
2314 // We've already performed all of the name lookup that we need
2315 // to for Objective-C methods; the next context will be the
2316 // outer scope.
2317 break;
2318 }
2319
Douglas Gregor546be3c2009-12-30 17:04:44 +00002320 if (Ctx->isFunctionOrMethod())
2321 continue;
2322
2323 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002324 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002325 }
2326 } else if (!S->getParent()) {
2327 // Look into the translation unit scope. We walk through the translation
2328 // unit's declaration context, because the Scope itself won't have all of
2329 // the declarations if we loaded a precompiled header.
2330 // FIXME: We would like the translation unit's Scope object to point to the
2331 // translation unit, so we don't need this special "if" branch. However,
2332 // doing so would force the normal C++ name-lookup code to look into the
2333 // translation unit decl when the IdentifierInfo chains would suffice.
2334 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002335 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002336 Entity = Result.getSema().Context.getTranslationUnitDecl();
2337 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002338 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002339 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002340
2341 if (Entity) {
2342 // Lookup visible declarations in any namespaces found by using
2343 // directives.
2344 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2345 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2346 for (; UI != UEnd; ++UI)
2347 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002348 Result, /*QualifiedNameLookup=*/false,
2349 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002350 }
2351
2352 // Lookup names in the parent scope.
2353 ShadowContextRAII Shadow(Visited);
2354 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2355}
2356
2357void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2358 VisibleDeclConsumer &Consumer) {
2359 // Determine the set of using directives available during
2360 // unqualified name lookup.
2361 Scope *Initial = S;
2362 UnqualUsingDirectiveSet UDirs;
2363 if (getLangOptions().CPlusPlus) {
2364 // Find the first namespace or translation-unit scope.
2365 while (S && !isNamespaceOrTranslationUnitScope(S))
2366 S = S->getParent();
2367
2368 UDirs.visitScopeChain(Initial, S);
2369 }
2370 UDirs.done();
2371
2372 // Look for visible declarations.
2373 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2374 VisibleDeclsRecord Visited;
2375 ShadowContextRAII Shadow(Visited);
2376 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2377}
2378
2379void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2380 VisibleDeclConsumer &Consumer) {
2381 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2382 VisibleDeclsRecord Visited;
2383 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002384 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2385 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002386}
2387
2388//----------------------------------------------------------------------------
2389// Typo correction
2390//----------------------------------------------------------------------------
2391
2392namespace {
2393class TypoCorrectionConsumer : public VisibleDeclConsumer {
2394 /// \brief The name written that is a typo in the source.
2395 llvm::StringRef Typo;
2396
2397 /// \brief The results found that have the smallest edit distance
2398 /// found (so far) with the typo name.
2399 llvm::SmallVector<NamedDecl *, 4> BestResults;
2400
Douglas Gregoraaf87162010-04-14 20:04:41 +00002401 /// \brief The keywords that have the smallest edit distance.
2402 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2403
Douglas Gregor546be3c2009-12-30 17:04:44 +00002404 /// \brief The best edit distance found so far.
2405 unsigned BestEditDistance;
2406
2407public:
2408 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2409 : Typo(Typo->getName()) { }
2410
Douglas Gregor0cc84042010-01-14 15:47:35 +00002411 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002412 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002413
2414 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2415 iterator begin() const { return BestResults.begin(); }
2416 iterator end() const { return BestResults.end(); }
Douglas Gregoraaf87162010-04-14 20:04:41 +00002417 void clear_decls() { BestResults.clear(); }
2418
2419 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002420
Douglas Gregoraaf87162010-04-14 20:04:41 +00002421 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2422 keyword_iterator;
2423 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2424 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2425 bool keyword_empty() const { return BestKeywords.empty(); }
2426 unsigned keyword_size() const { return BestKeywords.size(); }
2427
2428 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002429};
2430
2431}
2432
Douglas Gregor0cc84042010-01-14 15:47:35 +00002433void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2434 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002435 // Don't consider hidden names for typo correction.
2436 if (Hiding)
2437 return;
2438
2439 // Only consider entities with identifiers for names, ignoring
2440 // special names (constructors, overloaded operators, selectors,
2441 // etc.).
2442 IdentifierInfo *Name = ND->getIdentifier();
2443 if (!Name)
2444 return;
2445
2446 // Compute the edit distance between the typo and the name of this
2447 // entity. If this edit distance is not worse than the best edit
2448 // distance we've seen so far, add it to the list of results.
2449 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregoraaf87162010-04-14 20:04:41 +00002450 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002451 if (ED < BestEditDistance) {
2452 // This result is better than any we've seen before; clear out
2453 // the previous results.
2454 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002455 BestKeywords.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002456 BestEditDistance = ED;
2457 } else if (ED > BestEditDistance) {
2458 // This result is worse than the best results we've seen so far;
2459 // ignore it.
2460 return;
2461 }
2462 } else
2463 BestEditDistance = ED;
2464
2465 BestResults.push_back(ND);
2466}
2467
Douglas Gregoraaf87162010-04-14 20:04:41 +00002468void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2469 llvm::StringRef Keyword) {
2470 // Compute the edit distance between the typo and this keyword.
2471 // If this edit distance is not worse than the best edit
2472 // distance we've seen so far, add it to the list of results.
2473 unsigned ED = Typo.edit_distance(Keyword);
2474 if (!BestResults.empty() || !BestKeywords.empty()) {
2475 if (ED < BestEditDistance) {
2476 BestResults.clear();
2477 BestKeywords.clear();
2478 BestEditDistance = ED;
2479 } else if (ED > BestEditDistance) {
2480 // This result is worse than the best results we've seen so far;
2481 // ignore it.
2482 return;
2483 }
2484 } else
2485 BestEditDistance = ED;
2486
2487 BestKeywords.push_back(&Context.Idents.get(Keyword));
2488}
2489
Douglas Gregor546be3c2009-12-30 17:04:44 +00002490/// \brief Try to "correct" a typo in the source code by finding
2491/// visible declarations whose names are similar to the name that was
2492/// present in the source code.
2493///
2494/// \param Res the \c LookupResult structure that contains the name
2495/// that was present in the source code along with the name-lookup
2496/// criteria used to search for the name. On success, this structure
2497/// will contain the results of name lookup.
2498///
2499/// \param S the scope in which name lookup occurs.
2500///
2501/// \param SS the nested-name-specifier that precedes the name we're
2502/// looking for, if present.
2503///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002504/// \param MemberContext if non-NULL, the context in which to look for
2505/// a member access expression.
2506///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002507/// \param EnteringContext whether we're entering the context described by
2508/// the nested-name-specifier SS.
2509///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002510/// \param CTC The context in which typo correction occurs, which impacts the
2511/// set of keywords permitted.
2512///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002513/// \param OPT when non-NULL, the search for visible declarations will
2514/// also walk the protocols in the qualified interfaces of \p OPT.
2515///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002516/// \returns the corrected name if the typo was corrected, otherwise returns an
2517/// empty \c DeclarationName. When a typo was corrected, the result structure
2518/// may contain the results of name lookup for the correct name or it may be
2519/// empty.
2520DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002521 DeclContext *MemberContext,
2522 bool EnteringContext,
2523 CorrectTypoContext CTC,
2524 const ObjCObjectPointerType *OPT) {
Ted Kremenek1dac3412010-01-06 00:23:04 +00002525 if (Diags.hasFatalErrorOccurred())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002526 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002527
2528 // Provide a stop gap for files that are just seriously broken. Trying
2529 // to correct all typos can turn into a HUGE performance penalty, causing
2530 // some files to take minutes to get rejected by the parser.
2531 // FIXME: Is this the right solution?
2532 if (TyposCorrected == 20)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002533 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002534 ++TyposCorrected;
Ted Kremenek1dac3412010-01-06 00:23:04 +00002535
Douglas Gregor546be3c2009-12-30 17:04:44 +00002536 // We only attempt to correct typos for identifiers.
2537 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2538 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002539 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002540
2541 // If the scope specifier itself was invalid, don't try to correct
2542 // typos.
2543 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002544 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002545
2546 // Never try to correct typos during template deduction or
2547 // instantiation.
2548 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002549 return DeclarationName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002550
Douglas Gregor546be3c2009-12-30 17:04:44 +00002551 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002552
2553 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002554 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002555 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002556
2557 // Look in qualified interfaces.
2558 if (OPT) {
2559 for (ObjCObjectPointerType::qual_iterator
2560 I = OPT->qual_begin(), E = OPT->qual_end();
2561 I != E; ++I)
2562 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2563 }
2564 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002565 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2566 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002567 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002568
2569 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2570 } else {
2571 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2572 }
2573
Douglas Gregoraaf87162010-04-14 20:04:41 +00002574 // Add context-dependent keywords.
2575 bool WantTypeSpecifiers = false;
2576 bool WantExpressionKeywords = false;
2577 bool WantCXXNamedCasts = false;
2578 bool WantRemainingKeywords = false;
2579 switch (CTC) {
2580 case CTC_Unknown:
2581 WantTypeSpecifiers = true;
2582 WantExpressionKeywords = true;
2583 WantCXXNamedCasts = true;
2584 WantRemainingKeywords = true;
2585 break;
2586
2587 case CTC_NoKeywords:
2588 break;
2589
2590 case CTC_Type:
2591 WantTypeSpecifiers = true;
2592 break;
2593
2594 case CTC_ObjCMessageReceiver:
2595 Consumer.addKeywordResult(Context, "super");
2596 // Fall through to handle message receivers like expressions.
2597
2598 case CTC_Expression:
2599 if (getLangOptions().CPlusPlus)
2600 WantTypeSpecifiers = true;
2601 WantExpressionKeywords = true;
2602 // Fall through to get C++ named casts.
2603
2604 case CTC_CXXCasts:
2605 WantCXXNamedCasts = true;
2606 break;
2607
2608 case CTC_MemberLookup:
2609 if (getLangOptions().CPlusPlus)
2610 Consumer.addKeywordResult(Context, "template");
2611 break;
2612 }
2613
2614 if (WantTypeSpecifiers) {
2615 // Add type-specifier keywords to the set of results.
2616 const char *CTypeSpecs[] = {
2617 "char", "const", "double", "enum", "float", "int", "long", "short",
2618 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2619 "_Complex", "_Imaginary",
2620 // storage-specifiers as well
2621 "extern", "inline", "static", "typedef"
2622 };
2623
2624 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2625 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2626 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2627
2628 if (getLangOptions().C99)
2629 Consumer.addKeywordResult(Context, "restrict");
2630 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2631 Consumer.addKeywordResult(Context, "bool");
2632
2633 if (getLangOptions().CPlusPlus) {
2634 Consumer.addKeywordResult(Context, "class");
2635 Consumer.addKeywordResult(Context, "typename");
2636 Consumer.addKeywordResult(Context, "wchar_t");
2637
2638 if (getLangOptions().CPlusPlus0x) {
2639 Consumer.addKeywordResult(Context, "char16_t");
2640 Consumer.addKeywordResult(Context, "char32_t");
2641 Consumer.addKeywordResult(Context, "constexpr");
2642 Consumer.addKeywordResult(Context, "decltype");
2643 Consumer.addKeywordResult(Context, "thread_local");
2644 }
2645 }
2646
2647 if (getLangOptions().GNUMode)
2648 Consumer.addKeywordResult(Context, "typeof");
2649 }
2650
2651 if (WantCXXNamedCasts) {
2652 Consumer.addKeywordResult(Context, "const_cast");
2653 Consumer.addKeywordResult(Context, "dynamic_cast");
2654 Consumer.addKeywordResult(Context, "reinterpret_cast");
2655 Consumer.addKeywordResult(Context, "static_cast");
2656 }
2657
2658 if (WantExpressionKeywords) {
2659 Consumer.addKeywordResult(Context, "sizeof");
2660 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2661 Consumer.addKeywordResult(Context, "false");
2662 Consumer.addKeywordResult(Context, "true");
2663 }
2664
2665 if (getLangOptions().CPlusPlus) {
2666 const char *CXXExprs[] = {
2667 "delete", "new", "operator", "throw", "typeid"
2668 };
2669 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2670 for (unsigned I = 0; I != NumCXXExprs; ++I)
2671 Consumer.addKeywordResult(Context, CXXExprs[I]);
2672
2673 if (isa<CXXMethodDecl>(CurContext) &&
2674 cast<CXXMethodDecl>(CurContext)->isInstance())
2675 Consumer.addKeywordResult(Context, "this");
2676
2677 if (getLangOptions().CPlusPlus0x) {
2678 Consumer.addKeywordResult(Context, "alignof");
2679 Consumer.addKeywordResult(Context, "nullptr");
2680 }
2681 }
2682 }
2683
2684 if (WantRemainingKeywords) {
2685 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2686 // Statements.
2687 const char *CStmts[] = {
2688 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2689 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2690 for (unsigned I = 0; I != NumCStmts; ++I)
2691 Consumer.addKeywordResult(Context, CStmts[I]);
2692
2693 if (getLangOptions().CPlusPlus) {
2694 Consumer.addKeywordResult(Context, "catch");
2695 Consumer.addKeywordResult(Context, "try");
2696 }
2697
2698 if (S && S->getBreakParent())
2699 Consumer.addKeywordResult(Context, "break");
2700
2701 if (S && S->getContinueParent())
2702 Consumer.addKeywordResult(Context, "continue");
2703
2704 if (!getSwitchStack().empty()) {
2705 Consumer.addKeywordResult(Context, "case");
2706 Consumer.addKeywordResult(Context, "default");
2707 }
2708 } else {
2709 if (getLangOptions().CPlusPlus) {
2710 Consumer.addKeywordResult(Context, "namespace");
2711 Consumer.addKeywordResult(Context, "template");
2712 }
2713
2714 if (S && S->isClassScope()) {
2715 Consumer.addKeywordResult(Context, "explicit");
2716 Consumer.addKeywordResult(Context, "friend");
2717 Consumer.addKeywordResult(Context, "mutable");
2718 Consumer.addKeywordResult(Context, "private");
2719 Consumer.addKeywordResult(Context, "protected");
2720 Consumer.addKeywordResult(Context, "public");
2721 Consumer.addKeywordResult(Context, "virtual");
2722 }
2723 }
2724
2725 if (getLangOptions().CPlusPlus) {
2726 Consumer.addKeywordResult(Context, "using");
2727
2728 if (getLangOptions().CPlusPlus0x)
2729 Consumer.addKeywordResult(Context, "static_assert");
2730 }
2731 }
2732
2733 // If we haven't found anything, we're done.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002734 if (Consumer.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002735 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002736
2737 // Only allow a single, closest name in the result set (it's okay to
2738 // have overloads of that name, though).
Douglas Gregoraaf87162010-04-14 20:04:41 +00002739 DeclarationName BestName;
2740 NamedDecl *BestIvarOrPropertyDecl = 0;
2741 bool FoundIvarOrPropertyDecl = false;
2742
2743 // Check all of the declaration results to find the best name so far.
2744 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2745 IEnd = Consumer.end();
2746 I != IEnd; ++I) {
2747 if (!BestName)
2748 BestName = (*I)->getDeclName();
2749 else if (BestName != (*I)->getDeclName())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002750 return DeclarationName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002751
Douglas Gregoraaf87162010-04-14 20:04:41 +00002752 // \brief Keep track of either an Objective-C ivar or a property, but not
2753 // both.
2754 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
2755 if (FoundIvarOrPropertyDecl)
2756 BestIvarOrPropertyDecl = 0;
2757 else {
2758 BestIvarOrPropertyDecl = *I;
2759 FoundIvarOrPropertyDecl = true;
2760 }
2761 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002762 }
2763
Douglas Gregoraaf87162010-04-14 20:04:41 +00002764 // Now check all of the keyword results to find the best name.
2765 switch (Consumer.keyword_size()) {
2766 case 0:
2767 // No keywords matched.
2768 break;
2769
2770 case 1:
2771 // If we already have a name
2772 if (!BestName) {
2773 // We did not have anything previously,
2774 BestName = *Consumer.keyword_begin();
2775 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
2776 // We have a declaration with the same name as a context-sensitive
2777 // keyword. The keyword takes precedence.
2778 BestIvarOrPropertyDecl = 0;
2779 FoundIvarOrPropertyDecl = false;
2780 Consumer.clear_decls();
2781 } else {
2782 // Name collision; we will not correct typos.
2783 return DeclarationName();
2784 }
2785 break;
2786
2787 default:
2788 // Name collision; we will not correct typos.
2789 return DeclarationName();
2790 }
2791
Douglas Gregor546be3c2009-12-30 17:04:44 +00002792 // BestName is the closest viable name to what the user
2793 // typed. However, to make sure that we don't pick something that's
2794 // way off, make sure that the user typed at least 3 characters for
2795 // each correction.
2796 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002797 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
2798 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002799 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002800
2801 // Perform name lookup again with the name we chose, and declare
2802 // success if we found something that was not ambiguous.
2803 Res.clear();
2804 Res.setLookupName(BestName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002805
2806 // If we found an ivar or property, add that result; no further
2807 // lookup is required.
Douglas Gregoraaf87162010-04-14 20:04:41 +00002808 if (BestIvarOrPropertyDecl)
2809 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002810 // If we're looking into the context of a member, perform qualified
2811 // name lookup on the best name.
Douglas Gregoraaf87162010-04-14 20:04:41 +00002812 else if (!Consumer.keyword_empty()) {
2813 // The best match was a keyword. Return it.
2814 return BestName;
2815 } else if (MemberContext)
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002816 LookupQualifiedName(Res, MemberContext);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002817 // Perform lookup as if we had just parsed the best name.
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002818 else
2819 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2820 EnteringContext);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002821
2822 if (Res.isAmbiguous()) {
2823 Res.suppressDiagnostics();
Douglas Gregor931f98a2010-04-14 17:09:22 +00002824 return DeclarationName();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002825 }
2826
Douglas Gregor931f98a2010-04-14 17:09:22 +00002827 if (Res.getResultKind() != LookupResult::NotFound)
2828 return BestName;
2829
2830 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002831}