blob: fc5c8e868db71877984c8695be87f9056c09d682 [file] [log] [blame]
Douglas Gregor34074322009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor34074322009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6538c932009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2d435302009-12-30 17:04:44 +000030#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000031#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000032#include <vector>
33#include <iterator>
34#include <utility>
35#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000036
37using namespace clang;
38
John McCallf6c8a4e2009-11-10 07:01:13 +000039namespace {
40 class UnqualUsingEntry {
41 const DeclContext *Nominated;
42 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000043
John McCallf6c8a4e2009-11-10 07:01:13 +000044 public:
45 UnqualUsingEntry(const DeclContext *Nominated,
46 const DeclContext *CommonAncestor)
47 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
48 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000049
John McCallf6c8a4e2009-11-10 07:01:13 +000050 const DeclContext *getCommonAncestor() const {
51 return CommonAncestor;
52 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000053
John McCallf6c8a4e2009-11-10 07:01:13 +000054 const DeclContext *getNominatedNamespace() const {
55 return Nominated;
56 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 // Sort by the pointer value of the common ancestor.
59 struct Comparator {
60 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
61 return L.getCommonAncestor() < R.getCommonAncestor();
62 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
65 return E.getCommonAncestor() < DC;
66 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000067
John McCallf6c8a4e2009-11-10 07:01:13 +000068 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
69 return DC < E.getCommonAncestor();
70 }
71 };
72 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 /// A collection of using directives, as used by C++ unqualified
75 /// lookup.
76 class UnqualUsingDirectiveSet {
77 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000078
John McCallf6c8a4e2009-11-10 07:01:13 +000079 ListTy list;
80 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 public:
83 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000084
John McCallf6c8a4e2009-11-10 07:01:13 +000085 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
86 // C++ [namespace.udir]p1:
87 // During unqualified name lookup, the names appear as if they
88 // were declared in the nearest enclosing namespace which contains
89 // both the using-directive and the nominated namespace.
90 DeclContext *InnermostFileDC
91 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
92 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000093
John McCallf6c8a4e2009-11-10 07:01:13 +000094 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +000095 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
96 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
97 visit(Ctx, EffectiveDC);
98 } else {
99 Scope::udir_iterator I = S->using_directives_begin(),
100 End = S->using_directives_end();
101
102 for (; I != End; ++I)
103 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
104 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000105 }
106 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000107
108 // Visits a context and collect all of its using directives
109 // recursively. Treats all using directives as if they were
110 // declared in the context.
111 //
112 // A given context is only every visited once, so it is important
113 // that contexts be visited from the inside out in order to get
114 // the effective DCs right.
115 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
116 if (!visited.insert(DC))
117 return;
118
119 addUsingDirectives(DC, EffectiveDC);
120 }
121
122 // Visits a using directive and collects all of its using
123 // directives recursively. Treats all using directives as if they
124 // were declared in the effective DC.
125 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
126 DeclContext *NS = UD->getNominatedNamespace();
127 if (!visited.insert(NS))
128 return;
129
130 addUsingDirective(UD, EffectiveDC);
131 addUsingDirectives(NS, EffectiveDC);
132 }
133
134 // Adds all the using directives in a context (and those nominated
135 // by its using directives, transitively) as if they appeared in
136 // the given effective context.
137 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
138 llvm::SmallVector<DeclContext*,4> queue;
139 while (true) {
140 DeclContext::udir_iterator I, End;
141 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
142 UsingDirectiveDecl *UD = *I;
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (visited.insert(NS)) {
145 addUsingDirective(UD, EffectiveDC);
146 queue.push_back(NS);
147 }
148 }
149
150 if (queue.empty())
151 return;
152
153 DC = queue.back();
154 queue.pop_back();
155 }
156 }
157
158 // Add a using directive as if it had been declared in the given
159 // context. This helps implement C++ [namespace.udir]p3:
160 // The using-directive is transitive: if a scope contains a
161 // using-directive that nominates a second namespace that itself
162 // contains using-directives, the effect is as if the
163 // using-directives from the second namespace also appeared in
164 // the first.
165 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
166 // Find the common ancestor between the effective context and
167 // the nominated namespace.
168 DeclContext *Common = UD->getNominatedNamespace();
169 while (!Common->Encloses(EffectiveDC))
170 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000171 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000172
173 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
174 }
175
176 void done() {
177 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
178 }
179
180 typedef ListTy::iterator iterator;
181 typedef ListTy::const_iterator const_iterator;
182
183 iterator begin() { return list.begin(); }
184 iterator end() { return list.end(); }
185 const_iterator begin() const { return list.begin(); }
186 const_iterator end() const { return list.end(); }
187
188 std::pair<const_iterator,const_iterator>
189 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000190 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000191 UnqualUsingEntry::Comparator());
192 }
193 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000194}
195
Douglas Gregor889ceb72009-02-03 19:21:40 +0000196// Retrieve the set of identifier namespaces that correspond to a
197// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000198static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
199 bool CPlusPlus,
200 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000201 unsigned IDNS = 0;
202 switch (NameKind) {
203 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000204 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000205 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000206 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCallea305ed2009-12-18 10:40:03 +0000208 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
209 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210 break;
211
John McCallb9467b62010-04-24 01:30:58 +0000212 case Sema::LookupOperatorName:
213 // Operator lookup is its own crazy thing; it is not the same
214 // as (e.g.) looking up an operator name for redeclaration.
215 assert(!Redeclaration && "cannot do redeclaration operator lookup");
216 IDNS = Decl::IDNS_NonMemberOperator;
217 break;
218
Douglas Gregor889ceb72009-02-03 19:21:40 +0000219 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000220 if (CPlusPlus) {
221 IDNS = Decl::IDNS_Type;
222
223 // When looking for a redeclaration of a tag name, we add:
224 // 1) TagFriend to find undeclared friend decls
225 // 2) Namespace because they can't "overload" with tag decls.
226 // 3) Tag because it includes class templates, which can't
227 // "overload" with tag decls.
228 if (Redeclaration)
229 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
230 } else {
231 IDNS = Decl::IDNS_Tag;
232 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000233 break;
234
235 case Sema::LookupMemberName:
236 IDNS = Decl::IDNS_Member;
237 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000238 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000239 break;
240
241 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000242 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
243 break;
244
Douglas Gregor889ceb72009-02-03 19:21:40 +0000245 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000246 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000247 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000248
John McCall84d87672009-12-10 09:41:52 +0000249 case Sema::LookupUsingDeclName:
250 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
251 | Decl::IDNS_Member | Decl::IDNS_Using;
252 break;
253
Douglas Gregor79947a22009-04-24 00:11:27 +0000254 case Sema::LookupObjCProtocolName:
255 IDNS = Decl::IDNS_ObjCProtocol;
256 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000257 }
258 return IDNS;
259}
260
John McCallea305ed2009-12-18 10:40:03 +0000261void LookupResult::configure() {
262 IDNS = getIDNS(LookupKind,
263 SemaRef.getLangOptions().CPlusPlus,
264 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000265
266 // If we're looking for one of the allocation or deallocation
267 // operators, make sure that the implicitly-declared new and delete
268 // operators can be found.
269 if (!isForRedeclaration()) {
270 switch (Name.getCXXOverloadedOperator()) {
271 case OO_New:
272 case OO_Delete:
273 case OO_Array_New:
274 case OO_Array_Delete:
275 SemaRef.DeclareGlobalNewDelete();
276 break;
277
278 default:
279 break;
280 }
281 }
John McCallea305ed2009-12-18 10:40:03 +0000282}
283
John McCall9f3059a2009-10-09 21:13:30 +0000284// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000285void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000286 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000287}
288
John McCall283b9012009-11-22 00:44:51 +0000289/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000290void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000291 unsigned N = Decls.size();
John McCall84d87672009-12-10 09:41:52 +0000292
John McCall9f3059a2009-10-09 21:13:30 +0000293 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000294 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000295 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000296 return;
297 }
298
John McCall283b9012009-11-22 00:44:51 +0000299 // If there's a single decl, we need to examine it to decide what
300 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000301 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000302 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
303 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000304 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000305 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000306 ResultKind = FoundUnresolvedValue;
307 return;
308 }
John McCall9f3059a2009-10-09 21:13:30 +0000309
John McCall6538c932009-10-10 05:48:19 +0000310 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000311 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000312
John McCall9f3059a2009-10-09 21:13:30 +0000313 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
314
315 bool Ambiguous = false;
316 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000317 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000318
319 unsigned UniqueTagIndex = 0;
320
321 unsigned I = 0;
322 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000323 NamedDecl *D = Decls[I]->getUnderlyingDecl();
324 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000325
John McCallf0f1cf02009-11-17 07:50:12 +0000326 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000327 // If it's not unique, pull something off the back (and
328 // continue at this index).
329 Decls[I] = Decls[--N];
John McCall9f3059a2009-10-09 21:13:30 +0000330 } else {
331 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000332
333 if (isa<UnresolvedUsingValueDecl>(D)) {
334 HasUnresolved = true;
335 } else if (isa<TagDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000336 if (HasTag)
337 Ambiguous = true;
338 UniqueTagIndex = I;
339 HasTag = true;
John McCall283b9012009-11-22 00:44:51 +0000340 } else if (isa<FunctionTemplateDecl>(D)) {
341 HasFunction = true;
342 HasFunctionTemplate = true;
343 } else if (isa<FunctionDecl>(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000344 HasFunction = true;
345 } else {
346 if (HasNonFunction)
347 Ambiguous = true;
348 HasNonFunction = true;
349 }
350 I++;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000351 }
Mike Stump11289f42009-09-09 15:08:12 +0000352 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000353
John McCall9f3059a2009-10-09 21:13:30 +0000354 // C++ [basic.scope.hiding]p2:
355 // A class name or enumeration name can be hidden by the name of
356 // an object, function, or enumerator declared in the same
357 // scope. If a class or enumeration name and an object, function,
358 // or enumerator are declared in the same scope (in any order)
359 // with the same name, the class or enumeration name is hidden
360 // wherever the object, function, or enumerator name is visible.
361 // But it's still an error if there are distinct tag types found,
362 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000363 if (HideTags && HasTag && !Ambiguous &&
364 (HasFunction || HasNonFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000365 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000366
John McCall9f3059a2009-10-09 21:13:30 +0000367 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000368
John McCall80053822009-12-03 00:58:24 +0000369 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000370 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000371
John McCall9f3059a2009-10-09 21:13:30 +0000372 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000373 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000374 else if (HasUnresolved)
375 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000376 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000377 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000378 else
John McCall27b18f82009-11-17 02:14:36 +0000379 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000380}
381
John McCall5cebab12009-11-18 07:57:50 +0000382void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000383 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000384 DeclContext::lookup_iterator DI, DE;
385 for (I = P.begin(), E = P.end(); I != E; ++I)
386 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
387 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000388}
389
John McCall5cebab12009-11-18 07:57:50 +0000390void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000391 Paths = new CXXBasePaths;
392 Paths->swap(P);
393 addDeclsFromBasePaths(*Paths);
394 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000395 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000396}
397
John McCall5cebab12009-11-18 07:57:50 +0000398void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000399 Paths = new CXXBasePaths;
400 Paths->swap(P);
401 addDeclsFromBasePaths(*Paths);
402 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000403 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000404}
405
John McCall5cebab12009-11-18 07:57:50 +0000406void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000407 Out << Decls.size() << " result(s)";
408 if (isAmbiguous()) Out << ", ambiguous";
409 if (Paths) Out << ", base paths present";
410
411 for (iterator I = begin(), E = end(); I != E; ++I) {
412 Out << "\n";
413 (*I)->print(Out, 2);
414 }
415}
416
Douglas Gregord3a59182010-02-12 05:48:04 +0000417/// \brief Lookup a builtin function, when name lookup would otherwise
418/// fail.
419static bool LookupBuiltin(Sema &S, LookupResult &R) {
420 Sema::LookupNameKind NameKind = R.getLookupKind();
421
422 // If we didn't find a use of this identifier, and if the identifier
423 // corresponds to a compiler builtin, create the decl object for the builtin
424 // now, injecting it into translation unit scope, and return it.
425 if (NameKind == Sema::LookupOrdinaryName ||
426 NameKind == Sema::LookupRedeclarationWithLinkage) {
427 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
428 if (II) {
429 // If this is a builtin on this (or all) targets, create the decl.
430 if (unsigned BuiltinID = II->getBuiltinID()) {
431 // In C++, we don't have any predefined library functions like
432 // 'malloc'. Instead, we'll just error.
433 if (S.getLangOptions().CPlusPlus &&
434 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
435 return false;
436
437 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
438 S.TUScope, R.isForRedeclaration(),
439 R.getNameLoc());
440 if (D)
441 R.addDecl(D);
442 return (D != NULL);
443 }
444 }
445 }
446
447 return false;
448}
449
Douglas Gregor7454c562010-07-02 20:37:36 +0000450/// \brief Determine whether we can declare a special member function within
451/// the class at this point.
452static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
453 const CXXRecordDecl *Class) {
454 // We need to have a definition for the class.
455 if (!Class->getDefinition() || Class->isDependentContext())
456 return false;
457
458 // We can't be in the middle of defining the class.
459 if (const RecordType *RecordTy
460 = Context.getTypeDeclType(Class)->getAs<RecordType>())
461 return !RecordTy->isBeingDefined();
462
463 return false;
464}
465
466void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
467 // If the destructor has not yet been declared, do so now.
468 if (CanDeclareSpecialMemberFunction(Context, Class) &&
469 !Class->hasDeclaredDestructor())
470 DeclareImplicitDestructor(Class);
471}
472
473
John McCall9f3059a2009-10-09 21:13:30 +0000474// Adds all qualifying matches for a name within a decl context to the
475// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000476static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000477 bool Found = false;
478
Douglas Gregor7454c562010-07-02 20:37:36 +0000479 // Lazily declare C++ special member functions.
480 if (S.getLangOptions().CPlusPlus) {
481 switch (R.getLookupName().getNameKind()) {
482 case DeclarationName::CXXDestructorName:
483 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
484 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
485 CanDeclareSpecialMemberFunction(S.Context, Record))
486 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
487
488 break;
489
490 default:
491 break;
492 }
493 }
494
495 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000496 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000497 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000498 NamedDecl *D = *I;
499 if (R.isAcceptableDecl(D)) {
500 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000501 Found = true;
502 }
503 }
John McCall9f3059a2009-10-09 21:13:30 +0000504
Douglas Gregord3a59182010-02-12 05:48:04 +0000505 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
506 return true;
507
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000508 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000509 != DeclarationName::CXXConversionFunctionName ||
510 R.getLookupName().getCXXNameType()->isDependentType() ||
511 !isa<CXXRecordDecl>(DC))
512 return Found;
513
514 // C++ [temp.mem]p6:
515 // A specialization of a conversion function template is not found by
516 // name lookup. Instead, any conversion function templates visible in the
517 // context of the use are considered. [...]
518 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
519 if (!Record->isDefinition())
520 return Found;
521
522 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
523 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
524 UEnd = Unresolved->end(); U != UEnd; ++U) {
525 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
526 if (!ConvTemplate)
527 continue;
528
529 // When we're performing lookup for the purposes of redeclaration, just
530 // add the conversion function template. When we deduce template
531 // arguments for specializations, we'll end up unifying the return
532 // type of the new declaration with the type of the function template.
533 if (R.isForRedeclaration()) {
534 R.addDecl(ConvTemplate);
535 Found = true;
536 continue;
537 }
538
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000539 // C++ [temp.mem]p6:
Chandler Carruth3a693b72010-01-31 11:44:02 +0000540 // [...] For each such operator, if argument deduction succeeds
541 // (14.9.2.3), the resulting specialization is used as if found by
542 // name lookup.
543 //
544 // When referencing a conversion function for any purpose other than
545 // a redeclaration (such that we'll be building an expression with the
546 // result), perform template argument deduction and place the
547 // specialization into the result set. We do this to avoid forcing all
548 // callers to perform special deduction for conversion functions.
John McCallbc077cf2010-02-08 23:07:23 +0000549 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000550 FunctionDecl *Specialization = 0;
551
552 const FunctionProtoType *ConvProto
553 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
554 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000555
Chandler Carruth3a693b72010-01-31 11:44:02 +0000556 // Compute the type of the function that we would expect the conversion
557 // function to have, if it were to match the name given.
558 // FIXME: Calling convention!
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000559 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruth3a693b72010-01-31 11:44:02 +0000560 QualType ExpectedType
561 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
562 0, 0, ConvProto->isVariadic(),
563 ConvProto->getTypeQuals(),
564 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000565 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruth3a693b72010-01-31 11:44:02 +0000566
567 // Perform template argument deduction against the type that we would
568 // expect the function to have.
569 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
570 Specialization, Info)
571 == Sema::TDK_Success) {
572 R.addDecl(Specialization);
573 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000574 }
575 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000576
John McCall9f3059a2009-10-09 21:13:30 +0000577 return Found;
578}
579
John McCallf6c8a4e2009-11-10 07:01:13 +0000580// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000581static bool
Douglas Gregord3a59182010-02-12 05:48:04 +0000582CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
583 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000584
585 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
586
John McCallf6c8a4e2009-11-10 07:01:13 +0000587 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000588 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000589
John McCallf6c8a4e2009-11-10 07:01:13 +0000590 // Perform direct name lookup into the namespaces nominated by the
591 // using directives whose common ancestor is this namespace.
592 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
593 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000594
John McCallf6c8a4e2009-11-10 07:01:13 +0000595 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000596 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000597 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000598
599 R.resolveKind();
600
601 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000602}
603
604static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000605 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000606 return Ctx->isFileContext();
607 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000608}
Douglas Gregored8f2882009-01-30 01:04:22 +0000609
Douglas Gregor66230062010-03-15 14:33:29 +0000610// Find the next outer declaration context from this scope. This
611// routine actually returns the semantic outer context, which may
612// differ from the lexical context (encoded directly in the Scope
613// stack) when we are parsing a member of a class template. In this
614// case, the second element of the pair will be true, to indicate that
615// name lookup should continue searching in this semantic context when
616// it leaves the current template parameter scope.
617static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
618 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
619 DeclContext *Lexical = 0;
620 for (Scope *OuterS = S->getParent(); OuterS;
621 OuterS = OuterS->getParent()) {
622 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000623 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000624 break;
625 }
626 }
627
628 // C++ [temp.local]p8:
629 // In the definition of a member of a class template that appears
630 // outside of the namespace containing the class template
631 // definition, the name of a template-parameter hides the name of
632 // a member of this namespace.
633 //
634 // Example:
635 //
636 // namespace N {
637 // class C { };
638 //
639 // template<class T> class B {
640 // void f(T);
641 // };
642 // }
643 //
644 // template<class C> void N::B<C>::f(C) {
645 // C b; // C is the template parameter, not N::C
646 // }
647 //
648 // In this example, the lexical context we return is the
649 // TranslationUnit, while the semantic context is the namespace N.
650 if (!Lexical || !DC || !S->getParent() ||
651 !S->getParent()->isTemplateParamScope())
652 return std::make_pair(Lexical, false);
653
654 // Find the outermost template parameter scope.
655 // For the example, this is the scope for the template parameters of
656 // template<class C>.
657 Scope *OutermostTemplateScope = S->getParent();
658 while (OutermostTemplateScope->getParent() &&
659 OutermostTemplateScope->getParent()->isTemplateParamScope())
660 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregor7f737c02009-09-10 16:57:35 +0000661
Douglas Gregor66230062010-03-15 14:33:29 +0000662 // Find the namespace context in which the original scope occurs. In
663 // the example, this is namespace N.
664 DeclContext *Semantic = DC;
665 while (!Semantic->isFileContext())
666 Semantic = Semantic->getParent();
667
668 // Find the declaration context just outside of the template
669 // parameter scope. This is the context in which the template is
670 // being lexically declaration (a namespace context). In the
671 // example, this is the global scope.
672 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
673 Lexical->Encloses(Semantic))
674 return std::make_pair(Semantic, true);
675
676 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000677}
678
John McCall27b18f82009-11-17 02:14:36 +0000679bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000680 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000681
682 DeclarationName Name = R.getLookupName();
683
Douglas Gregor889ceb72009-02-03 19:21:40 +0000684 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000685 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000686 I = IdResolver.begin(Name),
687 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000688
Douglas Gregor889ceb72009-02-03 19:21:40 +0000689 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000690 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000691 // ...During unqualified name lookup (3.4.1), the names appear as if
692 // they were declared in the nearest enclosing namespace which contains
693 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000694 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000695 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000696 //
697 // For example:
698 // namespace A { int i; }
699 // void foo() {
700 // int i;
701 // {
702 // using namespace A;
703 // ++i; // finds local 'i', A::i appears at global scope
704 // }
705 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000706 //
Douglas Gregor66230062010-03-15 14:33:29 +0000707 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000708 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000709 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
710
Douglas Gregor889ceb72009-02-03 19:21:40 +0000711 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000712 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000713 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000714 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000715 Found = true;
716 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000717 }
718 }
John McCall9f3059a2009-10-09 21:13:30 +0000719 if (Found) {
720 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000721 if (S->isClassScope())
722 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
723 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000724 return true;
725 }
726
Douglas Gregor66230062010-03-15 14:33:29 +0000727 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
728 S->getParent() && !S->getParent()->isTemplateParamScope()) {
729 // We've just searched the last template parameter scope and
730 // found nothing, so look into the the contexts between the
731 // lexical and semantic declaration contexts returned by
732 // findOuterContext(). This implements the name lookup behavior
733 // of C++ [temp.local]p8.
734 Ctx = OutsideOfTemplateParamDC;
735 OutsideOfTemplateParamDC = 0;
736 }
737
738 if (Ctx) {
739 DeclContext *OuterCtx;
740 bool SearchAfterTemplateScope;
741 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
742 if (SearchAfterTemplateScope)
743 OutsideOfTemplateParamDC = OuterCtx;
744
Douglas Gregorea166062010-03-15 15:26:48 +0000745 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000746 // We do not directly look into transparent contexts, since
747 // those entities will be found in the nearest enclosing
748 // non-transparent context.
749 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000750 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000751
752 // We do not look directly into function or method contexts,
753 // since all of the local variables and parameters of the
754 // function/method are present within the Scope.
755 if (Ctx->isFunctionOrMethod()) {
756 // If we have an Objective-C instance method, look for ivars
757 // in the corresponding interface.
758 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
759 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
760 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
761 ObjCInterfaceDecl *ClassDeclared;
762 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
763 Name.getAsIdentifierInfo(),
764 ClassDeclared)) {
765 if (R.isAcceptableDecl(Ivar)) {
766 R.addDecl(Ivar);
767 R.resolveKind();
768 return true;
769 }
770 }
771 }
772 }
773
774 continue;
775 }
776
Douglas Gregor7f737c02009-09-10 16:57:35 +0000777 // Perform qualified name lookup into this context.
778 // FIXME: In some cases, we know that every name that could be found by
779 // this qualified name lookup will also be on the identifier chain. For
780 // example, inside a class without any base classes, we never need to
781 // perform qualified lookup because all of the members are on top of the
782 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000783 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000784 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000785 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000786 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000787 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000788
John McCallf6c8a4e2009-11-10 07:01:13 +0000789 // Stop if we ran out of scopes.
790 // FIXME: This really, really shouldn't be happening.
791 if (!S) return false;
792
Douglas Gregor700792c2009-02-05 19:25:20 +0000793 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000794 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000795 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000796 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
797 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000798
John McCallf6c8a4e2009-11-10 07:01:13 +0000799 UnqualUsingDirectiveSet UDirs;
800 UDirs.visitScopeChain(Initial, S);
801 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000802
Douglas Gregor700792c2009-02-05 19:25:20 +0000803 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000804 // Unqualified name lookup in C++ requires looking into scopes
805 // that aren't strictly lexical, and therefore we walk through the
806 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000807
Douglas Gregor889ceb72009-02-03 19:21:40 +0000808 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000809 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000810 bool Found = false;
Chris Lattner83f095c2009-03-28 19:18:32 +0000811 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000812 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000813 // We found something. Look for anything else in our scope
814 // with this same name and in an acceptable identifier
815 // namespace, so that we can construct an overload set if we
816 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000817 Found = true;
818 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000819 }
820 }
821
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000822 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000823 R.resolveKind();
824 return true;
825 }
826
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000827 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
828 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
829 S->getParent() && !S->getParent()->isTemplateParamScope()) {
830 // We've just searched the last template parameter scope and
831 // found nothing, so look into the the contexts between the
832 // lexical and semantic declaration contexts returned by
833 // findOuterContext(). This implements the name lookup behavior
834 // of C++ [temp.local]p8.
835 Ctx = OutsideOfTemplateParamDC;
836 OutsideOfTemplateParamDC = 0;
837 }
838
839 if (Ctx) {
840 DeclContext *OuterCtx;
841 bool SearchAfterTemplateScope;
842 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
843 if (SearchAfterTemplateScope)
844 OutsideOfTemplateParamDC = OuterCtx;
845
846 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
847 // We do not directly look into transparent contexts, since
848 // those entities will be found in the nearest enclosing
849 // non-transparent context.
850 if (Ctx->isTransparentContext())
851 continue;
852
853 // If we have a context, and it's not a context stashed in the
854 // template parameter scope for an out-of-line definition, also
855 // look into that context.
856 if (!(Found && S && S->isTemplateParamScope())) {
857 assert(Ctx->isFileContext() &&
858 "We should have been looking only at file context here already.");
859
860 // Look into context considering using-directives.
861 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
862 Found = true;
863 }
864
865 if (Found) {
866 R.resolveKind();
867 return true;
868 }
869
870 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
871 return false;
872 }
873 }
874
Douglas Gregor3ce74932010-02-05 07:07:10 +0000875 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000876 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000877 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000878
John McCall9f3059a2009-10-09 21:13:30 +0000879 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +0000880}
881
Douglas Gregor34074322009-01-14 22:20:51 +0000882/// @brief Perform unqualified name lookup starting from a given
883/// scope.
884///
885/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
886/// used to find names within the current scope. For example, 'x' in
887/// @code
888/// int x;
889/// int f() {
890/// return x; // unqualified name look finds 'x' in the global scope
891/// }
892/// @endcode
893///
894/// Different lookup criteria can find different names. For example, a
895/// particular scope can have both a struct and a function of the same
896/// name, and each can be found by certain lookup criteria. For more
897/// information about lookup criteria, see the documentation for the
898/// class LookupCriteria.
899///
900/// @param S The scope from which unqualified name lookup will
901/// begin. If the lookup criteria permits, name lookup may also search
902/// in the parent scopes.
903///
904/// @param Name The name of the entity that we are searching for.
905///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000906/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000907/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000908/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000909///
910/// @returns The result of name lookup, which includes zero or more
911/// declarations and possibly additional information used to diagnose
912/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +0000913bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
914 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +0000915 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000916
John McCall27b18f82009-11-17 02:14:36 +0000917 LookupNameKind NameKind = R.getLookupKind();
918
Douglas Gregor34074322009-01-14 22:20:51 +0000919 if (!getLangOptions().CPlusPlus) {
920 // Unqualified name lookup in C/Objective-C is purely lexical, so
921 // search in the declarations attached to the name.
922
John McCallea305ed2009-12-18 10:40:03 +0000923 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000924 // Find the nearest non-transparent declaration scope.
925 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000926 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000927 static_cast<DeclContext *>(S->getEntity())
928 ->isTransparentContext()))
929 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +0000930 }
931
John McCallea305ed2009-12-18 10:40:03 +0000932 unsigned IDNS = R.getIdentifierNamespace();
933
Douglas Gregor34074322009-01-14 22:20:51 +0000934 // Scan up the scope chain looking for a decl that matches this
935 // identifier that is in the appropriate namespace. This search
936 // should not take long, as shadowing of names is uncommon, and
937 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000938 bool LeftStartingScope = false;
939
Douglas Gregored8f2882009-01-30 01:04:22 +0000940 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000941 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000942 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000943 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000944 if (NameKind == LookupRedeclarationWithLinkage) {
945 // Determine whether this (or a previous) declaration is
946 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000947 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000948 LeftStartingScope = true;
949
950 // If we found something outside of our starting scope that
951 // does not have linkage, skip it.
952 if (LeftStartingScope && !((*I)->hasLinkage()))
953 continue;
954 }
955
John McCall9f3059a2009-10-09 21:13:30 +0000956 R.addDecl(*I);
957
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000958 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000959 // If this declaration has the "overloadable" attribute, we
960 // might have a set of overloaded functions.
961
962 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000963 while (!(S->getFlags() & Scope::DeclScope) ||
964 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000965 S = S->getParent();
966
967 // Find the last declaration in this scope (with the same
968 // name, naturally).
969 IdentifierResolver::iterator LastI = I;
970 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000971 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000972 break;
John McCall9f3059a2009-10-09 21:13:30 +0000973 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000974 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000975 }
976
John McCall9f3059a2009-10-09 21:13:30 +0000977 R.resolveKind();
978
979 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000980 }
Douglas Gregor34074322009-01-14 22:20:51 +0000981 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000982 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +0000983 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +0000984 return true;
Douglas Gregor34074322009-01-14 22:20:51 +0000985 }
986
987 // If we didn't find a use of this identifier, and if the identifier
988 // corresponds to a compiler builtin, create the decl object for the builtin
989 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +0000990 if (AllowBuiltinCreation)
991 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000992
John McCall9f3059a2009-10-09 21:13:30 +0000993 return false;
Douglas Gregor34074322009-01-14 22:20:51 +0000994}
995
John McCall6538c932009-10-10 05:48:19 +0000996/// @brief Perform qualified name lookup in the namespaces nominated by
997/// using directives by the given context.
998///
999/// C++98 [namespace.qual]p2:
1000/// Given X::m (where X is a user-declared namespace), or given ::m
1001/// (where X is the global namespace), let S be the set of all
1002/// declarations of m in X and in the transitive closure of all
1003/// namespaces nominated by using-directives in X and its used
1004/// namespaces, except that using-directives are ignored in any
1005/// namespace, including X, directly containing one or more
1006/// declarations of m. No namespace is searched more than once in
1007/// the lookup of a name. If S is the empty set, the program is
1008/// ill-formed. Otherwise, if S has exactly one member, or if the
1009/// context of the reference is a using-declaration
1010/// (namespace.udecl), S is the required set of declarations of
1011/// m. Otherwise if the use of m is not one that allows a unique
1012/// declaration to be chosen from S, the program is ill-formed.
1013/// C++98 [namespace.qual]p5:
1014/// During the lookup of a qualified namespace member name, if the
1015/// lookup finds more than one declaration of the member, and if one
1016/// declaration introduces a class name or enumeration name and the
1017/// other declarations either introduce the same object, the same
1018/// enumerator or a set of functions, the non-type name hides the
1019/// class or enumeration name if and only if the declarations are
1020/// from the same namespace; otherwise (the declarations are from
1021/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001022static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001023 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001024 assert(StartDC->isFileContext() && "start context is not a file context");
1025
1026 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1027 DeclContext::udir_iterator E = StartDC->using_directives_end();
1028
1029 if (I == E) return false;
1030
1031 // We have at least added all these contexts to the queue.
1032 llvm::DenseSet<DeclContext*> Visited;
1033 Visited.insert(StartDC);
1034
1035 // We have not yet looked into these namespaces, much less added
1036 // their "using-children" to the queue.
1037 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1038
1039 // We have already looked into the initial namespace; seed the queue
1040 // with its using-children.
1041 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001042 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001043 if (Visited.insert(ND).second)
1044 Queue.push_back(ND);
1045 }
1046
1047 // The easiest way to implement the restriction in [namespace.qual]p5
1048 // is to check whether any of the individual results found a tag
1049 // and, if so, to declare an ambiguity if the final result is not
1050 // a tag.
1051 bool FoundTag = false;
1052 bool FoundNonTag = false;
1053
John McCall5cebab12009-11-18 07:57:50 +00001054 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001055
1056 bool Found = false;
1057 while (!Queue.empty()) {
1058 NamespaceDecl *ND = Queue.back();
1059 Queue.pop_back();
1060
1061 // We go through some convolutions here to avoid copying results
1062 // between LookupResults.
1063 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001064 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001065 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001066
1067 if (FoundDirect) {
1068 // First do any local hiding.
1069 DirectR.resolveKind();
1070
1071 // If the local result is a tag, remember that.
1072 if (DirectR.isSingleTagDecl())
1073 FoundTag = true;
1074 else
1075 FoundNonTag = true;
1076
1077 // Append the local results to the total results if necessary.
1078 if (UseLocal) {
1079 R.addAllDecls(LocalR);
1080 LocalR.clear();
1081 }
1082 }
1083
1084 // If we find names in this namespace, ignore its using directives.
1085 if (FoundDirect) {
1086 Found = true;
1087 continue;
1088 }
1089
1090 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1091 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1092 if (Visited.insert(Nom).second)
1093 Queue.push_back(Nom);
1094 }
1095 }
1096
1097 if (Found) {
1098 if (FoundTag && FoundNonTag)
1099 R.setAmbiguousQualifiedTagHiding();
1100 else
1101 R.resolveKind();
1102 }
1103
1104 return Found;
1105}
1106
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001107/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001108///
1109/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1110/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001111/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001112///
1113/// Different lookup criteria can find different names. For example, a
1114/// particular scope can have both a struct and a function of the same
1115/// name, and each can be found by certain lookup criteria. For more
1116/// information about lookup criteria, see the documentation for the
1117/// class LookupCriteria.
1118///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001119/// \param R captures both the lookup criteria and any lookup results found.
1120///
1121/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001122/// search. If the lookup criteria permits, name lookup may also search
1123/// in the parent contexts or (for C++ classes) base classes.
1124///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001125/// \param InUnqualifiedLookup true if this is qualified name lookup that
1126/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001127///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001128/// \returns true if lookup succeeded, false if it failed.
1129bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1130 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001131 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001132
John McCall27b18f82009-11-17 02:14:36 +00001133 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001134 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001135
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001136 // Make sure that the declaration context is complete.
1137 assert((!isa<TagDecl>(LookupCtx) ||
1138 LookupCtx->isDependentContext() ||
1139 cast<TagDecl>(LookupCtx)->isDefinition() ||
1140 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1141 ->isBeingDefined()) &&
1142 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001143
Douglas Gregor34074322009-01-14 22:20:51 +00001144 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001145 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001146 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001147 if (isa<CXXRecordDecl>(LookupCtx))
1148 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001149 return true;
1150 }
Douglas Gregor34074322009-01-14 22:20:51 +00001151
John McCall6538c932009-10-10 05:48:19 +00001152 // Don't descend into implied contexts for redeclarations.
1153 // C++98 [namespace.qual]p6:
1154 // In a declaration for a namespace member in which the
1155 // declarator-id is a qualified-id, given that the qualified-id
1156 // for the namespace member has the form
1157 // nested-name-specifier unqualified-id
1158 // the unqualified-id shall name a member of the namespace
1159 // designated by the nested-name-specifier.
1160 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001161 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001162 return false;
1163
John McCall27b18f82009-11-17 02:14:36 +00001164 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001165 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001166 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001167
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001168 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001169 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001170 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001171 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001172 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001173
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001174 // If we're performing qualified name lookup into a dependent class,
1175 // then we are actually looking into a current instantiation. If we have any
1176 // dependent base classes, then we either have to delay lookup until
1177 // template instantiation time (at which point all bases will be available)
1178 // or we have to fail.
1179 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1180 LookupRec->hasAnyDependentBases()) {
1181 R.setNotFoundInCurrentInstantiation();
1182 return false;
1183 }
1184
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001185 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001186 CXXBasePaths Paths;
1187 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001188
1189 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001190 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001191 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001192 case LookupOrdinaryName:
1193 case LookupMemberName:
1194 case LookupRedeclarationWithLinkage:
1195 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1196 break;
1197
1198 case LookupTagName:
1199 BaseCallback = &CXXRecordDecl::FindTagMember;
1200 break;
John McCall84d87672009-12-10 09:41:52 +00001201
1202 case LookupUsingDeclName:
1203 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001204
1205 case LookupOperatorName:
1206 case LookupNamespaceName:
1207 case LookupObjCProtocolName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001208 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001209 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001210
1211 case LookupNestedNameSpecifierName:
1212 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1213 break;
1214 }
1215
John McCall27b18f82009-11-17 02:14:36 +00001216 if (!LookupRec->lookupInBases(BaseCallback,
1217 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001218 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001219
John McCall553c0792010-01-23 00:46:32 +00001220 R.setNamingClass(LookupRec);
1221
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001222 // C++ [class.member.lookup]p2:
1223 // [...] If the resulting set of declarations are not all from
1224 // sub-objects of the same type, or the set has a nonstatic member
1225 // and includes members from distinct sub-objects, there is an
1226 // ambiguity and the program is ill-formed. Otherwise that set is
1227 // the result of the lookup.
1228 // FIXME: support using declarations!
1229 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001230 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001231 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001232 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001233 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001234 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001235
John McCall401982f2010-01-20 21:53:11 +00001236 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1237 // across all paths.
1238 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1239
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001240 // Determine whether we're looking at a distinct sub-object or not.
1241 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001242 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001243 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1244 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001245 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001246 != Context.getCanonicalType(PathElement.Base->getType())) {
1247 // We found members of the given name in two subobjects of
1248 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001249 R.setAmbiguousBaseSubobjectTypes(Paths);
1250 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001251 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1252 // We have a different subobject of the same type.
1253
1254 // C++ [class.member.lookup]p5:
1255 // A static member, a nested type or an enumerator defined in
1256 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001257 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001258 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001259 if (isa<VarDecl>(FirstDecl) ||
1260 isa<TypeDecl>(FirstDecl) ||
1261 isa<EnumConstantDecl>(FirstDecl))
1262 continue;
1263
1264 if (isa<CXXMethodDecl>(FirstDecl)) {
1265 // Determine whether all of the methods are static.
1266 bool AllMethodsAreStatic = true;
1267 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1268 Func != Path->Decls.second; ++Func) {
1269 if (!isa<CXXMethodDecl>(*Func)) {
1270 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1271 break;
1272 }
1273
1274 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1275 AllMethodsAreStatic = false;
1276 break;
1277 }
1278 }
1279
1280 if (AllMethodsAreStatic)
1281 continue;
1282 }
1283
1284 // We have found a nonstatic member name in multiple, distinct
1285 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001286 R.setAmbiguousBaseSubobjects(Paths);
1287 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001288 }
1289 }
1290
1291 // Lookup in a base class succeeded; return these results.
1292
John McCall9f3059a2009-10-09 21:13:30 +00001293 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001294 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1295 NamedDecl *D = *I;
1296 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1297 D->getAccess());
1298 R.addDecl(D, AS);
1299 }
John McCall9f3059a2009-10-09 21:13:30 +00001300 R.resolveKind();
1301 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001302}
1303
1304/// @brief Performs name lookup for a name that was parsed in the
1305/// source code, and may contain a C++ scope specifier.
1306///
1307/// This routine is a convenience routine meant to be called from
1308/// contexts that receive a name and an optional C++ scope specifier
1309/// (e.g., "N::M::x"). It will then perform either qualified or
1310/// unqualified name lookup (with LookupQualifiedName or LookupName,
1311/// respectively) on the given name and return those results.
1312///
1313/// @param S The scope from which unqualified name lookup will
1314/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001315///
Douglas Gregore861bac2009-08-25 22:51:20 +00001316/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001317///
1318/// @param Name The name of the entity that name lookup will
1319/// search for.
1320///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001321/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001322/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001323/// C library functions (like "malloc") are implicitly declared.
1324///
Douglas Gregore861bac2009-08-25 22:51:20 +00001325/// @param EnteringContext Indicates whether we are going to enter the
1326/// context of the scope-specifier SS (if present).
1327///
John McCall9f3059a2009-10-09 21:13:30 +00001328/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001329bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001330 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001331 if (SS && SS->isInvalid()) {
1332 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001333 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001334 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001335 }
Mike Stump11289f42009-09-09 15:08:12 +00001336
Douglas Gregore861bac2009-08-25 22:51:20 +00001337 if (SS && SS->isSet()) {
1338 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001339 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001340 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001341 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001342 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001343
John McCall27b18f82009-11-17 02:14:36 +00001344 R.setContextRange(SS->getRange());
1345
1346 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001347 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001348
Douglas Gregore861bac2009-08-25 22:51:20 +00001349 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001350 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001351 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001352 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001353 }
1354
Mike Stump11289f42009-09-09 15:08:12 +00001355 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001356 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001357}
1358
Douglas Gregor889ceb72009-02-03 19:21:40 +00001359
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001360/// @brief Produce a diagnostic describing the ambiguity that resulted
1361/// from name lookup.
1362///
1363/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001364///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001365/// @param Name The name of the entity that name lookup was
1366/// searching for.
1367///
1368/// @param NameLoc The location of the name within the source code.
1369///
1370/// @param LookupRange A source range that provides more
1371/// source-location information concerning the lookup itself. For
1372/// example, this range might highlight a nested-name-specifier that
1373/// precedes the name.
1374///
1375/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001376bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001377 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1378
John McCall27b18f82009-11-17 02:14:36 +00001379 DeclarationName Name = Result.getLookupName();
1380 SourceLocation NameLoc = Result.getNameLoc();
1381 SourceRange LookupRange = Result.getContextRange();
1382
John McCall6538c932009-10-10 05:48:19 +00001383 switch (Result.getAmbiguityKind()) {
1384 case LookupResult::AmbiguousBaseSubobjects: {
1385 CXXBasePaths *Paths = Result.getBasePaths();
1386 QualType SubobjectType = Paths->front().back().Base->getType();
1387 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1388 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1389 << LookupRange;
1390
1391 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1392 while (isa<CXXMethodDecl>(*Found) &&
1393 cast<CXXMethodDecl>(*Found)->isStatic())
1394 ++Found;
1395
1396 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1397
1398 return true;
1399 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001400
John McCall6538c932009-10-10 05:48:19 +00001401 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001402 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1403 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001404
1405 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001406 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001407 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1408 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001409 Path != PathEnd; ++Path) {
1410 Decl *D = *Path->Decls.first;
1411 if (DeclsPrinted.insert(D).second)
1412 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1413 }
1414
Douglas Gregor1c846b02009-01-16 00:38:09 +00001415 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001416 }
1417
John McCall6538c932009-10-10 05:48:19 +00001418 case LookupResult::AmbiguousTagHiding: {
1419 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001420
John McCall6538c932009-10-10 05:48:19 +00001421 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1422
1423 LookupResult::iterator DI, DE = Result.end();
1424 for (DI = Result.begin(); DI != DE; ++DI)
1425 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1426 TagDecls.insert(TD);
1427 Diag(TD->getLocation(), diag::note_hidden_tag);
1428 }
1429
1430 for (DI = Result.begin(); DI != DE; ++DI)
1431 if (!isa<TagDecl>(*DI))
1432 Diag((*DI)->getLocation(), diag::note_hiding_object);
1433
1434 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001435 LookupResult::Filter F = Result.makeFilter();
1436 while (F.hasNext()) {
1437 if (TagDecls.count(F.next()))
1438 F.erase();
1439 }
1440 F.done();
John McCall6538c932009-10-10 05:48:19 +00001441
1442 return true;
1443 }
1444
1445 case LookupResult::AmbiguousReference: {
1446 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001447
John McCall6538c932009-10-10 05:48:19 +00001448 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1449 for (; DI != DE; ++DI)
1450 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001451
John McCall6538c932009-10-10 05:48:19 +00001452 return true;
1453 }
1454 }
1455
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001456 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001457 return true;
1458}
Douglas Gregore254f902009-02-04 00:32:51 +00001459
John McCallf24d7bb2010-05-28 18:45:08 +00001460namespace {
1461 struct AssociatedLookup {
1462 AssociatedLookup(Sema &S,
1463 Sema::AssociatedNamespaceSet &Namespaces,
1464 Sema::AssociatedClassSet &Classes)
1465 : S(S), Namespaces(Namespaces), Classes(Classes) {
1466 }
1467
1468 Sema &S;
1469 Sema::AssociatedNamespaceSet &Namespaces;
1470 Sema::AssociatedClassSet &Classes;
1471 };
1472}
1473
Mike Stump11289f42009-09-09 15:08:12 +00001474static void
John McCallf24d7bb2010-05-28 18:45:08 +00001475addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001476
Douglas Gregor8b895222010-04-30 07:08:38 +00001477static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1478 DeclContext *Ctx) {
1479 // Add the associated namespace for this class.
1480
1481 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1482 // be a locally scoped record.
1483
1484 while (Ctx->isRecord() || Ctx->isTransparentContext())
1485 Ctx = Ctx->getParent();
1486
John McCallc7e8e792009-08-07 22:18:02 +00001487 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001488 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001489}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001490
Mike Stump11289f42009-09-09 15:08:12 +00001491// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001492// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001493static void
John McCallf24d7bb2010-05-28 18:45:08 +00001494addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1495 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001496 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001497 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001498 switch (Arg.getKind()) {
1499 case TemplateArgument::Null:
1500 break;
Mike Stump11289f42009-09-09 15:08:12 +00001501
Douglas Gregor197e5f72009-07-08 07:51:57 +00001502 case TemplateArgument::Type:
1503 // [...] the namespaces and classes associated with the types of the
1504 // template arguments provided for template type parameters (excluding
1505 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001506 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001507 break;
Mike Stump11289f42009-09-09 15:08:12 +00001508
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001509 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001510 // [...] the namespaces in which any template template arguments are
1511 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001512 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001513 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001514 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001515 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001516 DeclContext *Ctx = ClassTemplate->getDeclContext();
1517 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001518 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001519 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001520 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001521 }
1522 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001523 }
1524
1525 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001526 case TemplateArgument::Integral:
1527 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001528 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001529 // associated namespaces. ]
1530 break;
Mike Stump11289f42009-09-09 15:08:12 +00001531
Douglas Gregor197e5f72009-07-08 07:51:57 +00001532 case TemplateArgument::Pack:
1533 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1534 PEnd = Arg.pack_end();
1535 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001536 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001537 break;
1538 }
1539}
1540
Douglas Gregore254f902009-02-04 00:32:51 +00001541// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001542// argument-dependent lookup with an argument of class type
1543// (C++ [basic.lookup.koenig]p2).
1544static void
John McCallf24d7bb2010-05-28 18:45:08 +00001545addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1546 CXXRecordDecl *Class) {
1547
1548 // Just silently ignore anything whose name is __va_list_tag.
1549 if (Class->getDeclName() == Result.S.VAListTagName)
1550 return;
1551
Douglas Gregore254f902009-02-04 00:32:51 +00001552 // C++ [basic.lookup.koenig]p2:
1553 // [...]
1554 // -- If T is a class type (including unions), its associated
1555 // classes are: the class itself; the class of which it is a
1556 // member, if any; and its direct and indirect base
1557 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001558 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001559
1560 // Add the class of which it is a member, if any.
1561 DeclContext *Ctx = Class->getDeclContext();
1562 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001563 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001564 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001565 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001566
Douglas Gregore254f902009-02-04 00:32:51 +00001567 // Add the class itself. If we've already seen this class, we don't
1568 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001569 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001570 return;
1571
Mike Stump11289f42009-09-09 15:08:12 +00001572 // -- If T is a template-id, its associated namespaces and classes are
1573 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001574 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001575 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001576 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001577 // namespaces in which any template template arguments are defined; and
1578 // the classes in which any member templates used as template template
1579 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001580 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001581 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001582 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1583 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1584 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001585 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001586 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001587 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001588
Douglas Gregor197e5f72009-07-08 07:51:57 +00001589 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1590 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001591 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001592 }
Mike Stump11289f42009-09-09 15:08:12 +00001593
John McCall67da35c2010-02-04 22:26:26 +00001594 // Only recurse into base classes for complete types.
1595 if (!Class->hasDefinition()) {
1596 // FIXME: we might need to instantiate templates here
1597 return;
1598 }
1599
Douglas Gregore254f902009-02-04 00:32:51 +00001600 // Add direct and indirect base classes along with their associated
1601 // namespaces.
1602 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1603 Bases.push_back(Class);
1604 while (!Bases.empty()) {
1605 // Pop this class off the stack.
1606 Class = Bases.back();
1607 Bases.pop_back();
1608
1609 // Visit the base classes.
1610 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1611 BaseEnd = Class->bases_end();
1612 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001613 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001614 // In dependent contexts, we do ADL twice, and the first time around,
1615 // the base type might be a dependent TemplateSpecializationType, or a
1616 // TemplateTypeParmType. If that happens, simply ignore it.
1617 // FIXME: If we want to support export, we probably need to add the
1618 // namespace of the template in a TemplateSpecializationType, or even
1619 // the classes and namespaces of known non-dependent arguments.
1620 if (!BaseType)
1621 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001622 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001623 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001624 // Find the associated namespace for this base class.
1625 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001626 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001627
1628 // Make sure we visit the bases of this base class.
1629 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1630 Bases.push_back(BaseDecl);
1631 }
1632 }
1633 }
1634}
1635
1636// \brief Add the associated classes and namespaces for
1637// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001638// (C++ [basic.lookup.koenig]p2).
1639static void
John McCallf24d7bb2010-05-28 18:45:08 +00001640addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001641 // C++ [basic.lookup.koenig]p2:
1642 //
1643 // For each argument type T in the function call, there is a set
1644 // of zero or more associated namespaces and a set of zero or more
1645 // associated classes to be considered. The sets of namespaces and
1646 // classes is determined entirely by the types of the function
1647 // arguments (and the namespace of any template template
1648 // argument). Typedef names and using-declarations used to specify
1649 // the types do not contribute to this set. The sets of namespaces
1650 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001651
John McCall0af3d3b2010-05-28 06:08:54 +00001652 llvm::SmallVector<const Type *, 16> Queue;
1653 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1654
Douglas Gregore254f902009-02-04 00:32:51 +00001655 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001656 switch (T->getTypeClass()) {
1657
1658#define TYPE(Class, Base)
1659#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1660#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1661#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1662#define ABSTRACT_TYPE(Class, Base)
1663#include "clang/AST/TypeNodes.def"
1664 // T is canonical. We can also ignore dependent types because
1665 // we don't need to do ADL at the definition point, but if we
1666 // wanted to implement template export (or if we find some other
1667 // use for associated classes and namespaces...) this would be
1668 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001669 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001670
John McCall0af3d3b2010-05-28 06:08:54 +00001671 // -- If T is a pointer to U or an array of U, its associated
1672 // namespaces and classes are those associated with U.
1673 case Type::Pointer:
1674 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1675 continue;
1676 case Type::ConstantArray:
1677 case Type::IncompleteArray:
1678 case Type::VariableArray:
1679 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1680 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001681
John McCall0af3d3b2010-05-28 06:08:54 +00001682 // -- If T is a fundamental type, its associated sets of
1683 // namespaces and classes are both empty.
1684 case Type::Builtin:
1685 break;
1686
1687 // -- If T is a class type (including unions), its associated
1688 // classes are: the class itself; the class of which it is a
1689 // member, if any; and its direct and indirect base
1690 // classes. Its associated namespaces are the namespaces in
1691 // which its associated classes are defined.
1692 case Type::Record: {
1693 CXXRecordDecl *Class
1694 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001695 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001696 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001697 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001698
John McCall0af3d3b2010-05-28 06:08:54 +00001699 // -- If T is an enumeration type, its associated namespace is
1700 // the namespace in which it is defined. If it is class
1701 // member, its associated class is the member’s class; else
1702 // it has no associated class.
1703 case Type::Enum: {
1704 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001705
John McCall0af3d3b2010-05-28 06:08:54 +00001706 DeclContext *Ctx = Enum->getDeclContext();
1707 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001708 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001709
John McCall0af3d3b2010-05-28 06:08:54 +00001710 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001711 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001712
John McCall0af3d3b2010-05-28 06:08:54 +00001713 break;
1714 }
1715
1716 // -- If T is a function type, its associated namespaces and
1717 // classes are those associated with the function parameter
1718 // types and those associated with the return type.
1719 case Type::FunctionProto: {
1720 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1721 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1722 ArgEnd = Proto->arg_type_end();
1723 Arg != ArgEnd; ++Arg)
1724 Queue.push_back(Arg->getTypePtr());
1725 // fallthrough
1726 }
1727 case Type::FunctionNoProto: {
1728 const FunctionType *FnType = cast<FunctionType>(T);
1729 T = FnType->getResultType().getTypePtr();
1730 continue;
1731 }
1732
1733 // -- If T is a pointer to a member function of a class X, its
1734 // associated namespaces and classes are those associated
1735 // with the function parameter types and return type,
1736 // together with those associated with X.
1737 //
1738 // -- If T is a pointer to a data member of class X, its
1739 // associated namespaces and classes are those associated
1740 // with the member type together with those associated with
1741 // X.
1742 case Type::MemberPointer: {
1743 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1744
1745 // Queue up the class type into which this points.
1746 Queue.push_back(MemberPtr->getClass());
1747
1748 // And directly continue with the pointee type.
1749 T = MemberPtr->getPointeeType().getTypePtr();
1750 continue;
1751 }
1752
1753 // As an extension, treat this like a normal pointer.
1754 case Type::BlockPointer:
1755 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1756 continue;
1757
1758 // References aren't covered by the standard, but that's such an
1759 // obvious defect that we cover them anyway.
1760 case Type::LValueReference:
1761 case Type::RValueReference:
1762 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1763 continue;
1764
1765 // These are fundamental types.
1766 case Type::Vector:
1767 case Type::ExtVector:
1768 case Type::Complex:
1769 break;
1770
1771 // These are ignored by ADL.
1772 case Type::ObjCObject:
1773 case Type::ObjCInterface:
1774 case Type::ObjCObjectPointer:
1775 break;
1776 }
1777
1778 if (Queue.empty()) break;
1779 T = Queue.back();
1780 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001781 }
Douglas Gregore254f902009-02-04 00:32:51 +00001782}
1783
1784/// \brief Find the associated classes and namespaces for
1785/// argument-dependent lookup for a call with the given set of
1786/// arguments.
1787///
1788/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001789/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001790/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001791void
Douglas Gregore254f902009-02-04 00:32:51 +00001792Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1793 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001794 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001795 AssociatedNamespaces.clear();
1796 AssociatedClasses.clear();
1797
John McCallf24d7bb2010-05-28 18:45:08 +00001798 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1799
Douglas Gregore254f902009-02-04 00:32:51 +00001800 // C++ [basic.lookup.koenig]p2:
1801 // For each argument type T in the function call, there is a set
1802 // of zero or more associated namespaces and a set of zero or more
1803 // associated classes to be considered. The sets of namespaces and
1804 // classes is determined entirely by the types of the function
1805 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001806 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001807 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1808 Expr *Arg = Args[ArgIdx];
1809
1810 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00001811 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001812 continue;
1813 }
1814
1815 // [...] In addition, if the argument is the name or address of a
1816 // set of overloaded functions and/or function templates, its
1817 // associated classes and namespaces are the union of those
1818 // associated with each of the members of the set: the namespace
1819 // in which the function or function template is defined and the
1820 // classes and namespaces associated with its (non-dependent)
1821 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001822 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001823 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1824 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1825 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001826
John McCallf24d7bb2010-05-28 18:45:08 +00001827 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1828 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00001829
John McCallf24d7bb2010-05-28 18:45:08 +00001830 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1831 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001832 // Look through any using declarations to find the underlying function.
1833 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001834
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001835 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1836 if (!FDecl)
1837 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001838
1839 // Add the classes and namespaces associated with the parameter
1840 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00001841 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001842 }
1843 }
1844}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001845
1846/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1847/// an acceptable non-member overloaded operator for a call whose
1848/// arguments have types T1 (and, if non-empty, T2). This routine
1849/// implements the check in C++ [over.match.oper]p3b2 concerning
1850/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001851static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001852IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1853 QualType T1, QualType T2,
1854 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001855 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1856 return true;
1857
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001858 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1859 return true;
1860
John McCall9dd450b2009-09-21 23:43:11 +00001861 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001862 if (Proto->getNumArgs() < 1)
1863 return false;
1864
1865 if (T1->isEnumeralType()) {
1866 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001867 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001868 return true;
1869 }
1870
1871 if (Proto->getNumArgs() < 2)
1872 return false;
1873
1874 if (!T2.isNull() && T2->isEnumeralType()) {
1875 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001876 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001877 return true;
1878 }
1879
1880 return false;
1881}
1882
John McCall5cebab12009-11-18 07:57:50 +00001883NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001884 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00001885 LookupNameKind NameKind,
1886 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001887 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00001888 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00001889 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00001890}
1891
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001892/// \brief Find the protocol with the given name, if any.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001893ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
1894 SourceLocation IdLoc) {
1895 Decl *D = LookupSingleName(TUScope, II, IdLoc,
1896 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001897 return cast_or_null<ObjCProtocolDecl>(D);
1898}
1899
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001900void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001901 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00001902 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001903 // C++ [over.match.oper]p3:
1904 // -- The set of non-member candidates is the result of the
1905 // unqualified lookup of operator@ in the context of the
1906 // expression according to the usual rules for name lookup in
1907 // unqualified function calls (3.4.2) except that all member
1908 // functions are ignored. However, if no operand has a class
1909 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001910 // that have a first parameter of type T1 or "reference to
1911 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001912 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001913 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001914 // when T2 is an enumeration type, are candidate functions.
1915 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00001916 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1917 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00001918
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001919 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1920
John McCall9f3059a2009-10-09 21:13:30 +00001921 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001922 return;
1923
1924 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1925 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00001926 NamedDecl *Found = (*Op)->getUnderlyingDecl();
1927 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001928 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00001929 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001930 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00001931 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001932 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001933 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001934 // later?
1935 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00001936 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00001937 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001938 }
1939}
1940
Douglas Gregore71edda2010-07-01 22:47:18 +00001941/// \brief Look for the destructor of the given class.
1942///
1943/// During semantic analysis, this routine should be used in lieu of
1944/// CXXRecordDecl::getDestructor().
1945///
1946/// \returns The destructor for this class.
1947CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +00001948 // If the destructor has not yet been declared, do so now.
1949 if (CanDeclareSpecialMemberFunction(Context, Class) &&
1950 !Class->hasDeclaredDestructor())
1951 DeclareImplicitDestructor(Class);
1952
Douglas Gregore71edda2010-07-01 22:47:18 +00001953 return Class->getDestructor();
1954}
1955
John McCall8fe68082010-01-26 07:16:45 +00001956void ADLResult::insert(NamedDecl *New) {
1957 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
1958
1959 // If we haven't yet seen a decl for this key, or the last decl
1960 // was exactly this one, we're done.
1961 if (Old == 0 || Old == New) {
1962 Old = New;
1963 return;
1964 }
1965
1966 // Otherwise, decide which is a more recent redeclaration.
1967 FunctionDecl *OldFD, *NewFD;
1968 if (isa<FunctionTemplateDecl>(New)) {
1969 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
1970 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
1971 } else {
1972 OldFD = cast<FunctionDecl>(Old);
1973 NewFD = cast<FunctionDecl>(New);
1974 }
1975
1976 FunctionDecl *Cursor = NewFD;
1977 while (true) {
1978 Cursor = Cursor->getPreviousDeclaration();
1979
1980 // If we got to the end without finding OldFD, OldFD is the newer
1981 // declaration; leave things as they are.
1982 if (!Cursor) return;
1983
1984 // If we do find OldFD, then NewFD is newer.
1985 if (Cursor == OldFD) break;
1986
1987 // Otherwise, keep looking.
1988 }
1989
1990 Old = New;
1991}
1992
Sebastian Redlc057f422009-10-23 19:23:15 +00001993void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001994 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00001995 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001996 // Find all of the associated namespaces and classes based on the
1997 // arguments we have.
1998 AssociatedNamespaceSet AssociatedNamespaces;
1999 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002000 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002001 AssociatedNamespaces,
2002 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002003
Sebastian Redlc057f422009-10-23 19:23:15 +00002004 QualType T1, T2;
2005 if (Operator) {
2006 T1 = Args[0]->getType();
2007 if (NumArgs >= 2)
2008 T2 = Args[1]->getType();
2009 }
2010
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002011 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002012 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2013 // and let Y be the lookup set produced by argument dependent
2014 // lookup (defined as follows). If X contains [...] then Y is
2015 // empty. Otherwise Y is the set of declarations found in the
2016 // namespaces associated with the argument types as described
2017 // below. The set of declarations found by the lookup of the name
2018 // is the union of X and Y.
2019 //
2020 // Here, we compute Y and add its members to the overloaded
2021 // candidate set.
2022 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002023 NSEnd = AssociatedNamespaces.end();
2024 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002025 // When considering an associated namespace, the lookup is the
2026 // same as the lookup performed when the associated namespace is
2027 // used as a qualifier (3.4.3.2) except that:
2028 //
2029 // -- Any using-directives in the associated namespace are
2030 // ignored.
2031 //
John McCallc7e8e792009-08-07 22:18:02 +00002032 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002033 // associated classes are visible within their respective
2034 // namespaces even if they are not visible during an ordinary
2035 // lookup (11.4).
2036 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002037 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002038 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002039 // If the only declaration here is an ordinary friend, consider
2040 // it only if it was declared in an associated classes.
2041 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002042 DeclContext *LexDC = D->getLexicalDeclContext();
2043 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2044 continue;
2045 }
Mike Stump11289f42009-09-09 15:08:12 +00002046
John McCall91f61fc2010-01-26 06:04:06 +00002047 if (isa<UsingShadowDecl>(D))
2048 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002049
John McCall91f61fc2010-01-26 06:04:06 +00002050 if (isa<FunctionDecl>(D)) {
2051 if (Operator &&
2052 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2053 T1, T2, Context))
2054 continue;
John McCall8fe68082010-01-26 07:16:45 +00002055 } else if (!isa<FunctionTemplateDecl>(D))
2056 continue;
2057
2058 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002059 }
2060 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002061}
Douglas Gregor2d435302009-12-30 17:04:44 +00002062
2063//----------------------------------------------------------------------------
2064// Search for all visible declarations.
2065//----------------------------------------------------------------------------
2066VisibleDeclConsumer::~VisibleDeclConsumer() { }
2067
2068namespace {
2069
2070class ShadowContextRAII;
2071
2072class VisibleDeclsRecord {
2073public:
2074 /// \brief An entry in the shadow map, which is optimized to store a
2075 /// single declaration (the common case) but can also store a list
2076 /// of declarations.
2077 class ShadowMapEntry {
2078 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2079
2080 /// \brief Contains either the solitary NamedDecl * or a vector
2081 /// of declarations.
2082 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2083
2084 public:
2085 ShadowMapEntry() : DeclOrVector() { }
2086
2087 void Add(NamedDecl *ND);
2088 void Destroy();
2089
2090 // Iteration.
2091 typedef NamedDecl **iterator;
2092 iterator begin();
2093 iterator end();
2094 };
2095
2096private:
2097 /// \brief A mapping from declaration names to the declarations that have
2098 /// this name within a particular scope.
2099 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2100
2101 /// \brief A list of shadow maps, which is used to model name hiding.
2102 std::list<ShadowMap> ShadowMaps;
2103
2104 /// \brief The declaration contexts we have already visited.
2105 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2106
2107 friend class ShadowContextRAII;
2108
2109public:
2110 /// \brief Determine whether we have already visited this context
2111 /// (and, if not, note that we are going to visit that context now).
2112 bool visitedContext(DeclContext *Ctx) {
2113 return !VisitedContexts.insert(Ctx);
2114 }
2115
2116 /// \brief Determine whether the given declaration is hidden in the
2117 /// current scope.
2118 ///
2119 /// \returns the declaration that hides the given declaration, or
2120 /// NULL if no such declaration exists.
2121 NamedDecl *checkHidden(NamedDecl *ND);
2122
2123 /// \brief Add a declaration to the current shadow map.
2124 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2125};
2126
2127/// \brief RAII object that records when we've entered a shadow context.
2128class ShadowContextRAII {
2129 VisibleDeclsRecord &Visible;
2130
2131 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2132
2133public:
2134 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2135 Visible.ShadowMaps.push_back(ShadowMap());
2136 }
2137
2138 ~ShadowContextRAII() {
2139 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2140 EEnd = Visible.ShadowMaps.back().end();
2141 E != EEnd;
2142 ++E)
2143 E->second.Destroy();
2144
2145 Visible.ShadowMaps.pop_back();
2146 }
2147};
2148
2149} // end anonymous namespace
2150
2151void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2152 if (DeclOrVector.isNull()) {
2153 // 0 - > 1 elements: just set the single element information.
2154 DeclOrVector = ND;
2155 return;
2156 }
2157
2158 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2159 // 1 -> 2 elements: create the vector of results and push in the
2160 // existing declaration.
2161 DeclVector *Vec = new DeclVector;
2162 Vec->push_back(PrevND);
2163 DeclOrVector = Vec;
2164 }
2165
2166 // Add the new element to the end of the vector.
2167 DeclOrVector.get<DeclVector*>()->push_back(ND);
2168}
2169
2170void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2171 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2172 delete Vec;
2173 DeclOrVector = ((NamedDecl *)0);
2174 }
2175}
2176
2177VisibleDeclsRecord::ShadowMapEntry::iterator
2178VisibleDeclsRecord::ShadowMapEntry::begin() {
2179 if (DeclOrVector.isNull())
2180 return 0;
2181
2182 if (DeclOrVector.dyn_cast<NamedDecl *>())
2183 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2184
2185 return DeclOrVector.get<DeclVector *>()->begin();
2186}
2187
2188VisibleDeclsRecord::ShadowMapEntry::iterator
2189VisibleDeclsRecord::ShadowMapEntry::end() {
2190 if (DeclOrVector.isNull())
2191 return 0;
2192
2193 if (DeclOrVector.dyn_cast<NamedDecl *>())
2194 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2195
2196 return DeclOrVector.get<DeclVector *>()->end();
2197}
2198
2199NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002200 // Look through using declarations.
2201 ND = ND->getUnderlyingDecl();
2202
Douglas Gregor2d435302009-12-30 17:04:44 +00002203 unsigned IDNS = ND->getIdentifierNamespace();
2204 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2205 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2206 SM != SMEnd; ++SM) {
2207 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2208 if (Pos == SM->end())
2209 continue;
2210
2211 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2212 IEnd = Pos->second.end();
2213 I != IEnd; ++I) {
2214 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002215 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor2d435302009-12-30 17:04:44 +00002216 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2217 Decl::IDNS_ObjCProtocol)))
2218 continue;
2219
2220 // Protocols are in distinct namespaces from everything else.
2221 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2222 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2223 (*I)->getIdentifierNamespace() != IDNS)
2224 continue;
2225
Douglas Gregor09bbc652010-01-14 15:47:35 +00002226 // Functions and function templates in the same scope overload
2227 // rather than hide. FIXME: Look for hiding based on function
2228 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002229 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002230 ND->isFunctionOrFunctionTemplate() &&
2231 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002232 continue;
2233
Douglas Gregor2d435302009-12-30 17:04:44 +00002234 // We've found a declaration that hides this one.
2235 return *I;
2236 }
2237 }
2238
2239 return 0;
2240}
2241
2242static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2243 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002244 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002245 VisibleDeclConsumer &Consumer,
2246 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002247 if (!Ctx)
2248 return;
2249
Douglas Gregor2d435302009-12-30 17:04:44 +00002250 // Make sure we don't visit the same context twice.
2251 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2252 return;
2253
Douglas Gregor7454c562010-07-02 20:37:36 +00002254 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2255 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2256
Douglas Gregor2d435302009-12-30 17:04:44 +00002257 // Enumerate all of the results in this context.
2258 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2259 CurCtx = CurCtx->getNextContext()) {
2260 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2261 DEnd = CurCtx->decls_end();
2262 D != DEnd; ++D) {
2263 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2264 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002265 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002266 Visited.add(ND);
2267 }
2268
2269 // Visit transparent contexts inside this context.
2270 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2271 if (InnerCtx->isTransparentContext())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002272 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002273 Consumer, Visited);
2274 }
2275 }
2276 }
2277
2278 // Traverse using directives for qualified name lookup.
2279 if (QualifiedNameLookup) {
2280 ShadowContextRAII Shadow(Visited);
2281 DeclContext::udir_iterator I, E;
2282 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2283 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002284 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002285 }
2286 }
2287
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002288 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002289 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002290 if (!Record->hasDefinition())
2291 return;
2292
Douglas Gregor2d435302009-12-30 17:04:44 +00002293 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2294 BEnd = Record->bases_end();
2295 B != BEnd; ++B) {
2296 QualType BaseType = B->getType();
2297
2298 // Don't look into dependent bases, because name lookup can't look
2299 // there anyway.
2300 if (BaseType->isDependentType())
2301 continue;
2302
2303 const RecordType *Record = BaseType->getAs<RecordType>();
2304 if (!Record)
2305 continue;
2306
2307 // FIXME: It would be nice to be able to determine whether referencing
2308 // a particular member would be ambiguous. For example, given
2309 //
2310 // struct A { int member; };
2311 // struct B { int member; };
2312 // struct C : A, B { };
2313 //
2314 // void f(C *c) { c->### }
2315 //
2316 // accessing 'member' would result in an ambiguity. However, we
2317 // could be smart enough to qualify the member with the base
2318 // class, e.g.,
2319 //
2320 // c->B::member
2321 //
2322 // or
2323 //
2324 // c->A::member
2325
2326 // Find results in this base class (and its bases).
2327 ShadowContextRAII Shadow(Visited);
2328 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002329 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002330 }
2331 }
2332
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002333 // Traverse the contexts of Objective-C classes.
2334 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2335 // Traverse categories.
2336 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2337 Category; Category = Category->getNextClassCategory()) {
2338 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002339 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2340 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002341 }
2342
2343 // Traverse protocols.
2344 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2345 E = IFace->protocol_end(); I != E; ++I) {
2346 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002347 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2348 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002349 }
2350
2351 // Traverse the superclass.
2352 if (IFace->getSuperClass()) {
2353 ShadowContextRAII Shadow(Visited);
2354 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002355 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002356 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002357
2358 // If there is an implementation, traverse it. We do this to find
2359 // synthesized ivars.
2360 if (IFace->getImplementation()) {
2361 ShadowContextRAII Shadow(Visited);
2362 LookupVisibleDecls(IFace->getImplementation(), Result,
2363 QualifiedNameLookup, true, Consumer, Visited);
2364 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002365 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2366 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2367 E = Protocol->protocol_end(); I != E; ++I) {
2368 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002369 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2370 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002371 }
2372 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2373 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2374 E = Category->protocol_end(); I != E; ++I) {
2375 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002376 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2377 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002378 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002379
2380 // If there is an implementation, traverse it.
2381 if (Category->getImplementation()) {
2382 ShadowContextRAII Shadow(Visited);
2383 LookupVisibleDecls(Category->getImplementation(), Result,
2384 QualifiedNameLookup, true, Consumer, Visited);
2385 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002386 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002387}
2388
2389static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2390 UnqualUsingDirectiveSet &UDirs,
2391 VisibleDeclConsumer &Consumer,
2392 VisibleDeclsRecord &Visited) {
2393 if (!S)
2394 return;
2395
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002396 if (!S->getEntity() || !S->getParent() ||
2397 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2398 // Walk through the declarations in this Scope.
2399 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2400 D != DEnd; ++D) {
2401 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
2402 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002403 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002404 Visited.add(ND);
2405 }
2406 }
2407 }
2408
Douglas Gregor66230062010-03-15 14:33:29 +00002409 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002410 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002411 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002412 // Look into this scope's declaration context, along with any of its
2413 // parent lookup contexts (e.g., enclosing classes), up to the point
2414 // where we hit the context stored in the next outer scope.
2415 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002416 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor2d435302009-12-30 17:04:44 +00002417
Douglas Gregorea166062010-03-15 15:26:48 +00002418 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002419 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002420 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2421 if (Method->isInstanceMethod()) {
2422 // For instance methods, look for ivars in the method's interface.
2423 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2424 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002425 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2426 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2427 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002428 }
2429
2430 // We've already performed all of the name lookup that we need
2431 // to for Objective-C methods; the next context will be the
2432 // outer scope.
2433 break;
2434 }
2435
Douglas Gregor2d435302009-12-30 17:04:44 +00002436 if (Ctx->isFunctionOrMethod())
2437 continue;
2438
2439 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002440 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002441 }
2442 } else if (!S->getParent()) {
2443 // Look into the translation unit scope. We walk through the translation
2444 // unit's declaration context, because the Scope itself won't have all of
2445 // the declarations if we loaded a precompiled header.
2446 // FIXME: We would like the translation unit's Scope object to point to the
2447 // translation unit, so we don't need this special "if" branch. However,
2448 // doing so would force the normal C++ name-lookup code to look into the
2449 // translation unit decl when the IdentifierInfo chains would suffice.
2450 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002451 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002452 Entity = Result.getSema().Context.getTranslationUnitDecl();
2453 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002454 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002455 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002456
2457 if (Entity) {
2458 // Lookup visible declarations in any namespaces found by using
2459 // directives.
2460 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2461 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2462 for (; UI != UEnd; ++UI)
2463 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002464 Result, /*QualifiedNameLookup=*/false,
2465 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002466 }
2467
2468 // Lookup names in the parent scope.
2469 ShadowContextRAII Shadow(Visited);
2470 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2471}
2472
2473void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2474 VisibleDeclConsumer &Consumer) {
2475 // Determine the set of using directives available during
2476 // unqualified name lookup.
2477 Scope *Initial = S;
2478 UnqualUsingDirectiveSet UDirs;
2479 if (getLangOptions().CPlusPlus) {
2480 // Find the first namespace or translation-unit scope.
2481 while (S && !isNamespaceOrTranslationUnitScope(S))
2482 S = S->getParent();
2483
2484 UDirs.visitScopeChain(Initial, S);
2485 }
2486 UDirs.done();
2487
2488 // Look for visible declarations.
2489 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2490 VisibleDeclsRecord Visited;
2491 ShadowContextRAII Shadow(Visited);
2492 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2493}
2494
2495void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2496 VisibleDeclConsumer &Consumer) {
2497 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2498 VisibleDeclsRecord Visited;
2499 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002500 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2501 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002502}
2503
2504//----------------------------------------------------------------------------
2505// Typo correction
2506//----------------------------------------------------------------------------
2507
2508namespace {
2509class TypoCorrectionConsumer : public VisibleDeclConsumer {
2510 /// \brief The name written that is a typo in the source.
2511 llvm::StringRef Typo;
2512
2513 /// \brief The results found that have the smallest edit distance
2514 /// found (so far) with the typo name.
2515 llvm::SmallVector<NamedDecl *, 4> BestResults;
2516
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002517 /// \brief The keywords that have the smallest edit distance.
2518 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2519
Douglas Gregor2d435302009-12-30 17:04:44 +00002520 /// \brief The best edit distance found so far.
2521 unsigned BestEditDistance;
2522
2523public:
2524 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2525 : Typo(Typo->getName()) { }
2526
Douglas Gregor09bbc652010-01-14 15:47:35 +00002527 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002528 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002529
2530 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2531 iterator begin() const { return BestResults.begin(); }
2532 iterator end() const { return BestResults.end(); }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002533 void clear_decls() { BestResults.clear(); }
2534
2535 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002536
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002537 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2538 keyword_iterator;
2539 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2540 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2541 bool keyword_empty() const { return BestKeywords.empty(); }
2542 unsigned keyword_size() const { return BestKeywords.size(); }
2543
2544 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002545};
2546
2547}
2548
Douglas Gregor09bbc652010-01-14 15:47:35 +00002549void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2550 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002551 // Don't consider hidden names for typo correction.
2552 if (Hiding)
2553 return;
2554
2555 // Only consider entities with identifiers for names, ignoring
2556 // special names (constructors, overloaded operators, selectors,
2557 // etc.).
2558 IdentifierInfo *Name = ND->getIdentifier();
2559 if (!Name)
2560 return;
2561
2562 // Compute the edit distance between the typo and the name of this
2563 // entity. If this edit distance is not worse than the best edit
2564 // distance we've seen so far, add it to the list of results.
2565 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002566 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002567 if (ED < BestEditDistance) {
2568 // This result is better than any we've seen before; clear out
2569 // the previous results.
2570 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002571 BestKeywords.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002572 BestEditDistance = ED;
2573 } else if (ED > BestEditDistance) {
2574 // This result is worse than the best results we've seen so far;
2575 // ignore it.
2576 return;
2577 }
2578 } else
2579 BestEditDistance = ED;
2580
2581 BestResults.push_back(ND);
2582}
2583
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002584void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2585 llvm::StringRef Keyword) {
2586 // Compute the edit distance between the typo and this keyword.
2587 // If this edit distance is not worse than the best edit
2588 // distance we've seen so far, add it to the list of results.
2589 unsigned ED = Typo.edit_distance(Keyword);
2590 if (!BestResults.empty() || !BestKeywords.empty()) {
2591 if (ED < BestEditDistance) {
2592 BestResults.clear();
2593 BestKeywords.clear();
2594 BestEditDistance = ED;
2595 } else if (ED > BestEditDistance) {
2596 // This result is worse than the best results we've seen so far;
2597 // ignore it.
2598 return;
2599 }
2600 } else
2601 BestEditDistance = ED;
2602
2603 BestKeywords.push_back(&Context.Idents.get(Keyword));
2604}
2605
Douglas Gregor2d435302009-12-30 17:04:44 +00002606/// \brief Try to "correct" a typo in the source code by finding
2607/// visible declarations whose names are similar to the name that was
2608/// present in the source code.
2609///
2610/// \param Res the \c LookupResult structure that contains the name
2611/// that was present in the source code along with the name-lookup
2612/// criteria used to search for the name. On success, this structure
2613/// will contain the results of name lookup.
2614///
2615/// \param S the scope in which name lookup occurs.
2616///
2617/// \param SS the nested-name-specifier that precedes the name we're
2618/// looking for, if present.
2619///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002620/// \param MemberContext if non-NULL, the context in which to look for
2621/// a member access expression.
2622///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002623/// \param EnteringContext whether we're entering the context described by
2624/// the nested-name-specifier SS.
2625///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002626/// \param CTC The context in which typo correction occurs, which impacts the
2627/// set of keywords permitted.
2628///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002629/// \param OPT when non-NULL, the search for visible declarations will
2630/// also walk the protocols in the qualified interfaces of \p OPT.
2631///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002632/// \returns the corrected name if the typo was corrected, otherwise returns an
2633/// empty \c DeclarationName. When a typo was corrected, the result structure
2634/// may contain the results of name lookup for the correct name or it may be
2635/// empty.
2636DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002637 DeclContext *MemberContext,
2638 bool EnteringContext,
2639 CorrectTypoContext CTC,
2640 const ObjCObjectPointerType *OPT) {
Ted Kremeneke51136e2010-01-06 00:23:04 +00002641 if (Diags.hasFatalErrorOccurred())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002642 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002643
2644 // Provide a stop gap for files that are just seriously broken. Trying
2645 // to correct all typos can turn into a HUGE performance penalty, causing
2646 // some files to take minutes to get rejected by the parser.
2647 // FIXME: Is this the right solution?
2648 if (TyposCorrected == 20)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002649 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002650 ++TyposCorrected;
Ted Kremeneke51136e2010-01-06 00:23:04 +00002651
Douglas Gregor2d435302009-12-30 17:04:44 +00002652 // We only attempt to correct typos for identifiers.
2653 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2654 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002655 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002656
2657 // If the scope specifier itself was invalid, don't try to correct
2658 // typos.
2659 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002660 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002661
2662 // Never try to correct typos during template deduction or
2663 // instantiation.
2664 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002665 return DeclarationName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002666
Douglas Gregor2d435302009-12-30 17:04:44 +00002667 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002668
2669 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002670 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002671 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002672
2673 // Look in qualified interfaces.
2674 if (OPT) {
2675 for (ObjCObjectPointerType::qual_iterator
2676 I = OPT->qual_begin(), E = OPT->qual_end();
2677 I != E; ++I)
2678 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2679 }
2680 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002681 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2682 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002683 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002684
2685 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2686 } else {
2687 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2688 }
2689
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002690 // Add context-dependent keywords.
2691 bool WantTypeSpecifiers = false;
2692 bool WantExpressionKeywords = false;
2693 bool WantCXXNamedCasts = false;
2694 bool WantRemainingKeywords = false;
2695 switch (CTC) {
2696 case CTC_Unknown:
2697 WantTypeSpecifiers = true;
2698 WantExpressionKeywords = true;
2699 WantCXXNamedCasts = true;
2700 WantRemainingKeywords = true;
Douglas Gregor5fd04d42010-05-18 16:14:23 +00002701
2702 if (ObjCMethodDecl *Method = getCurMethodDecl())
2703 if (Method->getClassInterface() &&
2704 Method->getClassInterface()->getSuperClass())
2705 Consumer.addKeywordResult(Context, "super");
2706
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002707 break;
2708
2709 case CTC_NoKeywords:
2710 break;
2711
2712 case CTC_Type:
2713 WantTypeSpecifiers = true;
2714 break;
2715
2716 case CTC_ObjCMessageReceiver:
2717 Consumer.addKeywordResult(Context, "super");
2718 // Fall through to handle message receivers like expressions.
2719
2720 case CTC_Expression:
2721 if (getLangOptions().CPlusPlus)
2722 WantTypeSpecifiers = true;
2723 WantExpressionKeywords = true;
2724 // Fall through to get C++ named casts.
2725
2726 case CTC_CXXCasts:
2727 WantCXXNamedCasts = true;
2728 break;
2729
2730 case CTC_MemberLookup:
2731 if (getLangOptions().CPlusPlus)
2732 Consumer.addKeywordResult(Context, "template");
2733 break;
2734 }
2735
2736 if (WantTypeSpecifiers) {
2737 // Add type-specifier keywords to the set of results.
2738 const char *CTypeSpecs[] = {
2739 "char", "const", "double", "enum", "float", "int", "long", "short",
2740 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2741 "_Complex", "_Imaginary",
2742 // storage-specifiers as well
2743 "extern", "inline", "static", "typedef"
2744 };
2745
2746 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2747 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2748 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2749
2750 if (getLangOptions().C99)
2751 Consumer.addKeywordResult(Context, "restrict");
2752 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2753 Consumer.addKeywordResult(Context, "bool");
2754
2755 if (getLangOptions().CPlusPlus) {
2756 Consumer.addKeywordResult(Context, "class");
2757 Consumer.addKeywordResult(Context, "typename");
2758 Consumer.addKeywordResult(Context, "wchar_t");
2759
2760 if (getLangOptions().CPlusPlus0x) {
2761 Consumer.addKeywordResult(Context, "char16_t");
2762 Consumer.addKeywordResult(Context, "char32_t");
2763 Consumer.addKeywordResult(Context, "constexpr");
2764 Consumer.addKeywordResult(Context, "decltype");
2765 Consumer.addKeywordResult(Context, "thread_local");
2766 }
2767 }
2768
2769 if (getLangOptions().GNUMode)
2770 Consumer.addKeywordResult(Context, "typeof");
2771 }
2772
Douglas Gregor86ad0852010-05-18 16:30:22 +00002773 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002774 Consumer.addKeywordResult(Context, "const_cast");
2775 Consumer.addKeywordResult(Context, "dynamic_cast");
2776 Consumer.addKeywordResult(Context, "reinterpret_cast");
2777 Consumer.addKeywordResult(Context, "static_cast");
2778 }
2779
2780 if (WantExpressionKeywords) {
2781 Consumer.addKeywordResult(Context, "sizeof");
2782 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2783 Consumer.addKeywordResult(Context, "false");
2784 Consumer.addKeywordResult(Context, "true");
2785 }
2786
2787 if (getLangOptions().CPlusPlus) {
2788 const char *CXXExprs[] = {
2789 "delete", "new", "operator", "throw", "typeid"
2790 };
2791 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2792 for (unsigned I = 0; I != NumCXXExprs; ++I)
2793 Consumer.addKeywordResult(Context, CXXExprs[I]);
2794
2795 if (isa<CXXMethodDecl>(CurContext) &&
2796 cast<CXXMethodDecl>(CurContext)->isInstance())
2797 Consumer.addKeywordResult(Context, "this");
2798
2799 if (getLangOptions().CPlusPlus0x) {
2800 Consumer.addKeywordResult(Context, "alignof");
2801 Consumer.addKeywordResult(Context, "nullptr");
2802 }
2803 }
2804 }
2805
2806 if (WantRemainingKeywords) {
2807 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2808 // Statements.
2809 const char *CStmts[] = {
2810 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2811 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2812 for (unsigned I = 0; I != NumCStmts; ++I)
2813 Consumer.addKeywordResult(Context, CStmts[I]);
2814
2815 if (getLangOptions().CPlusPlus) {
2816 Consumer.addKeywordResult(Context, "catch");
2817 Consumer.addKeywordResult(Context, "try");
2818 }
2819
2820 if (S && S->getBreakParent())
2821 Consumer.addKeywordResult(Context, "break");
2822
2823 if (S && S->getContinueParent())
2824 Consumer.addKeywordResult(Context, "continue");
2825
2826 if (!getSwitchStack().empty()) {
2827 Consumer.addKeywordResult(Context, "case");
2828 Consumer.addKeywordResult(Context, "default");
2829 }
2830 } else {
2831 if (getLangOptions().CPlusPlus) {
2832 Consumer.addKeywordResult(Context, "namespace");
2833 Consumer.addKeywordResult(Context, "template");
2834 }
2835
2836 if (S && S->isClassScope()) {
2837 Consumer.addKeywordResult(Context, "explicit");
2838 Consumer.addKeywordResult(Context, "friend");
2839 Consumer.addKeywordResult(Context, "mutable");
2840 Consumer.addKeywordResult(Context, "private");
2841 Consumer.addKeywordResult(Context, "protected");
2842 Consumer.addKeywordResult(Context, "public");
2843 Consumer.addKeywordResult(Context, "virtual");
2844 }
2845 }
2846
2847 if (getLangOptions().CPlusPlus) {
2848 Consumer.addKeywordResult(Context, "using");
2849
2850 if (getLangOptions().CPlusPlus0x)
2851 Consumer.addKeywordResult(Context, "static_assert");
2852 }
2853 }
2854
2855 // If we haven't found anything, we're done.
Douglas Gregor2d435302009-12-30 17:04:44 +00002856 if (Consumer.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002857 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002858
2859 // Only allow a single, closest name in the result set (it's okay to
2860 // have overloads of that name, though).
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002861 DeclarationName BestName;
2862 NamedDecl *BestIvarOrPropertyDecl = 0;
2863 bool FoundIvarOrPropertyDecl = false;
2864
2865 // Check all of the declaration results to find the best name so far.
2866 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2867 IEnd = Consumer.end();
2868 I != IEnd; ++I) {
2869 if (!BestName)
2870 BestName = (*I)->getDeclName();
2871 else if (BestName != (*I)->getDeclName())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002872 return DeclarationName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002873
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002874 // \brief Keep track of either an Objective-C ivar or a property, but not
2875 // both.
2876 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
2877 if (FoundIvarOrPropertyDecl)
2878 BestIvarOrPropertyDecl = 0;
2879 else {
2880 BestIvarOrPropertyDecl = *I;
2881 FoundIvarOrPropertyDecl = true;
2882 }
2883 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002884 }
2885
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002886 // Now check all of the keyword results to find the best name.
2887 switch (Consumer.keyword_size()) {
2888 case 0:
2889 // No keywords matched.
2890 break;
2891
2892 case 1:
2893 // If we already have a name
2894 if (!BestName) {
2895 // We did not have anything previously,
2896 BestName = *Consumer.keyword_begin();
2897 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
2898 // We have a declaration with the same name as a context-sensitive
2899 // keyword. The keyword takes precedence.
2900 BestIvarOrPropertyDecl = 0;
2901 FoundIvarOrPropertyDecl = false;
2902 Consumer.clear_decls();
Douglas Gregor86ad0852010-05-18 16:30:22 +00002903 } else if (CTC == CTC_ObjCMessageReceiver &&
2904 (*Consumer.keyword_begin())->isStr("super")) {
2905 // In an Objective-C message send, give the "super" keyword a slight
2906 // edge over entities not in function or method scope.
2907 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
2908 IEnd = Consumer.end();
2909 I != IEnd; ++I) {
2910 if ((*I)->getDeclName() == BestName) {
2911 if ((*I)->getDeclContext()->isFunctionOrMethod())
2912 return DeclarationName();
2913 }
2914 }
2915
2916 // Everything found was outside a function or method; the 'super'
2917 // keyword takes precedence.
2918 BestIvarOrPropertyDecl = 0;
2919 FoundIvarOrPropertyDecl = false;
2920 Consumer.clear_decls();
2921 BestName = *Consumer.keyword_begin();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002922 } else {
2923 // Name collision; we will not correct typos.
2924 return DeclarationName();
2925 }
2926 break;
2927
2928 default:
2929 // Name collision; we will not correct typos.
2930 return DeclarationName();
2931 }
2932
Douglas Gregor2d435302009-12-30 17:04:44 +00002933 // BestName is the closest viable name to what the user
2934 // typed. However, to make sure that we don't pick something that's
2935 // way off, make sure that the user typed at least 3 characters for
2936 // each correction.
2937 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002938 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
2939 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002940 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002941
2942 // Perform name lookup again with the name we chose, and declare
2943 // success if we found something that was not ambiguous.
2944 Res.clear();
2945 Res.setLookupName(BestName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002946
2947 // If we found an ivar or property, add that result; no further
2948 // lookup is required.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002949 if (BestIvarOrPropertyDecl)
2950 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002951 // If we're looking into the context of a member, perform qualified
2952 // name lookup on the best name.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002953 else if (!Consumer.keyword_empty()) {
2954 // The best match was a keyword. Return it.
2955 return BestName;
2956 } else if (MemberContext)
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002957 LookupQualifiedName(Res, MemberContext);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002958 // Perform lookup as if we had just parsed the best name.
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002959 else
2960 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2961 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00002962
2963 if (Res.isAmbiguous()) {
2964 Res.suppressDiagnostics();
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002965 return DeclarationName();
Douglas Gregor598b08f2009-12-31 05:20:13 +00002966 }
2967
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002968 if (Res.getResultKind() != LookupResult::NotFound)
2969 return BestName;
2970
2971 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002972}