blob: 337a4a3ce3f7dd41ab2675228d748feb2c4f66ee [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.
John McCall77bb1aa2010-05-01 00:40:08 +00001264 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
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
Douglas Gregor54022952010-04-30 07:08:38 +00001389static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1390 DeclContext *Ctx) {
1391 // Add the associated namespace for this class.
1392
1393 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1394 // be a locally scoped record.
1395
1396 while (Ctx->isRecord() || Ctx->isTransparentContext())
1397 Ctx = Ctx->getParent();
1398
John McCall6ff07852009-08-07 22:18:02 +00001399 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001400 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001401}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001402
Mike Stump1eb44332009-09-09 15:08:12 +00001403// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001404// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001405static void
1406addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001407 ASTContext &Context,
1408 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001409 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001410 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001411 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001412 switch (Arg.getKind()) {
1413 case TemplateArgument::Null:
1414 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Douglas Gregor69be8d62009-07-08 07:51:57 +00001416 case TemplateArgument::Type:
1417 // [...] the namespaces and classes associated with the types of the
1418 // template arguments provided for template type parameters (excluding
1419 // template template parameters)
1420 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1421 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001422 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001423 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Douglas Gregor788cd062009-11-11 01:00:40 +00001425 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001426 // [...] the namespaces in which any template template arguments are
1427 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001428 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001429 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001430 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001431 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001432 DeclContext *Ctx = ClassTemplate->getDeclContext();
1433 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1434 AssociatedClasses.insert(EnclosingClass);
1435 // Add the associated namespace for this class.
Douglas Gregor54022952010-04-30 07:08:38 +00001436 CollectEnclosingNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001437 }
1438 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001439 }
1440
1441 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001442 case TemplateArgument::Integral:
1443 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001444 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001445 // associated namespaces. ]
1446 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Douglas Gregor69be8d62009-07-08 07:51:57 +00001448 case TemplateArgument::Pack:
1449 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1450 PEnd = Arg.pack_end();
1451 P != PEnd; ++P)
1452 addAssociatedClassesAndNamespaces(*P, Context,
1453 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001454 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001455 break;
1456 }
1457}
1458
Douglas Gregorfa047642009-02-04 00:32:51 +00001459// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001460// argument-dependent lookup with an argument of class type
1461// (C++ [basic.lookup.koenig]p2).
1462static void
1463addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregorfa047642009-02-04 00:32:51 +00001464 ASTContext &Context,
1465 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001466 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001467 // C++ [basic.lookup.koenig]p2:
1468 // [...]
1469 // -- If T is a class type (including unions), its associated
1470 // classes are: the class itself; the class of which it is a
1471 // member, if any; and its direct and indirect base
1472 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001473 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001474
1475 // Add the class of which it is a member, if any.
1476 DeclContext *Ctx = Class->getDeclContext();
1477 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1478 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001479 // Add the associated namespace for this class.
Douglas Gregor54022952010-04-30 07:08:38 +00001480 CollectEnclosingNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Douglas Gregorfa047642009-02-04 00:32:51 +00001482 // Add the class itself. If we've already seen this class, we don't
1483 // need to visit base classes.
1484 if (!AssociatedClasses.insert(Class))
1485 return;
1486
Mike Stump1eb44332009-09-09 15:08:12 +00001487 // -- If T is a template-id, its associated namespaces and classes are
1488 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001489 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001490 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001491 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001492 // namespaces in which any template template arguments are defined; and
1493 // the classes in which any member templates used as template template
1494 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001495 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001496 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001497 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1498 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1499 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1500 AssociatedClasses.insert(EnclosingClass);
1501 // Add the associated namespace for this class.
Douglas Gregor54022952010-04-30 07:08:38 +00001502 CollectEnclosingNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Douglas Gregor69be8d62009-07-08 07:51:57 +00001504 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1505 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1506 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1507 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001508 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
John McCall86ff3082010-02-04 22:26:26 +00001511 // Only recurse into base classes for complete types.
1512 if (!Class->hasDefinition()) {
1513 // FIXME: we might need to instantiate templates here
1514 return;
1515 }
1516
Douglas Gregorfa047642009-02-04 00:32:51 +00001517 // Add direct and indirect base classes along with their associated
1518 // namespaces.
1519 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1520 Bases.push_back(Class);
1521 while (!Bases.empty()) {
1522 // Pop this class off the stack.
1523 Class = Bases.back();
1524 Bases.pop_back();
1525
1526 // Visit the base classes.
1527 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1528 BaseEnd = Class->bases_end();
1529 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001530 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001531 // In dependent contexts, we do ADL twice, and the first time around,
1532 // the base type might be a dependent TemplateSpecializationType, or a
1533 // TemplateTypeParmType. If that happens, simply ignore it.
1534 // FIXME: If we want to support export, we probably need to add the
1535 // namespace of the template in a TemplateSpecializationType, or even
1536 // the classes and namespaces of known non-dependent arguments.
1537 if (!BaseType)
1538 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001539 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1540 if (AssociatedClasses.insert(BaseDecl)) {
1541 // Find the associated namespace for this base class.
1542 DeclContext *BaseCtx = BaseDecl->getDeclContext();
Douglas Gregor54022952010-04-30 07:08:38 +00001543 CollectEnclosingNamespace(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.
Douglas Gregor54022952010-04-30 07:08:38 +00001618 CollectEnclosingNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001619
1620 return;
1621 }
1622
1623 // -- If T is a function type, its associated namespaces and
1624 // classes are those associated with the function parameter
1625 // types and those associated with the return type.
John McCall183700f2009-09-21 23:43:11 +00001626 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001627 // Return type
John McCall183700f2009-09-21 23:43:11 +00001628 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001629 Context,
John McCall6ff07852009-08-07 22:18:02 +00001630 AssociatedNamespaces, AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001631
John McCall183700f2009-09-21 23:43:11 +00001632 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001633 if (!Proto)
1634 return;
1635
1636 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001637 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001638 ArgEnd = Proto->arg_type_end();
Douglas Gregorfa047642009-02-04 00:32:51 +00001639 Arg != ArgEnd; ++Arg)
1640 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCall6ff07852009-08-07 22:18:02 +00001641 AssociatedNamespaces, AssociatedClasses);
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Douglas Gregorfa047642009-02-04 00:32:51 +00001643 return;
1644 }
1645
1646 // -- If T is a pointer to a member function of a class X, its
1647 // associated namespaces and classes are those associated
1648 // with the function parameter types and return type,
Mike Stump1eb44332009-09-09 15:08:12 +00001649 // together with those associated with X.
Douglas Gregorfa047642009-02-04 00:32:51 +00001650 //
1651 // -- If T is a pointer to a data member of class X, its
1652 // associated namespaces and classes are those associated
1653 // with the member type together with those associated with
Mike Stump1eb44332009-09-09 15:08:12 +00001654 // X.
Ted Kremenek6217b802009-07-29 21:53:49 +00001655 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001656 // Handle the type that the pointer to member points to.
1657 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1658 Context,
John McCall6ff07852009-08-07 22:18:02 +00001659 AssociatedNamespaces,
1660 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001661
1662 // Handle the class type into which this points.
Ted Kremenek6217b802009-07-29 21:53:49 +00001663 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001664 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1665 Context,
John McCall6ff07852009-08-07 22:18:02 +00001666 AssociatedNamespaces,
1667 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001668
1669 return;
1670 }
1671
1672 // FIXME: What about block pointers?
1673 // FIXME: What about Objective-C message sends?
1674}
1675
1676/// \brief Find the associated classes and namespaces for
1677/// argument-dependent lookup for a call with the given set of
1678/// arguments.
1679///
1680/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001681/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001682/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001683void
Douglas Gregorfa047642009-02-04 00:32:51 +00001684Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1685 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001686 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001687 AssociatedNamespaces.clear();
1688 AssociatedClasses.clear();
1689
1690 // C++ [basic.lookup.koenig]p2:
1691 // For each argument type T in the function call, there is a set
1692 // of zero or more associated namespaces and a set of zero or more
1693 // associated classes to be considered. The sets of namespaces and
1694 // classes is determined entirely by the types of the function
1695 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001696 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001697 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1698 Expr *Arg = Args[ArgIdx];
1699
1700 if (Arg->getType() != Context.OverloadTy) {
1701 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001702 AssociatedNamespaces,
1703 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001704 continue;
1705 }
1706
1707 // [...] In addition, if the argument is the name or address of a
1708 // set of overloaded functions and/or function templates, its
1709 // associated classes and namespaces are the union of those
1710 // associated with each of the members of the set: the namespace
1711 // in which the function or function template is defined and the
1712 // classes and namespaces associated with its (non-dependent)
1713 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001714 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001715 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1716 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1717 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001718
John McCallba135432009-11-21 08:51:07 +00001719 // TODO: avoid the copies. This should be easy when the cases
1720 // share a storage implementation.
1721 llvm::SmallVector<NamedDecl*, 8> Functions;
1722
1723 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1724 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00001725 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001726 continue;
1727
John McCallba135432009-11-21 08:51:07 +00001728 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1729 E = Functions.end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001730 // Look through any using declarations to find the underlying function.
1731 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001732
Chandler Carruthbd647292009-12-29 06:17:27 +00001733 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1734 if (!FDecl)
1735 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001736
1737 // Add the classes and namespaces associated with the parameter
1738 // types and return type of this function.
1739 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001740 AssociatedNamespaces,
1741 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001742 }
1743 }
1744}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001745
1746/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1747/// an acceptable non-member overloaded operator for a call whose
1748/// arguments have types T1 (and, if non-empty, T2). This routine
1749/// implements the check in C++ [over.match.oper]p3b2 concerning
1750/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001751static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001752IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1753 QualType T1, QualType T2,
1754 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001755 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1756 return true;
1757
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001758 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1759 return true;
1760
John McCall183700f2009-09-21 23:43:11 +00001761 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001762 if (Proto->getNumArgs() < 1)
1763 return false;
1764
1765 if (T1->isEnumeralType()) {
1766 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001767 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001768 return true;
1769 }
1770
1771 if (Proto->getNumArgs() < 2)
1772 return false;
1773
1774 if (!T2.isNull() && T2->isEnumeralType()) {
1775 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001776 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001777 return true;
1778 }
1779
1780 return false;
1781}
1782
John McCall7d384dd2009-11-18 07:57:50 +00001783NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00001784 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00001785 LookupNameKind NameKind,
1786 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00001787 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00001788 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00001789 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00001790}
1791
Douglas Gregor6e378de2009-04-23 23:18:26 +00001792/// \brief Find the protocol with the given name, if any.
Douglas Gregorc83c6872010-04-15 22:33:43 +00001793ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
1794 SourceLocation IdLoc) {
1795 Decl *D = LookupSingleName(TUScope, II, IdLoc,
1796 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001797 return cast_or_null<ObjCProtocolDecl>(D);
1798}
1799
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001800void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001801 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00001802 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001803 // C++ [over.match.oper]p3:
1804 // -- The set of non-member candidates is the result of the
1805 // unqualified lookup of operator@ in the context of the
1806 // expression according to the usual rules for name lookup in
1807 // unqualified function calls (3.4.2) except that all member
1808 // functions are ignored. However, if no operand has a class
1809 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00001810 // that have a first parameter of type T1 or "reference to
1811 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001812 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00001813 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001814 // when T2 is an enumeration type, are candidate functions.
1815 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00001816 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1817 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001819 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1820
John McCallf36e02d2009-10-09 21:13:30 +00001821 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001822 return;
1823
1824 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1825 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001826 NamedDecl *Found = (*Op)->getUnderlyingDecl();
1827 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001828 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001829 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00001830 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001831 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001832 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00001833 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00001834 // later?
1835 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00001836 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00001837 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001838 }
1839}
1840
John McCall7edb5fd2010-01-26 07:16:45 +00001841void ADLResult::insert(NamedDecl *New) {
1842 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1843
1844 // If we haven't yet seen a decl for this key, or the last decl
1845 // was exactly this one, we're done.
1846 if (Old == 0 || Old == New) {
1847 Old = New;
1848 return;
1849 }
1850
1851 // Otherwise, decide which is a more recent redeclaration.
1852 FunctionDecl *OldFD, *NewFD;
1853 if (isa<FunctionTemplateDecl>(New)) {
1854 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1855 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1856 } else {
1857 OldFD = cast<FunctionDecl>(Old);
1858 NewFD = cast<FunctionDecl>(New);
1859 }
1860
1861 FunctionDecl *Cursor = NewFD;
1862 while (true) {
1863 Cursor = Cursor->getPreviousDeclaration();
1864
1865 // If we got to the end without finding OldFD, OldFD is the newer
1866 // declaration; leave things as they are.
1867 if (!Cursor) return;
1868
1869 // If we do find OldFD, then NewFD is newer.
1870 if (Cursor == OldFD) break;
1871
1872 // Otherwise, keep looking.
1873 }
1874
1875 Old = New;
1876}
1877
Sebastian Redl644be852009-10-23 19:23:15 +00001878void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001879 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00001880 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001881 // Find all of the associated namespaces and classes based on the
1882 // arguments we have.
1883 AssociatedNamespaceSet AssociatedNamespaces;
1884 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00001885 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00001886 AssociatedNamespaces,
1887 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001888
Sebastian Redl644be852009-10-23 19:23:15 +00001889 QualType T1, T2;
1890 if (Operator) {
1891 T1 = Args[0]->getType();
1892 if (NumArgs >= 2)
1893 T2 = Args[1]->getType();
1894 }
1895
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001896 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001897 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1898 // and let Y be the lookup set produced by argument dependent
1899 // lookup (defined as follows). If X contains [...] then Y is
1900 // empty. Otherwise Y is the set of declarations found in the
1901 // namespaces associated with the argument types as described
1902 // below. The set of declarations found by the lookup of the name
1903 // is the union of X and Y.
1904 //
1905 // Here, we compute Y and add its members to the overloaded
1906 // candidate set.
1907 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001908 NSEnd = AssociatedNamespaces.end();
1909 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001910 // When considering an associated namespace, the lookup is the
1911 // same as the lookup performed when the associated namespace is
1912 // used as a qualifier (3.4.3.2) except that:
1913 //
1914 // -- Any using-directives in the associated namespace are
1915 // ignored.
1916 //
John McCall6ff07852009-08-07 22:18:02 +00001917 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001918 // associated classes are visible within their respective
1919 // namespaces even if they are not visible during an ordinary
1920 // lookup (11.4).
1921 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00001922 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00001923 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00001924 // If the only declaration here is an ordinary friend, consider
1925 // it only if it was declared in an associated classes.
1926 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00001927 DeclContext *LexDC = D->getLexicalDeclContext();
1928 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1929 continue;
1930 }
Mike Stump1eb44332009-09-09 15:08:12 +00001931
John McCalla113e722010-01-26 06:04:06 +00001932 if (isa<UsingShadowDecl>(D))
1933 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00001934
John McCalla113e722010-01-26 06:04:06 +00001935 if (isa<FunctionDecl>(D)) {
1936 if (Operator &&
1937 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
1938 T1, T2, Context))
1939 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00001940 } else if (!isa<FunctionTemplateDecl>(D))
1941 continue;
1942
1943 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001944 }
1945 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001946}
Douglas Gregor546be3c2009-12-30 17:04:44 +00001947
1948//----------------------------------------------------------------------------
1949// Search for all visible declarations.
1950//----------------------------------------------------------------------------
1951VisibleDeclConsumer::~VisibleDeclConsumer() { }
1952
1953namespace {
1954
1955class ShadowContextRAII;
1956
1957class VisibleDeclsRecord {
1958public:
1959 /// \brief An entry in the shadow map, which is optimized to store a
1960 /// single declaration (the common case) but can also store a list
1961 /// of declarations.
1962 class ShadowMapEntry {
1963 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
1964
1965 /// \brief Contains either the solitary NamedDecl * or a vector
1966 /// of declarations.
1967 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
1968
1969 public:
1970 ShadowMapEntry() : DeclOrVector() { }
1971
1972 void Add(NamedDecl *ND);
1973 void Destroy();
1974
1975 // Iteration.
1976 typedef NamedDecl **iterator;
1977 iterator begin();
1978 iterator end();
1979 };
1980
1981private:
1982 /// \brief A mapping from declaration names to the declarations that have
1983 /// this name within a particular scope.
1984 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
1985
1986 /// \brief A list of shadow maps, which is used to model name hiding.
1987 std::list<ShadowMap> ShadowMaps;
1988
1989 /// \brief The declaration contexts we have already visited.
1990 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
1991
1992 friend class ShadowContextRAII;
1993
1994public:
1995 /// \brief Determine whether we have already visited this context
1996 /// (and, if not, note that we are going to visit that context now).
1997 bool visitedContext(DeclContext *Ctx) {
1998 return !VisitedContexts.insert(Ctx);
1999 }
2000
2001 /// \brief Determine whether the given declaration is hidden in the
2002 /// current scope.
2003 ///
2004 /// \returns the declaration that hides the given declaration, or
2005 /// NULL if no such declaration exists.
2006 NamedDecl *checkHidden(NamedDecl *ND);
2007
2008 /// \brief Add a declaration to the current shadow map.
2009 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2010};
2011
2012/// \brief RAII object that records when we've entered a shadow context.
2013class ShadowContextRAII {
2014 VisibleDeclsRecord &Visible;
2015
2016 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2017
2018public:
2019 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2020 Visible.ShadowMaps.push_back(ShadowMap());
2021 }
2022
2023 ~ShadowContextRAII() {
2024 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2025 EEnd = Visible.ShadowMaps.back().end();
2026 E != EEnd;
2027 ++E)
2028 E->second.Destroy();
2029
2030 Visible.ShadowMaps.pop_back();
2031 }
2032};
2033
2034} // end anonymous namespace
2035
2036void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2037 if (DeclOrVector.isNull()) {
2038 // 0 - > 1 elements: just set the single element information.
2039 DeclOrVector = ND;
2040 return;
2041 }
2042
2043 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2044 // 1 -> 2 elements: create the vector of results and push in the
2045 // existing declaration.
2046 DeclVector *Vec = new DeclVector;
2047 Vec->push_back(PrevND);
2048 DeclOrVector = Vec;
2049 }
2050
2051 // Add the new element to the end of the vector.
2052 DeclOrVector.get<DeclVector*>()->push_back(ND);
2053}
2054
2055void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2056 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2057 delete Vec;
2058 DeclOrVector = ((NamedDecl *)0);
2059 }
2060}
2061
2062VisibleDeclsRecord::ShadowMapEntry::iterator
2063VisibleDeclsRecord::ShadowMapEntry::begin() {
2064 if (DeclOrVector.isNull())
2065 return 0;
2066
2067 if (DeclOrVector.dyn_cast<NamedDecl *>())
2068 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2069
2070 return DeclOrVector.get<DeclVector *>()->begin();
2071}
2072
2073VisibleDeclsRecord::ShadowMapEntry::iterator
2074VisibleDeclsRecord::ShadowMapEntry::end() {
2075 if (DeclOrVector.isNull())
2076 return 0;
2077
2078 if (DeclOrVector.dyn_cast<NamedDecl *>())
2079 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2080
2081 return DeclOrVector.get<DeclVector *>()->end();
2082}
2083
2084NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002085 // Look through using declarations.
2086 ND = ND->getUnderlyingDecl();
2087
Douglas Gregor546be3c2009-12-30 17:04:44 +00002088 unsigned IDNS = ND->getIdentifierNamespace();
2089 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2090 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2091 SM != SMEnd; ++SM) {
2092 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2093 if (Pos == SM->end())
2094 continue;
2095
2096 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2097 IEnd = Pos->second.end();
2098 I != IEnd; ++I) {
2099 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002100 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor546be3c2009-12-30 17:04:44 +00002101 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2102 Decl::IDNS_ObjCProtocol)))
2103 continue;
2104
2105 // Protocols are in distinct namespaces from everything else.
2106 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2107 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2108 (*I)->getIdentifierNamespace() != IDNS)
2109 continue;
2110
Douglas Gregor0cc84042010-01-14 15:47:35 +00002111 // Functions and function templates in the same scope overload
2112 // rather than hide. FIXME: Look for hiding based on function
2113 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002114 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002115 ND->isFunctionOrFunctionTemplate() &&
2116 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002117 continue;
2118
Douglas Gregor546be3c2009-12-30 17:04:44 +00002119 // We've found a declaration that hides this one.
2120 return *I;
2121 }
2122 }
2123
2124 return 0;
2125}
2126
2127static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2128 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002129 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002130 VisibleDeclConsumer &Consumer,
2131 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002132 if (!Ctx)
2133 return;
2134
Douglas Gregor546be3c2009-12-30 17:04:44 +00002135 // Make sure we don't visit the same context twice.
2136 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2137 return;
2138
2139 // Enumerate all of the results in this context.
2140 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2141 CurCtx = CurCtx->getNextContext()) {
2142 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2143 DEnd = CurCtx->decls_end();
2144 D != DEnd; ++D) {
2145 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2146 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002147 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002148 Visited.add(ND);
2149 }
2150
2151 // Visit transparent contexts inside this context.
2152 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2153 if (InnerCtx->isTransparentContext())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002154 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002155 Consumer, Visited);
2156 }
2157 }
2158 }
2159
2160 // Traverse using directives for qualified name lookup.
2161 if (QualifiedNameLookup) {
2162 ShadowContextRAII Shadow(Visited);
2163 DeclContext::udir_iterator I, E;
2164 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2165 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002166 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002167 }
2168 }
2169
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002170 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002171 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002172 if (!Record->hasDefinition())
2173 return;
2174
Douglas Gregor546be3c2009-12-30 17:04:44 +00002175 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2176 BEnd = Record->bases_end();
2177 B != BEnd; ++B) {
2178 QualType BaseType = B->getType();
2179
2180 // Don't look into dependent bases, because name lookup can't look
2181 // there anyway.
2182 if (BaseType->isDependentType())
2183 continue;
2184
2185 const RecordType *Record = BaseType->getAs<RecordType>();
2186 if (!Record)
2187 continue;
2188
2189 // FIXME: It would be nice to be able to determine whether referencing
2190 // a particular member would be ambiguous. For example, given
2191 //
2192 // struct A { int member; };
2193 // struct B { int member; };
2194 // struct C : A, B { };
2195 //
2196 // void f(C *c) { c->### }
2197 //
2198 // accessing 'member' would result in an ambiguity. However, we
2199 // could be smart enough to qualify the member with the base
2200 // class, e.g.,
2201 //
2202 // c->B::member
2203 //
2204 // or
2205 //
2206 // c->A::member
2207
2208 // Find results in this base class (and its bases).
2209 ShadowContextRAII Shadow(Visited);
2210 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002211 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002212 }
2213 }
2214
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002215 // Traverse the contexts of Objective-C classes.
2216 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2217 // Traverse categories.
2218 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2219 Category; Category = Category->getNextClassCategory()) {
2220 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002221 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2222 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002223 }
2224
2225 // Traverse protocols.
2226 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2227 E = IFace->protocol_end(); I != E; ++I) {
2228 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002229 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2230 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002231 }
2232
2233 // Traverse the superclass.
2234 if (IFace->getSuperClass()) {
2235 ShadowContextRAII Shadow(Visited);
2236 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002237 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002238 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002239
2240 // If there is an implementation, traverse it. We do this to find
2241 // synthesized ivars.
2242 if (IFace->getImplementation()) {
2243 ShadowContextRAII Shadow(Visited);
2244 LookupVisibleDecls(IFace->getImplementation(), Result,
2245 QualifiedNameLookup, true, Consumer, Visited);
2246 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002247 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2248 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2249 E = Protocol->protocol_end(); I != E; ++I) {
2250 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002251 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2252 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002253 }
2254 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2255 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2256 E = Category->protocol_end(); I != E; ++I) {
2257 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002258 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2259 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002260 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002261
2262 // If there is an implementation, traverse it.
2263 if (Category->getImplementation()) {
2264 ShadowContextRAII Shadow(Visited);
2265 LookupVisibleDecls(Category->getImplementation(), Result,
2266 QualifiedNameLookup, true, Consumer, Visited);
2267 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002268 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002269}
2270
2271static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2272 UnqualUsingDirectiveSet &UDirs,
2273 VisibleDeclConsumer &Consumer,
2274 VisibleDeclsRecord &Visited) {
2275 if (!S)
2276 return;
2277
Douglas Gregor539c5c32010-01-07 00:31:29 +00002278 if (!S->getEntity() || !S->getParent() ||
2279 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2280 // Walk through the declarations in this Scope.
2281 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2282 D != DEnd; ++D) {
2283 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2284 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002285 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002286 Visited.add(ND);
2287 }
2288 }
2289 }
2290
Douglas Gregor711be1e2010-03-15 14:33:29 +00002291 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002292 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002293 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002294 // Look into this scope's declaration context, along with any of its
2295 // parent lookup contexts (e.g., enclosing classes), up to the point
2296 // where we hit the context stored in the next outer scope.
2297 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002298 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor546be3c2009-12-30 17:04:44 +00002299
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002300 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002301 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002302 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2303 if (Method->isInstanceMethod()) {
2304 // For instance methods, look for ivars in the method's interface.
2305 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2306 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor62021192010-02-04 23:42:48 +00002307 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2308 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2309 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002310 }
2311
2312 // We've already performed all of the name lookup that we need
2313 // to for Objective-C methods; the next context will be the
2314 // outer scope.
2315 break;
2316 }
2317
Douglas Gregor546be3c2009-12-30 17:04:44 +00002318 if (Ctx->isFunctionOrMethod())
2319 continue;
2320
2321 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002322 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002323 }
2324 } else if (!S->getParent()) {
2325 // Look into the translation unit scope. We walk through the translation
2326 // unit's declaration context, because the Scope itself won't have all of
2327 // the declarations if we loaded a precompiled header.
2328 // FIXME: We would like the translation unit's Scope object to point to the
2329 // translation unit, so we don't need this special "if" branch. However,
2330 // doing so would force the normal C++ name-lookup code to look into the
2331 // translation unit decl when the IdentifierInfo chains would suffice.
2332 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002333 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002334 Entity = Result.getSema().Context.getTranslationUnitDecl();
2335 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002336 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002337 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002338
2339 if (Entity) {
2340 // Lookup visible declarations in any namespaces found by using
2341 // directives.
2342 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2343 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2344 for (; UI != UEnd; ++UI)
2345 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002346 Result, /*QualifiedNameLookup=*/false,
2347 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002348 }
2349
2350 // Lookup names in the parent scope.
2351 ShadowContextRAII Shadow(Visited);
2352 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2353}
2354
2355void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2356 VisibleDeclConsumer &Consumer) {
2357 // Determine the set of using directives available during
2358 // unqualified name lookup.
2359 Scope *Initial = S;
2360 UnqualUsingDirectiveSet UDirs;
2361 if (getLangOptions().CPlusPlus) {
2362 // Find the first namespace or translation-unit scope.
2363 while (S && !isNamespaceOrTranslationUnitScope(S))
2364 S = S->getParent();
2365
2366 UDirs.visitScopeChain(Initial, S);
2367 }
2368 UDirs.done();
2369
2370 // Look for visible declarations.
2371 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2372 VisibleDeclsRecord Visited;
2373 ShadowContextRAII Shadow(Visited);
2374 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2375}
2376
2377void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2378 VisibleDeclConsumer &Consumer) {
2379 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2380 VisibleDeclsRecord Visited;
2381 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002382 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2383 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002384}
2385
2386//----------------------------------------------------------------------------
2387// Typo correction
2388//----------------------------------------------------------------------------
2389
2390namespace {
2391class TypoCorrectionConsumer : public VisibleDeclConsumer {
2392 /// \brief The name written that is a typo in the source.
2393 llvm::StringRef Typo;
2394
2395 /// \brief The results found that have the smallest edit distance
2396 /// found (so far) with the typo name.
2397 llvm::SmallVector<NamedDecl *, 4> BestResults;
2398
Douglas Gregoraaf87162010-04-14 20:04:41 +00002399 /// \brief The keywords that have the smallest edit distance.
2400 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2401
Douglas Gregor546be3c2009-12-30 17:04:44 +00002402 /// \brief The best edit distance found so far.
2403 unsigned BestEditDistance;
2404
2405public:
2406 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2407 : Typo(Typo->getName()) { }
2408
Douglas Gregor0cc84042010-01-14 15:47:35 +00002409 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002410 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002411
2412 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2413 iterator begin() const { return BestResults.begin(); }
2414 iterator end() const { return BestResults.end(); }
Douglas Gregoraaf87162010-04-14 20:04:41 +00002415 void clear_decls() { BestResults.clear(); }
2416
2417 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002418
Douglas Gregoraaf87162010-04-14 20:04:41 +00002419 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2420 keyword_iterator;
2421 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2422 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2423 bool keyword_empty() const { return BestKeywords.empty(); }
2424 unsigned keyword_size() const { return BestKeywords.size(); }
2425
2426 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002427};
2428
2429}
2430
Douglas Gregor0cc84042010-01-14 15:47:35 +00002431void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2432 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002433 // Don't consider hidden names for typo correction.
2434 if (Hiding)
2435 return;
2436
2437 // Only consider entities with identifiers for names, ignoring
2438 // special names (constructors, overloaded operators, selectors,
2439 // etc.).
2440 IdentifierInfo *Name = ND->getIdentifier();
2441 if (!Name)
2442 return;
2443
2444 // Compute the edit distance between the typo and the name of this
2445 // entity. If this edit distance is not worse than the best edit
2446 // distance we've seen so far, add it to the list of results.
2447 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregoraaf87162010-04-14 20:04:41 +00002448 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002449 if (ED < BestEditDistance) {
2450 // This result is better than any we've seen before; clear out
2451 // the previous results.
2452 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002453 BestKeywords.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002454 BestEditDistance = ED;
2455 } else if (ED > BestEditDistance) {
2456 // This result is worse than the best results we've seen so far;
2457 // ignore it.
2458 return;
2459 }
2460 } else
2461 BestEditDistance = ED;
2462
2463 BestResults.push_back(ND);
2464}
2465
Douglas Gregoraaf87162010-04-14 20:04:41 +00002466void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2467 llvm::StringRef Keyword) {
2468 // Compute the edit distance between the typo and this keyword.
2469 // If this edit distance is not worse than the best edit
2470 // distance we've seen so far, add it to the list of results.
2471 unsigned ED = Typo.edit_distance(Keyword);
2472 if (!BestResults.empty() || !BestKeywords.empty()) {
2473 if (ED < BestEditDistance) {
2474 BestResults.clear();
2475 BestKeywords.clear();
2476 BestEditDistance = ED;
2477 } else if (ED > BestEditDistance) {
2478 // This result is worse than the best results we've seen so far;
2479 // ignore it.
2480 return;
2481 }
2482 } else
2483 BestEditDistance = ED;
2484
2485 BestKeywords.push_back(&Context.Idents.get(Keyword));
2486}
2487
Douglas Gregor546be3c2009-12-30 17:04:44 +00002488/// \brief Try to "correct" a typo in the source code by finding
2489/// visible declarations whose names are similar to the name that was
2490/// present in the source code.
2491///
2492/// \param Res the \c LookupResult structure that contains the name
2493/// that was present in the source code along with the name-lookup
2494/// criteria used to search for the name. On success, this structure
2495/// will contain the results of name lookup.
2496///
2497/// \param S the scope in which name lookup occurs.
2498///
2499/// \param SS the nested-name-specifier that precedes the name we're
2500/// looking for, if present.
2501///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002502/// \param MemberContext if non-NULL, the context in which to look for
2503/// a member access expression.
2504///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002505/// \param EnteringContext whether we're entering the context described by
2506/// the nested-name-specifier SS.
2507///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002508/// \param CTC The context in which typo correction occurs, which impacts the
2509/// set of keywords permitted.
2510///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002511/// \param OPT when non-NULL, the search for visible declarations will
2512/// also walk the protocols in the qualified interfaces of \p OPT.
2513///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002514/// \returns the corrected name if the typo was corrected, otherwise returns an
2515/// empty \c DeclarationName. When a typo was corrected, the result structure
2516/// may contain the results of name lookup for the correct name or it may be
2517/// empty.
2518DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002519 DeclContext *MemberContext,
2520 bool EnteringContext,
2521 CorrectTypoContext CTC,
2522 const ObjCObjectPointerType *OPT) {
Ted Kremenek1dac3412010-01-06 00:23:04 +00002523 if (Diags.hasFatalErrorOccurred())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002524 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002525
2526 // Provide a stop gap for files that are just seriously broken. Trying
2527 // to correct all typos can turn into a HUGE performance penalty, causing
2528 // some files to take minutes to get rejected by the parser.
2529 // FIXME: Is this the right solution?
2530 if (TyposCorrected == 20)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002531 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002532 ++TyposCorrected;
Ted Kremenek1dac3412010-01-06 00:23:04 +00002533
Douglas Gregor546be3c2009-12-30 17:04:44 +00002534 // We only attempt to correct typos for identifiers.
2535 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2536 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002537 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002538
2539 // If the scope specifier itself was invalid, don't try to correct
2540 // typos.
2541 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002542 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002543
2544 // Never try to correct typos during template deduction or
2545 // instantiation.
2546 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002547 return DeclarationName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002548
Douglas Gregor546be3c2009-12-30 17:04:44 +00002549 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002550
2551 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002552 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002553 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002554
2555 // Look in qualified interfaces.
2556 if (OPT) {
2557 for (ObjCObjectPointerType::qual_iterator
2558 I = OPT->qual_begin(), E = OPT->qual_end();
2559 I != E; ++I)
2560 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2561 }
2562 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002563 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2564 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002565 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002566
2567 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2568 } else {
2569 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2570 }
2571
Douglas Gregoraaf87162010-04-14 20:04:41 +00002572 // Add context-dependent keywords.
2573 bool WantTypeSpecifiers = false;
2574 bool WantExpressionKeywords = false;
2575 bool WantCXXNamedCasts = false;
2576 bool WantRemainingKeywords = false;
2577 switch (CTC) {
2578 case CTC_Unknown:
2579 WantTypeSpecifiers = true;
2580 WantExpressionKeywords = true;
2581 WantCXXNamedCasts = true;
2582 WantRemainingKeywords = true;
2583 break;
2584
2585 case CTC_NoKeywords:
2586 break;
2587
2588 case CTC_Type:
2589 WantTypeSpecifiers = true;
2590 break;
2591
2592 case CTC_ObjCMessageReceiver:
2593 Consumer.addKeywordResult(Context, "super");
2594 // Fall through to handle message receivers like expressions.
2595
2596 case CTC_Expression:
2597 if (getLangOptions().CPlusPlus)
2598 WantTypeSpecifiers = true;
2599 WantExpressionKeywords = true;
2600 // Fall through to get C++ named casts.
2601
2602 case CTC_CXXCasts:
2603 WantCXXNamedCasts = true;
2604 break;
2605
2606 case CTC_MemberLookup:
2607 if (getLangOptions().CPlusPlus)
2608 Consumer.addKeywordResult(Context, "template");
2609 break;
2610 }
2611
2612 if (WantTypeSpecifiers) {
2613 // Add type-specifier keywords to the set of results.
2614 const char *CTypeSpecs[] = {
2615 "char", "const", "double", "enum", "float", "int", "long", "short",
2616 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2617 "_Complex", "_Imaginary",
2618 // storage-specifiers as well
2619 "extern", "inline", "static", "typedef"
2620 };
2621
2622 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2623 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2624 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2625
2626 if (getLangOptions().C99)
2627 Consumer.addKeywordResult(Context, "restrict");
2628 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2629 Consumer.addKeywordResult(Context, "bool");
2630
2631 if (getLangOptions().CPlusPlus) {
2632 Consumer.addKeywordResult(Context, "class");
2633 Consumer.addKeywordResult(Context, "typename");
2634 Consumer.addKeywordResult(Context, "wchar_t");
2635
2636 if (getLangOptions().CPlusPlus0x) {
2637 Consumer.addKeywordResult(Context, "char16_t");
2638 Consumer.addKeywordResult(Context, "char32_t");
2639 Consumer.addKeywordResult(Context, "constexpr");
2640 Consumer.addKeywordResult(Context, "decltype");
2641 Consumer.addKeywordResult(Context, "thread_local");
2642 }
2643 }
2644
2645 if (getLangOptions().GNUMode)
2646 Consumer.addKeywordResult(Context, "typeof");
2647 }
2648
2649 if (WantCXXNamedCasts) {
2650 Consumer.addKeywordResult(Context, "const_cast");
2651 Consumer.addKeywordResult(Context, "dynamic_cast");
2652 Consumer.addKeywordResult(Context, "reinterpret_cast");
2653 Consumer.addKeywordResult(Context, "static_cast");
2654 }
2655
2656 if (WantExpressionKeywords) {
2657 Consumer.addKeywordResult(Context, "sizeof");
2658 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2659 Consumer.addKeywordResult(Context, "false");
2660 Consumer.addKeywordResult(Context, "true");
2661 }
2662
2663 if (getLangOptions().CPlusPlus) {
2664 const char *CXXExprs[] = {
2665 "delete", "new", "operator", "throw", "typeid"
2666 };
2667 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2668 for (unsigned I = 0; I != NumCXXExprs; ++I)
2669 Consumer.addKeywordResult(Context, CXXExprs[I]);
2670
2671 if (isa<CXXMethodDecl>(CurContext) &&
2672 cast<CXXMethodDecl>(CurContext)->isInstance())
2673 Consumer.addKeywordResult(Context, "this");
2674
2675 if (getLangOptions().CPlusPlus0x) {
2676 Consumer.addKeywordResult(Context, "alignof");
2677 Consumer.addKeywordResult(Context, "nullptr");
2678 }
2679 }
2680 }
2681
2682 if (WantRemainingKeywords) {
2683 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2684 // Statements.
2685 const char *CStmts[] = {
2686 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2687 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2688 for (unsigned I = 0; I != NumCStmts; ++I)
2689 Consumer.addKeywordResult(Context, CStmts[I]);
2690
2691 if (getLangOptions().CPlusPlus) {
2692 Consumer.addKeywordResult(Context, "catch");
2693 Consumer.addKeywordResult(Context, "try");
2694 }
2695
2696 if (S && S->getBreakParent())
2697 Consumer.addKeywordResult(Context, "break");
2698
2699 if (S && S->getContinueParent())
2700 Consumer.addKeywordResult(Context, "continue");
2701
2702 if (!getSwitchStack().empty()) {
2703 Consumer.addKeywordResult(Context, "case");
2704 Consumer.addKeywordResult(Context, "default");
2705 }
2706 } else {
2707 if (getLangOptions().CPlusPlus) {
2708 Consumer.addKeywordResult(Context, "namespace");
2709 Consumer.addKeywordResult(Context, "template");
2710 }
2711
2712 if (S && S->isClassScope()) {
2713 Consumer.addKeywordResult(Context, "explicit");
2714 Consumer.addKeywordResult(Context, "friend");
2715 Consumer.addKeywordResult(Context, "mutable");
2716 Consumer.addKeywordResult(Context, "private");
2717 Consumer.addKeywordResult(Context, "protected");
2718 Consumer.addKeywordResult(Context, "public");
2719 Consumer.addKeywordResult(Context, "virtual");
2720 }
2721 }
2722
2723 if (getLangOptions().CPlusPlus) {
2724 Consumer.addKeywordResult(Context, "using");
2725
2726 if (getLangOptions().CPlusPlus0x)
2727 Consumer.addKeywordResult(Context, "static_assert");
2728 }
2729 }
2730
2731 // If we haven't found anything, we're done.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002732 if (Consumer.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002733 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002734
2735 // Only allow a single, closest name in the result set (it's okay to
2736 // have overloads of that name, though).
Douglas Gregoraaf87162010-04-14 20:04:41 +00002737 DeclarationName BestName;
2738 NamedDecl *BestIvarOrPropertyDecl = 0;
2739 bool FoundIvarOrPropertyDecl = false;
2740
2741 // Check all of the declaration results to find the best name so far.
2742 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2743 IEnd = Consumer.end();
2744 I != IEnd; ++I) {
2745 if (!BestName)
2746 BestName = (*I)->getDeclName();
2747 else if (BestName != (*I)->getDeclName())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002748 return DeclarationName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002749
Douglas Gregoraaf87162010-04-14 20:04:41 +00002750 // \brief Keep track of either an Objective-C ivar or a property, but not
2751 // both.
2752 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
2753 if (FoundIvarOrPropertyDecl)
2754 BestIvarOrPropertyDecl = 0;
2755 else {
2756 BestIvarOrPropertyDecl = *I;
2757 FoundIvarOrPropertyDecl = true;
2758 }
2759 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002760 }
2761
Douglas Gregoraaf87162010-04-14 20:04:41 +00002762 // Now check all of the keyword results to find the best name.
2763 switch (Consumer.keyword_size()) {
2764 case 0:
2765 // No keywords matched.
2766 break;
2767
2768 case 1:
2769 // If we already have a name
2770 if (!BestName) {
2771 // We did not have anything previously,
2772 BestName = *Consumer.keyword_begin();
2773 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
2774 // We have a declaration with the same name as a context-sensitive
2775 // keyword. The keyword takes precedence.
2776 BestIvarOrPropertyDecl = 0;
2777 FoundIvarOrPropertyDecl = false;
2778 Consumer.clear_decls();
2779 } else {
2780 // Name collision; we will not correct typos.
2781 return DeclarationName();
2782 }
2783 break;
2784
2785 default:
2786 // Name collision; we will not correct typos.
2787 return DeclarationName();
2788 }
2789
Douglas Gregor546be3c2009-12-30 17:04:44 +00002790 // BestName is the closest viable name to what the user
2791 // typed. However, to make sure that we don't pick something that's
2792 // way off, make sure that the user typed at least 3 characters for
2793 // each correction.
2794 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002795 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
2796 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002797 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002798
2799 // Perform name lookup again with the name we chose, and declare
2800 // success if we found something that was not ambiguous.
2801 Res.clear();
2802 Res.setLookupName(BestName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002803
2804 // If we found an ivar or property, add that result; no further
2805 // lookup is required.
Douglas Gregoraaf87162010-04-14 20:04:41 +00002806 if (BestIvarOrPropertyDecl)
2807 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002808 // If we're looking into the context of a member, perform qualified
2809 // name lookup on the best name.
Douglas Gregoraaf87162010-04-14 20:04:41 +00002810 else if (!Consumer.keyword_empty()) {
2811 // The best match was a keyword. Return it.
2812 return BestName;
2813 } else if (MemberContext)
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002814 LookupQualifiedName(Res, MemberContext);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002815 // Perform lookup as if we had just parsed the best name.
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002816 else
2817 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2818 EnteringContext);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002819
2820 if (Res.isAmbiguous()) {
2821 Res.suppressDiagnostics();
Douglas Gregor931f98a2010-04-14 17:09:22 +00002822 return DeclarationName();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002823 }
2824
Douglas Gregor931f98a2010-04-14 17:09:22 +00002825 if (Res.getResultKind() != LookupResult::NotFound)
2826 return BestName;
2827
2828 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002829}