blob: 6ff9cc69f1cf5d9bce2a444251a1c5604ac58ada [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//===----------------------------------------------------------------------===//
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
John McCall8b0666c2010-08-20 18:27:03 +000017#include "clang/Sema/DeclSpec.h"
John McCallcc14d1f2010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall19c1bfd2010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000023#include "clang/AST/Decl.h"
24#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000026#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000027#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000028#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000030#include "clang/Basic/LangOptions.h"
John McCalla1e130b2010-08-25 07:03:20 +000031#include "llvm/ADT/DenseSet.h"
Douglas Gregor34074322009-01-14 22:20:51 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000034#include "llvm/ADT/StringMap.h"
John McCall6538c932009-10-10 05:48:19 +000035#include "llvm/Support/ErrorHandling.h"
Douglas Gregor0afa7f62010-10-14 20:34:08 +000036#include <limits>
Douglas Gregor2d435302009-12-30 17:04:44 +000037#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000038#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000039#include <vector>
40#include <iterator>
41#include <utility>
42#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000043
44using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000045using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000046
John McCallf6c8a4e2009-11-10 07:01:13 +000047namespace {
48 class UnqualUsingEntry {
49 const DeclContext *Nominated;
50 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000051
John McCallf6c8a4e2009-11-10 07:01:13 +000052 public:
53 UnqualUsingEntry(const DeclContext *Nominated,
54 const DeclContext *CommonAncestor)
55 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
56 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000057
John McCallf6c8a4e2009-11-10 07:01:13 +000058 const DeclContext *getCommonAncestor() const {
59 return CommonAncestor;
60 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000061
John McCallf6c8a4e2009-11-10 07:01:13 +000062 const DeclContext *getNominatedNamespace() const {
63 return Nominated;
64 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000065
John McCallf6c8a4e2009-11-10 07:01:13 +000066 // Sort by the pointer value of the common ancestor.
67 struct Comparator {
68 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
69 return L.getCommonAncestor() < R.getCommonAncestor();
70 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000071
John McCallf6c8a4e2009-11-10 07:01:13 +000072 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
73 return E.getCommonAncestor() < DC;
74 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000075
John McCallf6c8a4e2009-11-10 07:01:13 +000076 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
77 return DC < E.getCommonAncestor();
78 }
79 };
80 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000081
John McCallf6c8a4e2009-11-10 07:01:13 +000082 /// A collection of using directives, as used by C++ unqualified
83 /// lookup.
84 class UnqualUsingDirectiveSet {
85 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000086
John McCallf6c8a4e2009-11-10 07:01:13 +000087 ListTy list;
88 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000089
John McCallf6c8a4e2009-11-10 07:01:13 +000090 public:
91 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000092
John McCallf6c8a4e2009-11-10 07:01:13 +000093 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
94 // C++ [namespace.udir]p1:
95 // During unqualified name lookup, the names appear as if they
96 // were declared in the nearest enclosing namespace which contains
97 // both the using-directive and the nominated namespace.
98 DeclContext *InnermostFileDC
99 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
100 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000101
John McCallf6c8a4e2009-11-10 07:01:13 +0000102 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000103 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
104 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
105 visit(Ctx, EffectiveDC);
106 } else {
107 Scope::udir_iterator I = S->using_directives_begin(),
108 End = S->using_directives_end();
109
110 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000111 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000112 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000113 }
114 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000115
116 // Visits a context and collect all of its using directives
117 // recursively. Treats all using directives as if they were
118 // declared in the context.
119 //
120 // A given context is only every visited once, so it is important
121 // that contexts be visited from the inside out in order to get
122 // the effective DCs right.
123 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
124 if (!visited.insert(DC))
125 return;
126
127 addUsingDirectives(DC, EffectiveDC);
128 }
129
130 // Visits a using directive and collects all of its using
131 // directives recursively. Treats all using directives as if they
132 // were declared in the effective DC.
133 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
134 DeclContext *NS = UD->getNominatedNamespace();
135 if (!visited.insert(NS))
136 return;
137
138 addUsingDirective(UD, EffectiveDC);
139 addUsingDirectives(NS, EffectiveDC);
140 }
141
142 // Adds all the using directives in a context (and those nominated
143 // by its using directives, transitively) as if they appeared in
144 // the given effective context.
145 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
146 llvm::SmallVector<DeclContext*,4> queue;
147 while (true) {
148 DeclContext::udir_iterator I, End;
149 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
150 UsingDirectiveDecl *UD = *I;
151 DeclContext *NS = UD->getNominatedNamespace();
152 if (visited.insert(NS)) {
153 addUsingDirective(UD, EffectiveDC);
154 queue.push_back(NS);
155 }
156 }
157
158 if (queue.empty())
159 return;
160
161 DC = queue.back();
162 queue.pop_back();
163 }
164 }
165
166 // Add a using directive as if it had been declared in the given
167 // context. This helps implement C++ [namespace.udir]p3:
168 // The using-directive is transitive: if a scope contains a
169 // using-directive that nominates a second namespace that itself
170 // contains using-directives, the effect is as if the
171 // using-directives from the second namespace also appeared in
172 // the first.
173 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
174 // Find the common ancestor between the effective context and
175 // the nominated namespace.
176 DeclContext *Common = UD->getNominatedNamespace();
177 while (!Common->Encloses(EffectiveDC))
178 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000179 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000180
181 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
182 }
183
184 void done() {
185 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
186 }
187
John McCallf6c8a4e2009-11-10 07:01:13 +0000188 typedef ListTy::const_iterator const_iterator;
189
John McCallf6c8a4e2009-11-10 07:01:13 +0000190 const_iterator begin() const { return list.begin(); }
191 const_iterator end() const { return list.end(); }
192
193 std::pair<const_iterator,const_iterator>
194 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000195 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 UnqualUsingEntry::Comparator());
197 }
198 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000199}
200
Douglas Gregor889ceb72009-02-03 19:21:40 +0000201// Retrieve the set of identifier namespaces that correspond to a
202// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000203static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
204 bool CPlusPlus,
205 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206 unsigned IDNS = 0;
207 switch (NameKind) {
208 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000209 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000211 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000212 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCallea305ed2009-12-18 10:40:03 +0000213 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
214 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 break;
216
John McCallb9467b62010-04-24 01:30:58 +0000217 case Sema::LookupOperatorName:
218 // Operator lookup is its own crazy thing; it is not the same
219 // as (e.g.) looking up an operator name for redeclaration.
220 assert(!Redeclaration && "cannot do redeclaration operator lookup");
221 IDNS = Decl::IDNS_NonMemberOperator;
222 break;
223
Douglas Gregor889ceb72009-02-03 19:21:40 +0000224 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000225 if (CPlusPlus) {
226 IDNS = Decl::IDNS_Type;
227
228 // When looking for a redeclaration of a tag name, we add:
229 // 1) TagFriend to find undeclared friend decls
230 // 2) Namespace because they can't "overload" with tag decls.
231 // 3) Tag because it includes class templates, which can't
232 // "overload" with tag decls.
233 if (Redeclaration)
234 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
235 } else {
236 IDNS = Decl::IDNS_Tag;
237 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000238 break;
239
240 case Sema::LookupMemberName:
241 IDNS = Decl::IDNS_Member;
242 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000244 break;
245
246 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000247 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
248 break;
249
Douglas Gregor889ceb72009-02-03 19:21:40 +0000250 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000251 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000252 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000253
John McCall84d87672009-12-10 09:41:52 +0000254 case Sema::LookupUsingDeclName:
255 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
256 | Decl::IDNS_Member | Decl::IDNS_Using;
257 break;
258
Douglas Gregor79947a22009-04-24 00:11:27 +0000259 case Sema::LookupObjCProtocolName:
260 IDNS = Decl::IDNS_ObjCProtocol;
261 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000262
263 case Sema::LookupAnyName:
264 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
265 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
266 | Decl::IDNS_Type;
267 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000268 }
269 return IDNS;
270}
271
John McCallea305ed2009-12-18 10:40:03 +0000272void LookupResult::configure() {
273 IDNS = getIDNS(LookupKind,
274 SemaRef.getLangOptions().CPlusPlus,
275 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000276
277 // If we're looking for one of the allocation or deallocation
278 // operators, make sure that the implicitly-declared new and delete
279 // operators can be found.
280 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000281 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000282 case OO_New:
283 case OO_Delete:
284 case OO_Array_New:
285 case OO_Array_Delete:
286 SemaRef.DeclareGlobalNewDelete();
287 break;
288
289 default:
290 break;
291 }
292 }
John McCallea305ed2009-12-18 10:40:03 +0000293}
294
John McCall19c1bfd2010-08-25 05:32:35 +0000295void LookupResult::sanity() const {
296 assert(ResultKind != NotFound || Decls.size() == 0);
297 assert(ResultKind != Found || Decls.size() == 1);
298 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
299 (Decls.size() == 1 &&
300 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
301 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
302 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000303 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
304 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000305 assert((Paths != NULL) == (ResultKind == Ambiguous &&
306 (Ambiguity == AmbiguousBaseSubobjectTypes ||
307 Ambiguity == AmbiguousBaseSubobjects)));
308}
John McCall19c1bfd2010-08-25 05:32:35 +0000309
John McCall9f3059a2009-10-09 21:13:30 +0000310// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000311void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000312 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000313}
314
John McCall283b9012009-11-22 00:44:51 +0000315/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000316void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000317 unsigned N = Decls.size();
John McCall84d87672009-12-10 09:41:52 +0000318
John McCall9f3059a2009-10-09 21:13:30 +0000319 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000320 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000321 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000322 return;
323 }
324
John McCall283b9012009-11-22 00:44:51 +0000325 // If there's a single decl, we need to examine it to decide what
326 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000327 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000328 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
329 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000330 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000331 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000332 ResultKind = FoundUnresolvedValue;
333 return;
334 }
John McCall9f3059a2009-10-09 21:13:30 +0000335
John McCall6538c932009-10-10 05:48:19 +0000336 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000337 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000338
John McCall9f3059a2009-10-09 21:13:30 +0000339 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000340 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
341
John McCall9f3059a2009-10-09 21:13:30 +0000342 bool Ambiguous = false;
343 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000344 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000345
346 unsigned UniqueTagIndex = 0;
347
348 unsigned I = 0;
349 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000350 NamedDecl *D = Decls[I]->getUnderlyingDecl();
351 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000352
Douglas Gregor13e65872010-08-11 14:45:53 +0000353 // Redeclarations of types via typedef can occur both within a scope
354 // and, through using declarations and directives, across scopes. There is
355 // no ambiguity if they all refer to the same type, so unique based on the
356 // canonical type.
357 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
358 if (!TD->getDeclContext()->isRecord()) {
359 QualType T = SemaRef.Context.getTypeDeclType(TD);
360 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
361 // The type is not unique; pull something off the back and continue
362 // at this index.
363 Decls[I] = Decls[--N];
364 continue;
365 }
366 }
367 }
368
John McCallf0f1cf02009-11-17 07:50:12 +0000369 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000370 // If it's not unique, pull something off the back (and
371 // continue at this index).
372 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000373 continue;
374 }
375
376 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000377
Douglas Gregor13e65872010-08-11 14:45:53 +0000378 if (isa<UnresolvedUsingValueDecl>(D)) {
379 HasUnresolved = true;
380 } else if (isa<TagDecl>(D)) {
381 if (HasTag)
382 Ambiguous = true;
383 UniqueTagIndex = I;
384 HasTag = true;
385 } else if (isa<FunctionTemplateDecl>(D)) {
386 HasFunction = true;
387 HasFunctionTemplate = true;
388 } else if (isa<FunctionDecl>(D)) {
389 HasFunction = true;
390 } else {
391 if (HasNonFunction)
392 Ambiguous = true;
393 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000394 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000395 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000396 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000397
John McCall9f3059a2009-10-09 21:13:30 +0000398 // C++ [basic.scope.hiding]p2:
399 // A class name or enumeration name can be hidden by the name of
400 // an object, function, or enumerator declared in the same
401 // scope. If a class or enumeration name and an object, function,
402 // or enumerator are declared in the same scope (in any order)
403 // with the same name, the class or enumeration name is hidden
404 // wherever the object, function, or enumerator name is visible.
405 // But it's still an error if there are distinct tag types found,
406 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000407 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregore63d0872010-10-23 16:06:17 +0000408 (HasFunction || HasNonFunction || HasUnresolved)) {
409 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
410 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
411 Decls[UniqueTagIndex] = Decls[--N];
412 else
413 Ambiguous = true;
414 }
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000415
John McCall9f3059a2009-10-09 21:13:30 +0000416 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000417
John McCall80053822009-12-03 00:58:24 +0000418 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000419 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000420
John McCall9f3059a2009-10-09 21:13:30 +0000421 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000422 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000423 else if (HasUnresolved)
424 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000425 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000426 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000427 else
John McCall27b18f82009-11-17 02:14:36 +0000428 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000429}
430
John McCall5cebab12009-11-18 07:57:50 +0000431void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000432 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000433 DeclContext::lookup_iterator DI, DE;
434 for (I = P.begin(), E = P.end(); I != E; ++I)
435 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
436 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000437}
438
John McCall5cebab12009-11-18 07:57:50 +0000439void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000440 Paths = new CXXBasePaths;
441 Paths->swap(P);
442 addDeclsFromBasePaths(*Paths);
443 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000444 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000445}
446
John McCall5cebab12009-11-18 07:57:50 +0000447void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000448 Paths = new CXXBasePaths;
449 Paths->swap(P);
450 addDeclsFromBasePaths(*Paths);
451 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000452 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000453}
454
John McCall5cebab12009-11-18 07:57:50 +0000455void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000456 Out << Decls.size() << " result(s)";
457 if (isAmbiguous()) Out << ", ambiguous";
458 if (Paths) Out << ", base paths present";
459
460 for (iterator I = begin(), E = end(); I != E; ++I) {
461 Out << "\n";
462 (*I)->print(Out, 2);
463 }
464}
465
Douglas Gregord3a59182010-02-12 05:48:04 +0000466/// \brief Lookup a builtin function, when name lookup would otherwise
467/// fail.
468static bool LookupBuiltin(Sema &S, LookupResult &R) {
469 Sema::LookupNameKind NameKind = R.getLookupKind();
470
471 // If we didn't find a use of this identifier, and if the identifier
472 // corresponds to a compiler builtin, create the decl object for the builtin
473 // now, injecting it into translation unit scope, and return it.
474 if (NameKind == Sema::LookupOrdinaryName ||
475 NameKind == Sema::LookupRedeclarationWithLinkage) {
476 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
477 if (II) {
478 // If this is a builtin on this (or all) targets, create the decl.
479 if (unsigned BuiltinID = II->getBuiltinID()) {
480 // In C++, we don't have any predefined library functions like
481 // 'malloc'. Instead, we'll just error.
482 if (S.getLangOptions().CPlusPlus &&
483 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
484 return false;
Fariborz Jahaniane8473c22010-11-30 17:35:24 +0000485
Douglas Gregord3a59182010-02-12 05:48:04 +0000486 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
487 S.TUScope, R.isForRedeclaration(),
488 R.getNameLoc());
489 if (D)
490 R.addDecl(D);
491 return (D != NULL);
492 }
493 }
494 }
495
496 return false;
497}
498
Douglas Gregor7454c562010-07-02 20:37:36 +0000499/// \brief Determine whether we can declare a special member function within
500/// the class at this point.
501static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
502 const CXXRecordDecl *Class) {
John McCall2ded5d22010-08-11 23:52:36 +0000503 // Don't do it if the class is invalid.
504 if (Class->isInvalidDecl())
505 return false;
506
Douglas Gregor7454c562010-07-02 20:37:36 +0000507 // We need to have a definition for the class.
508 if (!Class->getDefinition() || Class->isDependentContext())
509 return false;
510
511 // We can't be in the middle of defining the class.
512 if (const RecordType *RecordTy
513 = Context.getTypeDeclType(Class)->getAs<RecordType>())
514 return !RecordTy->isBeingDefined();
515
516 return false;
517}
518
519void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000520 if (!CanDeclareSpecialMemberFunction(Context, Class))
521 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000522
523 // If the default constructor has not yet been declared, do so now.
524 if (!Class->hasDeclaredDefaultConstructor())
525 DeclareImplicitDefaultConstructor(Class);
Douglas Gregora6d69502010-07-02 23:41:54 +0000526
527 // If the copy constructor has not yet been declared, do so now.
528 if (!Class->hasDeclaredCopyConstructor())
529 DeclareImplicitCopyConstructor(Class);
530
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000531 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000532 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000533 DeclareImplicitCopyAssignment(Class);
534
Douglas Gregor7454c562010-07-02 20:37:36 +0000535 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000536 if (!Class->hasDeclaredDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +0000537 DeclareImplicitDestructor(Class);
538}
539
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000540/// \brief Determine whether this is the name of an implicitly-declared
541/// special member function.
542static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
543 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000544 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000545 case DeclarationName::CXXDestructorName:
546 return true;
547
548 case DeclarationName::CXXOperatorName:
549 return Name.getCXXOverloadedOperator() == OO_Equal;
550
551 default:
552 break;
553 }
554
555 return false;
556}
557
558/// \brief If there are any implicit member functions with the given name
559/// that need to be declared in the given declaration context, do so.
560static void DeclareImplicitMemberFunctionsWithName(Sema &S,
561 DeclarationName Name,
562 const DeclContext *DC) {
563 if (!DC)
564 return;
565
566 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000567 case DeclarationName::CXXConstructorName:
568 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000569 if (Record->getDefinition() &&
570 CanDeclareSpecialMemberFunction(S.Context, Record)) {
571 if (!Record->hasDeclaredDefaultConstructor())
572 S.DeclareImplicitDefaultConstructor(
573 const_cast<CXXRecordDecl *>(Record));
574 if (!Record->hasDeclaredCopyConstructor())
575 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
576 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000577 break;
578
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000579 case DeclarationName::CXXDestructorName:
580 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
581 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
582 CanDeclareSpecialMemberFunction(S.Context, Record))
583 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000584 break;
585
586 case DeclarationName::CXXOperatorName:
587 if (Name.getCXXOverloadedOperator() != OO_Equal)
588 break;
589
590 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
591 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
592 CanDeclareSpecialMemberFunction(S.Context, Record))
593 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
594 break;
595
596 default:
597 break;
598 }
599}
Douglas Gregor7454c562010-07-02 20:37:36 +0000600
John McCall9f3059a2009-10-09 21:13:30 +0000601// Adds all qualifying matches for a name within a decl context to the
602// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000603static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000604 bool Found = false;
605
Douglas Gregor7454c562010-07-02 20:37:36 +0000606 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000607 if (S.getLangOptions().CPlusPlus)
608 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor7454c562010-07-02 20:37:36 +0000609
610 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000611 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000612 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000613 NamedDecl *D = *I;
614 if (R.isAcceptableDecl(D)) {
615 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000616 Found = true;
617 }
618 }
John McCall9f3059a2009-10-09 21:13:30 +0000619
Douglas Gregord3a59182010-02-12 05:48:04 +0000620 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
621 return true;
622
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000623 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000624 != DeclarationName::CXXConversionFunctionName ||
625 R.getLookupName().getCXXNameType()->isDependentType() ||
626 !isa<CXXRecordDecl>(DC))
627 return Found;
628
629 // C++ [temp.mem]p6:
630 // A specialization of a conversion function template is not found by
631 // name lookup. Instead, any conversion function templates visible in the
632 // context of the use are considered. [...]
633 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
634 if (!Record->isDefinition())
635 return Found;
636
637 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
638 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
639 UEnd = Unresolved->end(); U != UEnd; ++U) {
640 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
641 if (!ConvTemplate)
642 continue;
643
644 // When we're performing lookup for the purposes of redeclaration, just
645 // add the conversion function template. When we deduce template
646 // arguments for specializations, we'll end up unifying the return
647 // type of the new declaration with the type of the function template.
648 if (R.isForRedeclaration()) {
649 R.addDecl(ConvTemplate);
650 Found = true;
651 continue;
652 }
653
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000654 // C++ [temp.mem]p6:
Chandler Carruth3a693b72010-01-31 11:44:02 +0000655 // [...] For each such operator, if argument deduction succeeds
656 // (14.9.2.3), the resulting specialization is used as if found by
657 // name lookup.
658 //
659 // When referencing a conversion function for any purpose other than
660 // a redeclaration (such that we'll be building an expression with the
661 // result), perform template argument deduction and place the
662 // specialization into the result set. We do this to avoid forcing all
663 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000664 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000665 FunctionDecl *Specialization = 0;
666
667 const FunctionProtoType *ConvProto
668 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
669 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000670
Chandler Carruth3a693b72010-01-31 11:44:02 +0000671 // Compute the type of the function that we would expect the conversion
672 // function to have, if it were to match the name given.
673 // FIXME: Calling convention!
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000674 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruth3a693b72010-01-31 11:44:02 +0000675 QualType ExpectedType
676 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
677 0, 0, ConvProto->isVariadic(),
678 ConvProto->getTypeQuals(),
679 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000680 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruth3a693b72010-01-31 11:44:02 +0000681
682 // Perform template argument deduction against the type that we would
683 // expect the function to have.
684 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
685 Specialization, Info)
686 == Sema::TDK_Success) {
687 R.addDecl(Specialization);
688 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000689 }
690 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000691
John McCall9f3059a2009-10-09 21:13:30 +0000692 return Found;
693}
694
John McCallf6c8a4e2009-11-10 07:01:13 +0000695// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000696static bool
Douglas Gregord3a59182010-02-12 05:48:04 +0000697CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
698 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000699
700 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
701
John McCallf6c8a4e2009-11-10 07:01:13 +0000702 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000703 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000704
John McCallf6c8a4e2009-11-10 07:01:13 +0000705 // Perform direct name lookup into the namespaces nominated by the
706 // using directives whose common ancestor is this namespace.
707 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
708 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000709
John McCallf6c8a4e2009-11-10 07:01:13 +0000710 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000711 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000712 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000713
714 R.resolveKind();
715
716 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000717}
718
719static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000720 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000721 return Ctx->isFileContext();
722 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000723}
Douglas Gregored8f2882009-01-30 01:04:22 +0000724
Douglas Gregor66230062010-03-15 14:33:29 +0000725// Find the next outer declaration context from this scope. This
726// routine actually returns the semantic outer context, which may
727// differ from the lexical context (encoded directly in the Scope
728// stack) when we are parsing a member of a class template. In this
729// case, the second element of the pair will be true, to indicate that
730// name lookup should continue searching in this semantic context when
731// it leaves the current template parameter scope.
732static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
733 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
734 DeclContext *Lexical = 0;
735 for (Scope *OuterS = S->getParent(); OuterS;
736 OuterS = OuterS->getParent()) {
737 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000738 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000739 break;
740 }
741 }
742
743 // C++ [temp.local]p8:
744 // In the definition of a member of a class template that appears
745 // outside of the namespace containing the class template
746 // definition, the name of a template-parameter hides the name of
747 // a member of this namespace.
748 //
749 // Example:
750 //
751 // namespace N {
752 // class C { };
753 //
754 // template<class T> class B {
755 // void f(T);
756 // };
757 // }
758 //
759 // template<class C> void N::B<C>::f(C) {
760 // C b; // C is the template parameter, not N::C
761 // }
762 //
763 // In this example, the lexical context we return is the
764 // TranslationUnit, while the semantic context is the namespace N.
765 if (!Lexical || !DC || !S->getParent() ||
766 !S->getParent()->isTemplateParamScope())
767 return std::make_pair(Lexical, false);
768
769 // Find the outermost template parameter scope.
770 // For the example, this is the scope for the template parameters of
771 // template<class C>.
772 Scope *OutermostTemplateScope = S->getParent();
773 while (OutermostTemplateScope->getParent() &&
774 OutermostTemplateScope->getParent()->isTemplateParamScope())
775 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregor7f737c02009-09-10 16:57:35 +0000776
Douglas Gregor66230062010-03-15 14:33:29 +0000777 // Find the namespace context in which the original scope occurs. In
778 // the example, this is namespace N.
779 DeclContext *Semantic = DC;
780 while (!Semantic->isFileContext())
781 Semantic = Semantic->getParent();
782
783 // Find the declaration context just outside of the template
784 // parameter scope. This is the context in which the template is
785 // being lexically declaration (a namespace context). In the
786 // example, this is the global scope.
787 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
788 Lexical->Encloses(Semantic))
789 return std::make_pair(Semantic, true);
790
791 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000792}
793
John McCall27b18f82009-11-17 02:14:36 +0000794bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000795 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000796
797 DeclarationName Name = R.getLookupName();
798
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000799 // If this is the name of an implicitly-declared special member function,
800 // go through the scope stack to implicitly declare
801 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
802 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
803 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
804 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
805 }
806
807 // Implicitly declare member functions with the name we're looking for, if in
808 // fact we are in a scope where it matters.
809
Douglas Gregor889ceb72009-02-03 19:21:40 +0000810 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000811 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000812 I = IdResolver.begin(Name),
813 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000814
Douglas Gregor889ceb72009-02-03 19:21:40 +0000815 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000816 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000817 // ...During unqualified name lookup (3.4.1), the names appear as if
818 // they were declared in the nearest enclosing namespace which contains
819 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000820 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000821 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000822 //
823 // For example:
824 // namespace A { int i; }
825 // void foo() {
826 // int i;
827 // {
828 // using namespace A;
829 // ++i; // finds local 'i', A::i appears at global scope
830 // }
831 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000832 //
Douglas Gregor66230062010-03-15 14:33:29 +0000833 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000834 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000835 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
836
Douglas Gregor889ceb72009-02-03 19:21:40 +0000837 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000838 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000839 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000840 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000841 Found = true;
842 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000843 }
844 }
John McCall9f3059a2009-10-09 21:13:30 +0000845 if (Found) {
846 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000847 if (S->isClassScope())
848 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
849 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000850 return true;
851 }
852
Douglas Gregor66230062010-03-15 14:33:29 +0000853 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
854 S->getParent() && !S->getParent()->isTemplateParamScope()) {
855 // We've just searched the last template parameter scope and
856 // found nothing, so look into the the contexts between the
857 // lexical and semantic declaration contexts returned by
858 // findOuterContext(). This implements the name lookup behavior
859 // of C++ [temp.local]p8.
860 Ctx = OutsideOfTemplateParamDC;
861 OutsideOfTemplateParamDC = 0;
862 }
863
864 if (Ctx) {
865 DeclContext *OuterCtx;
866 bool SearchAfterTemplateScope;
867 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
868 if (SearchAfterTemplateScope)
869 OutsideOfTemplateParamDC = OuterCtx;
870
Douglas Gregorea166062010-03-15 15:26:48 +0000871 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000872 // We do not directly look into transparent contexts, since
873 // those entities will be found in the nearest enclosing
874 // non-transparent context.
875 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000876 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000877
878 // We do not look directly into function or method contexts,
879 // since all of the local variables and parameters of the
880 // function/method are present within the Scope.
881 if (Ctx->isFunctionOrMethod()) {
882 // If we have an Objective-C instance method, look for ivars
883 // in the corresponding interface.
884 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
885 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
886 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
887 ObjCInterfaceDecl *ClassDeclared;
888 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
889 Name.getAsIdentifierInfo(),
890 ClassDeclared)) {
891 if (R.isAcceptableDecl(Ivar)) {
892 R.addDecl(Ivar);
893 R.resolveKind();
894 return true;
895 }
896 }
897 }
898 }
899
900 continue;
901 }
902
Douglas Gregor7f737c02009-09-10 16:57:35 +0000903 // Perform qualified name lookup into this context.
904 // FIXME: In some cases, we know that every name that could be found by
905 // this qualified name lookup will also be on the identifier chain. For
906 // example, inside a class without any base classes, we never need to
907 // perform qualified lookup because all of the members are on top of the
908 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000909 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000910 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000911 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000912 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000913 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000914
John McCallf6c8a4e2009-11-10 07:01:13 +0000915 // Stop if we ran out of scopes.
916 // FIXME: This really, really shouldn't be happening.
917 if (!S) return false;
918
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000919 // If we are looking for members, no need to look into global/namespace scope.
920 if (R.getLookupKind() == LookupMemberName)
921 return false;
922
Douglas Gregor700792c2009-02-05 19:25:20 +0000923 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000924 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000925 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000926 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
927 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000928
John McCallf6c8a4e2009-11-10 07:01:13 +0000929 UnqualUsingDirectiveSet UDirs;
930 UDirs.visitScopeChain(Initial, S);
931 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000932
Douglas Gregor700792c2009-02-05 19:25:20 +0000933 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000934 // Unqualified name lookup in C++ requires looking into scopes
935 // that aren't strictly lexical, and therefore we walk through the
936 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000937
Douglas Gregor889ceb72009-02-03 19:21:40 +0000938 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000939 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000940 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000941 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000942 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000943 // We found something. Look for anything else in our scope
944 // with this same name and in an acceptable identifier
945 // namespace, so that we can construct an overload set if we
946 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000947 Found = true;
948 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000949 }
950 }
951
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000952 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000953 R.resolveKind();
954 return true;
955 }
956
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000957 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
958 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
959 S->getParent() && !S->getParent()->isTemplateParamScope()) {
960 // We've just searched the last template parameter scope and
961 // found nothing, so look into the the contexts between the
962 // lexical and semantic declaration contexts returned by
963 // findOuterContext(). This implements the name lookup behavior
964 // of C++ [temp.local]p8.
965 Ctx = OutsideOfTemplateParamDC;
966 OutsideOfTemplateParamDC = 0;
967 }
968
969 if (Ctx) {
970 DeclContext *OuterCtx;
971 bool SearchAfterTemplateScope;
972 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
973 if (SearchAfterTemplateScope)
974 OutsideOfTemplateParamDC = OuterCtx;
975
976 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
977 // We do not directly look into transparent contexts, since
978 // those entities will be found in the nearest enclosing
979 // non-transparent context.
980 if (Ctx->isTransparentContext())
981 continue;
982
983 // If we have a context, and it's not a context stashed in the
984 // template parameter scope for an out-of-line definition, also
985 // look into that context.
986 if (!(Found && S && S->isTemplateParamScope())) {
987 assert(Ctx->isFileContext() &&
988 "We should have been looking only at file context here already.");
989
990 // Look into context considering using-directives.
991 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
992 Found = true;
993 }
994
995 if (Found) {
996 R.resolveKind();
997 return true;
998 }
999
1000 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1001 return false;
1002 }
1003 }
1004
Douglas Gregor3ce74932010-02-05 07:07:10 +00001005 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001006 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001007 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001008
John McCall9f3059a2009-10-09 21:13:30 +00001009 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001010}
1011
Douglas Gregor34074322009-01-14 22:20:51 +00001012/// @brief Perform unqualified name lookup starting from a given
1013/// scope.
1014///
1015/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1016/// used to find names within the current scope. For example, 'x' in
1017/// @code
1018/// int x;
1019/// int f() {
1020/// return x; // unqualified name look finds 'x' in the global scope
1021/// }
1022/// @endcode
1023///
1024/// Different lookup criteria can find different names. For example, a
1025/// particular scope can have both a struct and a function of the same
1026/// name, and each can be found by certain lookup criteria. For more
1027/// information about lookup criteria, see the documentation for the
1028/// class LookupCriteria.
1029///
1030/// @param S The scope from which unqualified name lookup will
1031/// begin. If the lookup criteria permits, name lookup may also search
1032/// in the parent scopes.
1033///
1034/// @param Name The name of the entity that we are searching for.
1035///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001036/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001037/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001038/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001039///
1040/// @returns The result of name lookup, which includes zero or more
1041/// declarations and possibly additional information used to diagnose
1042/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001043bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1044 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001045 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001046
John McCall27b18f82009-11-17 02:14:36 +00001047 LookupNameKind NameKind = R.getLookupKind();
1048
Douglas Gregor34074322009-01-14 22:20:51 +00001049 if (!getLangOptions().CPlusPlus) {
1050 // Unqualified name lookup in C/Objective-C is purely lexical, so
1051 // search in the declarations attached to the name.
1052
John McCallea305ed2009-12-18 10:40:03 +00001053 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001054 // Find the nearest non-transparent declaration scope.
1055 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001056 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001057 static_cast<DeclContext *>(S->getEntity())
1058 ->isTransparentContext()))
1059 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001060 }
1061
John McCallea305ed2009-12-18 10:40:03 +00001062 unsigned IDNS = R.getIdentifierNamespace();
1063
Douglas Gregor34074322009-01-14 22:20:51 +00001064 // Scan up the scope chain looking for a decl that matches this
1065 // identifier that is in the appropriate namespace. This search
1066 // should not take long, as shadowing of names is uncommon, and
1067 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001068 bool LeftStartingScope = false;
1069
Douglas Gregored8f2882009-01-30 01:04:22 +00001070 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001071 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001072 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001073 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001074 if (NameKind == LookupRedeclarationWithLinkage) {
1075 // Determine whether this (or a previous) declaration is
1076 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001077 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001078 LeftStartingScope = true;
1079
1080 // If we found something outside of our starting scope that
1081 // does not have linkage, skip it.
1082 if (LeftStartingScope && !((*I)->hasLinkage()))
1083 continue;
1084 }
1085
John McCall9f3059a2009-10-09 21:13:30 +00001086 R.addDecl(*I);
1087
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001088 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001089 // If this declaration has the "overloadable" attribute, we
1090 // might have a set of overloaded functions.
1091
1092 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001093 while (!(S->getFlags() & Scope::DeclScope) ||
John McCall48871652010-08-21 09:40:31 +00001094 !S->isDeclScope(*I))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001095 S = S->getParent();
1096
1097 // Find the last declaration in this scope (with the same
1098 // name, naturally).
1099 IdentifierResolver::iterator LastI = I;
1100 for (++LastI; LastI != IEnd; ++LastI) {
John McCall48871652010-08-21 09:40:31 +00001101 if (!S->isDeclScope(*LastI))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001102 break;
John McCall9f3059a2009-10-09 21:13:30 +00001103 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001104 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001105 }
1106
John McCall9f3059a2009-10-09 21:13:30 +00001107 R.resolveKind();
1108
1109 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001110 }
Douglas Gregor34074322009-01-14 22:20:51 +00001111 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001112 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001113 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001114 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001115 }
1116
1117 // If we didn't find a use of this identifier, and if the identifier
1118 // corresponds to a compiler builtin, create the decl object for the builtin
1119 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +00001120 if (AllowBuiltinCreation)
1121 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001122
John McCall9f3059a2009-10-09 21:13:30 +00001123 return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001124}
1125
John McCall6538c932009-10-10 05:48:19 +00001126/// @brief Perform qualified name lookup in the namespaces nominated by
1127/// using directives by the given context.
1128///
1129/// C++98 [namespace.qual]p2:
1130/// Given X::m (where X is a user-declared namespace), or given ::m
1131/// (where X is the global namespace), let S be the set of all
1132/// declarations of m in X and in the transitive closure of all
1133/// namespaces nominated by using-directives in X and its used
1134/// namespaces, except that using-directives are ignored in any
1135/// namespace, including X, directly containing one or more
1136/// declarations of m. No namespace is searched more than once in
1137/// the lookup of a name. If S is the empty set, the program is
1138/// ill-formed. Otherwise, if S has exactly one member, or if the
1139/// context of the reference is a using-declaration
1140/// (namespace.udecl), S is the required set of declarations of
1141/// m. Otherwise if the use of m is not one that allows a unique
1142/// declaration to be chosen from S, the program is ill-formed.
1143/// C++98 [namespace.qual]p5:
1144/// During the lookup of a qualified namespace member name, if the
1145/// lookup finds more than one declaration of the member, and if one
1146/// declaration introduces a class name or enumeration name and the
1147/// other declarations either introduce the same object, the same
1148/// enumerator or a set of functions, the non-type name hides the
1149/// class or enumeration name if and only if the declarations are
1150/// from the same namespace; otherwise (the declarations are from
1151/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001152static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001153 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001154 assert(StartDC->isFileContext() && "start context is not a file context");
1155
1156 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1157 DeclContext::udir_iterator E = StartDC->using_directives_end();
1158
1159 if (I == E) return false;
1160
1161 // We have at least added all these contexts to the queue.
1162 llvm::DenseSet<DeclContext*> Visited;
1163 Visited.insert(StartDC);
1164
1165 // We have not yet looked into these namespaces, much less added
1166 // their "using-children" to the queue.
1167 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1168
1169 // We have already looked into the initial namespace; seed the queue
1170 // with its using-children.
1171 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001172 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001173 if (Visited.insert(ND).second)
1174 Queue.push_back(ND);
1175 }
1176
1177 // The easiest way to implement the restriction in [namespace.qual]p5
1178 // is to check whether any of the individual results found a tag
1179 // and, if so, to declare an ambiguity if the final result is not
1180 // a tag.
1181 bool FoundTag = false;
1182 bool FoundNonTag = false;
1183
John McCall5cebab12009-11-18 07:57:50 +00001184 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001185
1186 bool Found = false;
1187 while (!Queue.empty()) {
1188 NamespaceDecl *ND = Queue.back();
1189 Queue.pop_back();
1190
1191 // We go through some convolutions here to avoid copying results
1192 // between LookupResults.
1193 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001194 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001195 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001196
1197 if (FoundDirect) {
1198 // First do any local hiding.
1199 DirectR.resolveKind();
1200
1201 // If the local result is a tag, remember that.
1202 if (DirectR.isSingleTagDecl())
1203 FoundTag = true;
1204 else
1205 FoundNonTag = true;
1206
1207 // Append the local results to the total results if necessary.
1208 if (UseLocal) {
1209 R.addAllDecls(LocalR);
1210 LocalR.clear();
1211 }
1212 }
1213
1214 // If we find names in this namespace, ignore its using directives.
1215 if (FoundDirect) {
1216 Found = true;
1217 continue;
1218 }
1219
1220 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1221 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1222 if (Visited.insert(Nom).second)
1223 Queue.push_back(Nom);
1224 }
1225 }
1226
1227 if (Found) {
1228 if (FoundTag && FoundNonTag)
1229 R.setAmbiguousQualifiedTagHiding();
1230 else
1231 R.resolveKind();
1232 }
1233
1234 return Found;
1235}
1236
Douglas Gregor39982192010-08-15 06:18:01 +00001237/// \brief Callback that looks for any member of a class with the given name.
1238static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1239 CXXBasePath &Path,
1240 void *Name) {
1241 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1242
1243 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1244 Path.Decls = BaseRecord->lookup(N);
1245 return Path.Decls.first != Path.Decls.second;
1246}
1247
Douglas Gregorc0d24902010-10-22 22:08:47 +00001248/// \brief Determine whether the given set of member declarations contains only
1249/// static members, nested types, and enumerators.
1250template<typename InputIterator>
1251static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1252 Decl *D = (*First)->getUnderlyingDecl();
1253 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1254 return true;
1255
1256 if (isa<CXXMethodDecl>(D)) {
1257 // Determine whether all of the methods are static.
1258 bool AllMethodsAreStatic = true;
1259 for(; First != Last; ++First) {
1260 D = (*First)->getUnderlyingDecl();
1261
1262 if (!isa<CXXMethodDecl>(D)) {
1263 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1264 break;
1265 }
1266
1267 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1268 AllMethodsAreStatic = false;
1269 break;
1270 }
1271 }
1272
1273 if (AllMethodsAreStatic)
1274 return true;
1275 }
1276
1277 return false;
1278}
1279
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001280/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001281///
1282/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1283/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001284/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001285///
1286/// Different lookup criteria can find different names. For example, a
1287/// particular scope can have both a struct and a function of the same
1288/// name, and each can be found by certain lookup criteria. For more
1289/// information about lookup criteria, see the documentation for the
1290/// class LookupCriteria.
1291///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001292/// \param R captures both the lookup criteria and any lookup results found.
1293///
1294/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001295/// search. If the lookup criteria permits, name lookup may also search
1296/// in the parent contexts or (for C++ classes) base classes.
1297///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001298/// \param InUnqualifiedLookup true if this is qualified name lookup that
1299/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001300///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001301/// \returns true if lookup succeeded, false if it failed.
1302bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1303 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001304 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001305
John McCall27b18f82009-11-17 02:14:36 +00001306 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001307 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001308
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001309 // Make sure that the declaration context is complete.
1310 assert((!isa<TagDecl>(LookupCtx) ||
1311 LookupCtx->isDependentContext() ||
1312 cast<TagDecl>(LookupCtx)->isDefinition() ||
1313 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1314 ->isBeingDefined()) &&
1315 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001316
Douglas Gregor34074322009-01-14 22:20:51 +00001317 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001318 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001319 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001320 if (isa<CXXRecordDecl>(LookupCtx))
1321 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001322 return true;
1323 }
Douglas Gregor34074322009-01-14 22:20:51 +00001324
John McCall6538c932009-10-10 05:48:19 +00001325 // Don't descend into implied contexts for redeclarations.
1326 // C++98 [namespace.qual]p6:
1327 // In a declaration for a namespace member in which the
1328 // declarator-id is a qualified-id, given that the qualified-id
1329 // for the namespace member has the form
1330 // nested-name-specifier unqualified-id
1331 // the unqualified-id shall name a member of the namespace
1332 // designated by the nested-name-specifier.
1333 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001334 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001335 return false;
1336
John McCall27b18f82009-11-17 02:14:36 +00001337 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001338 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001339 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001340
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001341 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001342 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001343 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001344 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001345 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001346
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001347 // If we're performing qualified name lookup into a dependent class,
1348 // then we are actually looking into a current instantiation. If we have any
1349 // dependent base classes, then we either have to delay lookup until
1350 // template instantiation time (at which point all bases will be available)
1351 // or we have to fail.
1352 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1353 LookupRec->hasAnyDependentBases()) {
1354 R.setNotFoundInCurrentInstantiation();
1355 return false;
1356 }
1357
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001358 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001359 CXXBasePaths Paths;
1360 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001361
1362 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001363 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001364 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001365 case LookupOrdinaryName:
1366 case LookupMemberName:
1367 case LookupRedeclarationWithLinkage:
1368 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1369 break;
1370
1371 case LookupTagName:
1372 BaseCallback = &CXXRecordDecl::FindTagMember;
1373 break;
John McCall84d87672009-12-10 09:41:52 +00001374
Douglas Gregor39982192010-08-15 06:18:01 +00001375 case LookupAnyName:
1376 BaseCallback = &LookupAnyMember;
1377 break;
1378
John McCall84d87672009-12-10 09:41:52 +00001379 case LookupUsingDeclName:
1380 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001381
1382 case LookupOperatorName:
1383 case LookupNamespaceName:
1384 case LookupObjCProtocolName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001385 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001386 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001387
1388 case LookupNestedNameSpecifierName:
1389 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1390 break;
1391 }
1392
John McCall27b18f82009-11-17 02:14:36 +00001393 if (!LookupRec->lookupInBases(BaseCallback,
1394 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001395 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001396
John McCall553c0792010-01-23 00:46:32 +00001397 R.setNamingClass(LookupRec);
1398
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001399 // C++ [class.member.lookup]p2:
1400 // [...] If the resulting set of declarations are not all from
1401 // sub-objects of the same type, or the set has a nonstatic member
1402 // and includes members from distinct sub-objects, there is an
1403 // ambiguity and the program is ill-formed. Otherwise that set is
1404 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001405 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001406 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001407 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001408
Douglas Gregor36d1b142009-10-06 17:59:45 +00001409 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001410 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001411 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001412
John McCall401982f2010-01-20 21:53:11 +00001413 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1414 // across all paths.
1415 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1416
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001417 // Determine whether we're looking at a distinct sub-object or not.
1418 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001419 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001420 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1421 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001422 continue;
1423 }
1424
1425 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001426 != Context.getCanonicalType(PathElement.Base->getType())) {
1427 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001428 // different types. If the declaration sets aren't the same, this
1429 // this lookup is ambiguous.
1430 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1431 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1432 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1433 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
1434
1435 while (FirstD != FirstPath->Decls.second &&
1436 CurrentD != Path->Decls.second) {
1437 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1438 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1439 break;
1440
1441 ++FirstD;
1442 ++CurrentD;
1443 }
1444
1445 if (FirstD == FirstPath->Decls.second &&
1446 CurrentD == Path->Decls.second)
1447 continue;
1448 }
1449
John McCall9f3059a2009-10-09 21:13:30 +00001450 R.setAmbiguousBaseSubobjectTypes(Paths);
1451 return true;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001452 }
1453
1454 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001455 // We have a different subobject of the same type.
1456
1457 // C++ [class.member.lookup]p5:
1458 // A static member, a nested type or an enumerator defined in
1459 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001460 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001461 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001462 continue;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001463
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001464 // We have found a nonstatic member name in multiple, distinct
1465 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001466 R.setAmbiguousBaseSubobjects(Paths);
1467 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001468 }
1469 }
1470
1471 // Lookup in a base class succeeded; return these results.
1472
John McCall9f3059a2009-10-09 21:13:30 +00001473 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001474 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1475 NamedDecl *D = *I;
1476 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1477 D->getAccess());
1478 R.addDecl(D, AS);
1479 }
John McCall9f3059a2009-10-09 21:13:30 +00001480 R.resolveKind();
1481 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001482}
1483
1484/// @brief Performs name lookup for a name that was parsed in the
1485/// source code, and may contain a C++ scope specifier.
1486///
1487/// This routine is a convenience routine meant to be called from
1488/// contexts that receive a name and an optional C++ scope specifier
1489/// (e.g., "N::M::x"). It will then perform either qualified or
1490/// unqualified name lookup (with LookupQualifiedName or LookupName,
1491/// respectively) on the given name and return those results.
1492///
1493/// @param S The scope from which unqualified name lookup will
1494/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001495///
Douglas Gregore861bac2009-08-25 22:51:20 +00001496/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001497///
1498/// @param Name The name of the entity that name lookup will
1499/// search for.
1500///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001501/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001502/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001503/// C library functions (like "malloc") are implicitly declared.
1504///
Douglas Gregore861bac2009-08-25 22:51:20 +00001505/// @param EnteringContext Indicates whether we are going to enter the
1506/// context of the scope-specifier SS (if present).
1507///
John McCall9f3059a2009-10-09 21:13:30 +00001508/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001509bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001510 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001511 if (SS && SS->isInvalid()) {
1512 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001513 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001514 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001515 }
Mike Stump11289f42009-09-09 15:08:12 +00001516
Douglas Gregore861bac2009-08-25 22:51:20 +00001517 if (SS && SS->isSet()) {
1518 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001519 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001520 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001521 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001522 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001523
John McCall27b18f82009-11-17 02:14:36 +00001524 R.setContextRange(SS->getRange());
1525
1526 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001527 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001528
Douglas Gregore861bac2009-08-25 22:51:20 +00001529 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001530 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001531 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001532 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001533 }
1534
Mike Stump11289f42009-09-09 15:08:12 +00001535 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001536 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001537}
1538
Douglas Gregor889ceb72009-02-03 19:21:40 +00001539
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001540/// @brief Produce a diagnostic describing the ambiguity that resulted
1541/// from name lookup.
1542///
1543/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001544///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001545/// @param Name The name of the entity that name lookup was
1546/// searching for.
1547///
1548/// @param NameLoc The location of the name within the source code.
1549///
1550/// @param LookupRange A source range that provides more
1551/// source-location information concerning the lookup itself. For
1552/// example, this range might highlight a nested-name-specifier that
1553/// precedes the name.
1554///
1555/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001556bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001557 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1558
John McCall27b18f82009-11-17 02:14:36 +00001559 DeclarationName Name = Result.getLookupName();
1560 SourceLocation NameLoc = Result.getNameLoc();
1561 SourceRange LookupRange = Result.getContextRange();
1562
John McCall6538c932009-10-10 05:48:19 +00001563 switch (Result.getAmbiguityKind()) {
1564 case LookupResult::AmbiguousBaseSubobjects: {
1565 CXXBasePaths *Paths = Result.getBasePaths();
1566 QualType SubobjectType = Paths->front().back().Base->getType();
1567 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1568 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1569 << LookupRange;
1570
1571 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1572 while (isa<CXXMethodDecl>(*Found) &&
1573 cast<CXXMethodDecl>(*Found)->isStatic())
1574 ++Found;
1575
1576 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1577
1578 return true;
1579 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001580
John McCall6538c932009-10-10 05:48:19 +00001581 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001582 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1583 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001584
1585 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001586 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001587 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1588 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001589 Path != PathEnd; ++Path) {
1590 Decl *D = *Path->Decls.first;
1591 if (DeclsPrinted.insert(D).second)
1592 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1593 }
1594
Douglas Gregor1c846b02009-01-16 00:38:09 +00001595 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001596 }
1597
John McCall6538c932009-10-10 05:48:19 +00001598 case LookupResult::AmbiguousTagHiding: {
1599 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001600
John McCall6538c932009-10-10 05:48:19 +00001601 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1602
1603 LookupResult::iterator DI, DE = Result.end();
1604 for (DI = Result.begin(); DI != DE; ++DI)
1605 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1606 TagDecls.insert(TD);
1607 Diag(TD->getLocation(), diag::note_hidden_tag);
1608 }
1609
1610 for (DI = Result.begin(); DI != DE; ++DI)
1611 if (!isa<TagDecl>(*DI))
1612 Diag((*DI)->getLocation(), diag::note_hiding_object);
1613
1614 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001615 LookupResult::Filter F = Result.makeFilter();
1616 while (F.hasNext()) {
1617 if (TagDecls.count(F.next()))
1618 F.erase();
1619 }
1620 F.done();
John McCall6538c932009-10-10 05:48:19 +00001621
1622 return true;
1623 }
1624
1625 case LookupResult::AmbiguousReference: {
1626 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001627
John McCall6538c932009-10-10 05:48:19 +00001628 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1629 for (; DI != DE; ++DI)
1630 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001631
John McCall6538c932009-10-10 05:48:19 +00001632 return true;
1633 }
1634 }
1635
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001636 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001637 return true;
1638}
Douglas Gregore254f902009-02-04 00:32:51 +00001639
John McCallf24d7bb2010-05-28 18:45:08 +00001640namespace {
1641 struct AssociatedLookup {
1642 AssociatedLookup(Sema &S,
1643 Sema::AssociatedNamespaceSet &Namespaces,
1644 Sema::AssociatedClassSet &Classes)
1645 : S(S), Namespaces(Namespaces), Classes(Classes) {
1646 }
1647
1648 Sema &S;
1649 Sema::AssociatedNamespaceSet &Namespaces;
1650 Sema::AssociatedClassSet &Classes;
1651 };
1652}
1653
Mike Stump11289f42009-09-09 15:08:12 +00001654static void
John McCallf24d7bb2010-05-28 18:45:08 +00001655addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001656
Douglas Gregor8b895222010-04-30 07:08:38 +00001657static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1658 DeclContext *Ctx) {
1659 // Add the associated namespace for this class.
1660
1661 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1662 // be a locally scoped record.
1663
Sebastian Redlbd595762010-08-31 20:53:31 +00001664 // We skip out of inline namespaces. The innermost non-inline namespace
1665 // contains all names of all its nested inline namespaces anyway, so we can
1666 // replace the entire inline namespace tree with its root.
1667 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1668 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001669 Ctx = Ctx->getParent();
1670
John McCallc7e8e792009-08-07 22:18:02 +00001671 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001672 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001673}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001674
Mike Stump11289f42009-09-09 15:08:12 +00001675// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001676// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001677static void
John McCallf24d7bb2010-05-28 18:45:08 +00001678addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1679 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001680 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001681 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001682 switch (Arg.getKind()) {
1683 case TemplateArgument::Null:
1684 break;
Mike Stump11289f42009-09-09 15:08:12 +00001685
Douglas Gregor197e5f72009-07-08 07:51:57 +00001686 case TemplateArgument::Type:
1687 // [...] the namespaces and classes associated with the types of the
1688 // template arguments provided for template type parameters (excluding
1689 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001690 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001691 break;
Mike Stump11289f42009-09-09 15:08:12 +00001692
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001693 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001694 // [...] the namespaces in which any template template arguments are
1695 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001696 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001697 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001698 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001699 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001700 DeclContext *Ctx = ClassTemplate->getDeclContext();
1701 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001702 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001703 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001704 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001705 }
1706 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001707 }
1708
1709 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001710 case TemplateArgument::Integral:
1711 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001712 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001713 // associated namespaces. ]
1714 break;
Mike Stump11289f42009-09-09 15:08:12 +00001715
Douglas Gregor197e5f72009-07-08 07:51:57 +00001716 case TemplateArgument::Pack:
1717 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1718 PEnd = Arg.pack_end();
1719 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001720 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001721 break;
1722 }
1723}
1724
Douglas Gregore254f902009-02-04 00:32:51 +00001725// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001726// argument-dependent lookup with an argument of class type
1727// (C++ [basic.lookup.koenig]p2).
1728static void
John McCallf24d7bb2010-05-28 18:45:08 +00001729addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1730 CXXRecordDecl *Class) {
1731
1732 // Just silently ignore anything whose name is __va_list_tag.
1733 if (Class->getDeclName() == Result.S.VAListTagName)
1734 return;
1735
Douglas Gregore254f902009-02-04 00:32:51 +00001736 // C++ [basic.lookup.koenig]p2:
1737 // [...]
1738 // -- If T is a class type (including unions), its associated
1739 // classes are: the class itself; the class of which it is a
1740 // member, if any; and its direct and indirect base
1741 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001742 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001743
1744 // Add the class of which it is a member, if any.
1745 DeclContext *Ctx = Class->getDeclContext();
1746 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001747 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001748 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001749 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001750
Douglas Gregore254f902009-02-04 00:32:51 +00001751 // Add the class itself. If we've already seen this class, we don't
1752 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001753 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001754 return;
1755
Mike Stump11289f42009-09-09 15:08:12 +00001756 // -- If T is a template-id, its associated namespaces and classes are
1757 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001758 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001759 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001760 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001761 // namespaces in which any template template arguments are defined; and
1762 // the classes in which any member templates used as template template
1763 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001764 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001765 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001766 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1767 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1768 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001769 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001770 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001771 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001772
Douglas Gregor197e5f72009-07-08 07:51:57 +00001773 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1774 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001775 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001776 }
Mike Stump11289f42009-09-09 15:08:12 +00001777
John McCall67da35c2010-02-04 22:26:26 +00001778 // Only recurse into base classes for complete types.
1779 if (!Class->hasDefinition()) {
1780 // FIXME: we might need to instantiate templates here
1781 return;
1782 }
1783
Douglas Gregore254f902009-02-04 00:32:51 +00001784 // Add direct and indirect base classes along with their associated
1785 // namespaces.
1786 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1787 Bases.push_back(Class);
1788 while (!Bases.empty()) {
1789 // Pop this class off the stack.
1790 Class = Bases.back();
1791 Bases.pop_back();
1792
1793 // Visit the base classes.
1794 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1795 BaseEnd = Class->bases_end();
1796 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001797 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001798 // In dependent contexts, we do ADL twice, and the first time around,
1799 // the base type might be a dependent TemplateSpecializationType, or a
1800 // TemplateTypeParmType. If that happens, simply ignore it.
1801 // FIXME: If we want to support export, we probably need to add the
1802 // namespace of the template in a TemplateSpecializationType, or even
1803 // the classes and namespaces of known non-dependent arguments.
1804 if (!BaseType)
1805 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001806 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001807 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001808 // Find the associated namespace for this base class.
1809 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001810 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001811
1812 // Make sure we visit the bases of this base class.
1813 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1814 Bases.push_back(BaseDecl);
1815 }
1816 }
1817 }
1818}
1819
1820// \brief Add the associated classes and namespaces for
1821// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001822// (C++ [basic.lookup.koenig]p2).
1823static void
John McCallf24d7bb2010-05-28 18:45:08 +00001824addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001825 // C++ [basic.lookup.koenig]p2:
1826 //
1827 // For each argument type T in the function call, there is a set
1828 // of zero or more associated namespaces and a set of zero or more
1829 // associated classes to be considered. The sets of namespaces and
1830 // classes is determined entirely by the types of the function
1831 // arguments (and the namespace of any template template
1832 // argument). Typedef names and using-declarations used to specify
1833 // the types do not contribute to this set. The sets of namespaces
1834 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001835
John McCall0af3d3b2010-05-28 06:08:54 +00001836 llvm::SmallVector<const Type *, 16> Queue;
1837 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1838
Douglas Gregore254f902009-02-04 00:32:51 +00001839 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001840 switch (T->getTypeClass()) {
1841
1842#define TYPE(Class, Base)
1843#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1844#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1845#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1846#define ABSTRACT_TYPE(Class, Base)
1847#include "clang/AST/TypeNodes.def"
1848 // T is canonical. We can also ignore dependent types because
1849 // we don't need to do ADL at the definition point, but if we
1850 // wanted to implement template export (or if we find some other
1851 // use for associated classes and namespaces...) this would be
1852 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001853 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001854
John McCall0af3d3b2010-05-28 06:08:54 +00001855 // -- If T is a pointer to U or an array of U, its associated
1856 // namespaces and classes are those associated with U.
1857 case Type::Pointer:
1858 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1859 continue;
1860 case Type::ConstantArray:
1861 case Type::IncompleteArray:
1862 case Type::VariableArray:
1863 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1864 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001865
John McCall0af3d3b2010-05-28 06:08:54 +00001866 // -- If T is a fundamental type, its associated sets of
1867 // namespaces and classes are both empty.
1868 case Type::Builtin:
1869 break;
1870
1871 // -- If T is a class type (including unions), its associated
1872 // classes are: the class itself; the class of which it is a
1873 // member, if any; and its direct and indirect base
1874 // classes. Its associated namespaces are the namespaces in
1875 // which its associated classes are defined.
1876 case Type::Record: {
1877 CXXRecordDecl *Class
1878 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001879 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001880 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001881 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001882
John McCall0af3d3b2010-05-28 06:08:54 +00001883 // -- If T is an enumeration type, its associated namespace is
1884 // the namespace in which it is defined. If it is class
1885 // member, its associated class is the member’s class; else
1886 // it has no associated class.
1887 case Type::Enum: {
1888 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001889
John McCall0af3d3b2010-05-28 06:08:54 +00001890 DeclContext *Ctx = Enum->getDeclContext();
1891 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001892 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001893
John McCall0af3d3b2010-05-28 06:08:54 +00001894 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001895 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001896
John McCall0af3d3b2010-05-28 06:08:54 +00001897 break;
1898 }
1899
1900 // -- If T is a function type, its associated namespaces and
1901 // classes are those associated with the function parameter
1902 // types and those associated with the return type.
1903 case Type::FunctionProto: {
1904 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1905 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1906 ArgEnd = Proto->arg_type_end();
1907 Arg != ArgEnd; ++Arg)
1908 Queue.push_back(Arg->getTypePtr());
1909 // fallthrough
1910 }
1911 case Type::FunctionNoProto: {
1912 const FunctionType *FnType = cast<FunctionType>(T);
1913 T = FnType->getResultType().getTypePtr();
1914 continue;
1915 }
1916
1917 // -- If T is a pointer to a member function of a class X, its
1918 // associated namespaces and classes are those associated
1919 // with the function parameter types and return type,
1920 // together with those associated with X.
1921 //
1922 // -- If T is a pointer to a data member of class X, its
1923 // associated namespaces and classes are those associated
1924 // with the member type together with those associated with
1925 // X.
1926 case Type::MemberPointer: {
1927 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1928
1929 // Queue up the class type into which this points.
1930 Queue.push_back(MemberPtr->getClass());
1931
1932 // And directly continue with the pointee type.
1933 T = MemberPtr->getPointeeType().getTypePtr();
1934 continue;
1935 }
1936
1937 // As an extension, treat this like a normal pointer.
1938 case Type::BlockPointer:
1939 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1940 continue;
1941
1942 // References aren't covered by the standard, but that's such an
1943 // obvious defect that we cover them anyway.
1944 case Type::LValueReference:
1945 case Type::RValueReference:
1946 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1947 continue;
1948
1949 // These are fundamental types.
1950 case Type::Vector:
1951 case Type::ExtVector:
1952 case Type::Complex:
1953 break;
1954
1955 // These are ignored by ADL.
1956 case Type::ObjCObject:
1957 case Type::ObjCInterface:
1958 case Type::ObjCObjectPointer:
1959 break;
1960 }
1961
1962 if (Queue.empty()) break;
1963 T = Queue.back();
1964 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001965 }
Douglas Gregore254f902009-02-04 00:32:51 +00001966}
1967
1968/// \brief Find the associated classes and namespaces for
1969/// argument-dependent lookup for a call with the given set of
1970/// arguments.
1971///
1972/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001973/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001974/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001975void
Douglas Gregore254f902009-02-04 00:32:51 +00001976Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1977 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001978 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001979 AssociatedNamespaces.clear();
1980 AssociatedClasses.clear();
1981
John McCallf24d7bb2010-05-28 18:45:08 +00001982 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1983
Douglas Gregore254f902009-02-04 00:32:51 +00001984 // C++ [basic.lookup.koenig]p2:
1985 // For each argument type T in the function call, there is a set
1986 // of zero or more associated namespaces and a set of zero or more
1987 // associated classes to be considered. The sets of namespaces and
1988 // classes is determined entirely by the types of the function
1989 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001990 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001991 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1992 Expr *Arg = Args[ArgIdx];
1993
1994 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00001995 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001996 continue;
1997 }
1998
1999 // [...] In addition, if the argument is the name or address of a
2000 // set of overloaded functions and/or function templates, its
2001 // associated classes and namespaces are the union of those
2002 // associated with each of the members of the set: the namespace
2003 // in which the function or function template is defined and the
2004 // classes and namespaces associated with its (non-dependent)
2005 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002006 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002007 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002008 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002009 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002010
John McCallf24d7bb2010-05-28 18:45:08 +00002011 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2012 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002013
John McCallf24d7bb2010-05-28 18:45:08 +00002014 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2015 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002016 // Look through any using declarations to find the underlying function.
2017 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002018
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002019 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2020 if (!FDecl)
2021 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002022
2023 // Add the classes and namespaces associated with the parameter
2024 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002025 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002026 }
2027 }
2028}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002029
2030/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2031/// an acceptable non-member overloaded operator for a call whose
2032/// arguments have types T1 (and, if non-empty, T2). This routine
2033/// implements the check in C++ [over.match.oper]p3b2 concerning
2034/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002035static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002036IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2037 QualType T1, QualType T2,
2038 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002039 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2040 return true;
2041
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002042 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2043 return true;
2044
John McCall9dd450b2009-09-21 23:43:11 +00002045 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002046 if (Proto->getNumArgs() < 1)
2047 return false;
2048
2049 if (T1->isEnumeralType()) {
2050 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002051 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002052 return true;
2053 }
2054
2055 if (Proto->getNumArgs() < 2)
2056 return false;
2057
2058 if (!T2.isNull() && T2->isEnumeralType()) {
2059 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002060 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002061 return true;
2062 }
2063
2064 return false;
2065}
2066
John McCall5cebab12009-11-18 07:57:50 +00002067NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002068 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002069 LookupNameKind NameKind,
2070 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002071 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002072 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002073 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002074}
2075
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002076/// \brief Find the protocol with the given name, if any.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002077ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2078 SourceLocation IdLoc) {
2079 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2080 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002081 return cast_or_null<ObjCProtocolDecl>(D);
2082}
2083
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002084void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002085 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002086 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002087 // C++ [over.match.oper]p3:
2088 // -- The set of non-member candidates is the result of the
2089 // unqualified lookup of operator@ in the context of the
2090 // expression according to the usual rules for name lookup in
2091 // unqualified function calls (3.4.2) except that all member
2092 // functions are ignored. However, if no operand has a class
2093 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002094 // that have a first parameter of type T1 or "reference to
2095 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002096 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002097 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002098 // when T2 is an enumeration type, are candidate functions.
2099 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002100 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2101 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002102
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002103 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2104
John McCall9f3059a2009-10-09 21:13:30 +00002105 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002106 return;
2107
2108 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2109 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002110 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2111 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002112 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002113 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002114 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002115 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002116 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002117 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002118 // later?
2119 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002120 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002121 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002122 }
2123}
2124
Douglas Gregor52b72822010-07-02 23:12:18 +00002125/// \brief Look up the constructors for the given class.
2126DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +00002127 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002128 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2129 if (!Class->hasDeclaredDefaultConstructor())
2130 DeclareImplicitDefaultConstructor(Class);
2131 if (!Class->hasDeclaredCopyConstructor())
2132 DeclareImplicitCopyConstructor(Class);
2133 }
Douglas Gregora6d69502010-07-02 23:41:54 +00002134
Douglas Gregor52b72822010-07-02 23:12:18 +00002135 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2136 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2137 return Class->lookup(Name);
2138}
2139
Douglas Gregore71edda2010-07-01 22:47:18 +00002140/// \brief Look for the destructor of the given class.
2141///
2142/// During semantic analysis, this routine should be used in lieu of
2143/// CXXRecordDecl::getDestructor().
2144///
2145/// \returns The destructor for this class.
2146CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +00002147 // If the destructor has not yet been declared, do so now.
2148 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2149 !Class->hasDeclaredDestructor())
2150 DeclareImplicitDestructor(Class);
2151
Douglas Gregore71edda2010-07-01 22:47:18 +00002152 return Class->getDestructor();
2153}
2154
John McCall8fe68082010-01-26 07:16:45 +00002155void ADLResult::insert(NamedDecl *New) {
2156 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2157
2158 // If we haven't yet seen a decl for this key, or the last decl
2159 // was exactly this one, we're done.
2160 if (Old == 0 || Old == New) {
2161 Old = New;
2162 return;
2163 }
2164
2165 // Otherwise, decide which is a more recent redeclaration.
2166 FunctionDecl *OldFD, *NewFD;
2167 if (isa<FunctionTemplateDecl>(New)) {
2168 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2169 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2170 } else {
2171 OldFD = cast<FunctionDecl>(Old);
2172 NewFD = cast<FunctionDecl>(New);
2173 }
2174
2175 FunctionDecl *Cursor = NewFD;
2176 while (true) {
2177 Cursor = Cursor->getPreviousDeclaration();
2178
2179 // If we got to the end without finding OldFD, OldFD is the newer
2180 // declaration; leave things as they are.
2181 if (!Cursor) return;
2182
2183 // If we do find OldFD, then NewFD is newer.
2184 if (Cursor == OldFD) break;
2185
2186 // Otherwise, keep looking.
2187 }
2188
2189 Old = New;
2190}
2191
Sebastian Redlc057f422009-10-23 19:23:15 +00002192void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002193 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00002194 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002195 // Find all of the associated namespaces and classes based on the
2196 // arguments we have.
2197 AssociatedNamespaceSet AssociatedNamespaces;
2198 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002199 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002200 AssociatedNamespaces,
2201 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002202
Sebastian Redlc057f422009-10-23 19:23:15 +00002203 QualType T1, T2;
2204 if (Operator) {
2205 T1 = Args[0]->getType();
2206 if (NumArgs >= 2)
2207 T2 = Args[1]->getType();
2208 }
2209
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002210 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002211 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2212 // and let Y be the lookup set produced by argument dependent
2213 // lookup (defined as follows). If X contains [...] then Y is
2214 // empty. Otherwise Y is the set of declarations found in the
2215 // namespaces associated with the argument types as described
2216 // below. The set of declarations found by the lookup of the name
2217 // is the union of X and Y.
2218 //
2219 // Here, we compute Y and add its members to the overloaded
2220 // candidate set.
2221 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002222 NSEnd = AssociatedNamespaces.end();
2223 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002224 // When considering an associated namespace, the lookup is the
2225 // same as the lookup performed when the associated namespace is
2226 // used as a qualifier (3.4.3.2) except that:
2227 //
2228 // -- Any using-directives in the associated namespace are
2229 // ignored.
2230 //
John McCallc7e8e792009-08-07 22:18:02 +00002231 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002232 // associated classes are visible within their respective
2233 // namespaces even if they are not visible during an ordinary
2234 // lookup (11.4).
2235 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002236 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002237 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002238 // If the only declaration here is an ordinary friend, consider
2239 // it only if it was declared in an associated classes.
2240 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002241 DeclContext *LexDC = D->getLexicalDeclContext();
2242 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2243 continue;
2244 }
Mike Stump11289f42009-09-09 15:08:12 +00002245
John McCall91f61fc2010-01-26 06:04:06 +00002246 if (isa<UsingShadowDecl>(D))
2247 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002248
John McCall91f61fc2010-01-26 06:04:06 +00002249 if (isa<FunctionDecl>(D)) {
2250 if (Operator &&
2251 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2252 T1, T2, Context))
2253 continue;
John McCall8fe68082010-01-26 07:16:45 +00002254 } else if (!isa<FunctionTemplateDecl>(D))
2255 continue;
2256
2257 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002258 }
2259 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002260}
Douglas Gregor2d435302009-12-30 17:04:44 +00002261
2262//----------------------------------------------------------------------------
2263// Search for all visible declarations.
2264//----------------------------------------------------------------------------
2265VisibleDeclConsumer::~VisibleDeclConsumer() { }
2266
2267namespace {
2268
2269class ShadowContextRAII;
2270
2271class VisibleDeclsRecord {
2272public:
2273 /// \brief An entry in the shadow map, which is optimized to store a
2274 /// single declaration (the common case) but can also store a list
2275 /// of declarations.
2276 class ShadowMapEntry {
2277 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2278
2279 /// \brief Contains either the solitary NamedDecl * or a vector
2280 /// of declarations.
2281 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2282
2283 public:
2284 ShadowMapEntry() : DeclOrVector() { }
2285
2286 void Add(NamedDecl *ND);
2287 void Destroy();
2288
2289 // Iteration.
2290 typedef NamedDecl **iterator;
2291 iterator begin();
2292 iterator end();
2293 };
2294
2295private:
2296 /// \brief A mapping from declaration names to the declarations that have
2297 /// this name within a particular scope.
2298 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2299
2300 /// \brief A list of shadow maps, which is used to model name hiding.
2301 std::list<ShadowMap> ShadowMaps;
2302
2303 /// \brief The declaration contexts we have already visited.
2304 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2305
2306 friend class ShadowContextRAII;
2307
2308public:
2309 /// \brief Determine whether we have already visited this context
2310 /// (and, if not, note that we are going to visit that context now).
2311 bool visitedContext(DeclContext *Ctx) {
2312 return !VisitedContexts.insert(Ctx);
2313 }
2314
Douglas Gregor39982192010-08-15 06:18:01 +00002315 bool alreadyVisitedContext(DeclContext *Ctx) {
2316 return VisitedContexts.count(Ctx);
2317 }
2318
Douglas Gregor2d435302009-12-30 17:04:44 +00002319 /// \brief Determine whether the given declaration is hidden in the
2320 /// current scope.
2321 ///
2322 /// \returns the declaration that hides the given declaration, or
2323 /// NULL if no such declaration exists.
2324 NamedDecl *checkHidden(NamedDecl *ND);
2325
2326 /// \brief Add a declaration to the current shadow map.
2327 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2328};
2329
2330/// \brief RAII object that records when we've entered a shadow context.
2331class ShadowContextRAII {
2332 VisibleDeclsRecord &Visible;
2333
2334 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2335
2336public:
2337 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2338 Visible.ShadowMaps.push_back(ShadowMap());
2339 }
2340
2341 ~ShadowContextRAII() {
2342 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2343 EEnd = Visible.ShadowMaps.back().end();
2344 E != EEnd;
2345 ++E)
2346 E->second.Destroy();
2347
2348 Visible.ShadowMaps.pop_back();
2349 }
2350};
2351
2352} // end anonymous namespace
2353
2354void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2355 if (DeclOrVector.isNull()) {
2356 // 0 - > 1 elements: just set the single element information.
2357 DeclOrVector = ND;
2358 return;
2359 }
2360
2361 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2362 // 1 -> 2 elements: create the vector of results and push in the
2363 // existing declaration.
2364 DeclVector *Vec = new DeclVector;
2365 Vec->push_back(PrevND);
2366 DeclOrVector = Vec;
2367 }
2368
2369 // Add the new element to the end of the vector.
2370 DeclOrVector.get<DeclVector*>()->push_back(ND);
2371}
2372
2373void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2374 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2375 delete Vec;
2376 DeclOrVector = ((NamedDecl *)0);
2377 }
2378}
2379
2380VisibleDeclsRecord::ShadowMapEntry::iterator
2381VisibleDeclsRecord::ShadowMapEntry::begin() {
2382 if (DeclOrVector.isNull())
2383 return 0;
2384
2385 if (DeclOrVector.dyn_cast<NamedDecl *>())
2386 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2387
2388 return DeclOrVector.get<DeclVector *>()->begin();
2389}
2390
2391VisibleDeclsRecord::ShadowMapEntry::iterator
2392VisibleDeclsRecord::ShadowMapEntry::end() {
2393 if (DeclOrVector.isNull())
2394 return 0;
2395
2396 if (DeclOrVector.dyn_cast<NamedDecl *>())
2397 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2398
2399 return DeclOrVector.get<DeclVector *>()->end();
2400}
2401
2402NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002403 // Look through using declarations.
2404 ND = ND->getUnderlyingDecl();
2405
Douglas Gregor2d435302009-12-30 17:04:44 +00002406 unsigned IDNS = ND->getIdentifierNamespace();
2407 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2408 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2409 SM != SMEnd; ++SM) {
2410 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2411 if (Pos == SM->end())
2412 continue;
2413
2414 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2415 IEnd = Pos->second.end();
2416 I != IEnd; ++I) {
2417 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002418 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor2d435302009-12-30 17:04:44 +00002419 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2420 Decl::IDNS_ObjCProtocol)))
2421 continue;
2422
2423 // Protocols are in distinct namespaces from everything else.
2424 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2425 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2426 (*I)->getIdentifierNamespace() != IDNS)
2427 continue;
2428
Douglas Gregor09bbc652010-01-14 15:47:35 +00002429 // Functions and function templates in the same scope overload
2430 // rather than hide. FIXME: Look for hiding based on function
2431 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002432 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002433 ND->isFunctionOrFunctionTemplate() &&
2434 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002435 continue;
2436
Douglas Gregor2d435302009-12-30 17:04:44 +00002437 // We've found a declaration that hides this one.
2438 return *I;
2439 }
2440 }
2441
2442 return 0;
2443}
2444
2445static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2446 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002447 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002448 VisibleDeclConsumer &Consumer,
2449 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002450 if (!Ctx)
2451 return;
2452
Douglas Gregor2d435302009-12-30 17:04:44 +00002453 // Make sure we don't visit the same context twice.
2454 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2455 return;
2456
Douglas Gregor7454c562010-07-02 20:37:36 +00002457 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2458 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2459
Douglas Gregor2d435302009-12-30 17:04:44 +00002460 // Enumerate all of the results in this context.
2461 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2462 CurCtx = CurCtx->getNextContext()) {
2463 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2464 DEnd = CurCtx->decls_end();
2465 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002466 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002467 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002468 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002469 Visited.add(ND);
2470 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002471 } else if (ObjCForwardProtocolDecl *ForwardProto
2472 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2473 for (ObjCForwardProtocolDecl::protocol_iterator
2474 P = ForwardProto->protocol_begin(),
2475 PEnd = ForwardProto->protocol_end();
2476 P != PEnd;
2477 ++P) {
2478 if (Result.isAcceptableDecl(*P)) {
2479 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2480 Visited.add(*P);
2481 }
2482 }
2483 }
Sebastian Redlbd595762010-08-31 20:53:31 +00002484 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002485 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002486 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002487 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002488 Consumer, Visited);
2489 }
2490 }
2491 }
2492
2493 // Traverse using directives for qualified name lookup.
2494 if (QualifiedNameLookup) {
2495 ShadowContextRAII Shadow(Visited);
2496 DeclContext::udir_iterator I, E;
2497 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2498 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002499 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002500 }
2501 }
2502
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002503 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002504 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002505 if (!Record->hasDefinition())
2506 return;
2507
Douglas Gregor2d435302009-12-30 17:04:44 +00002508 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2509 BEnd = Record->bases_end();
2510 B != BEnd; ++B) {
2511 QualType BaseType = B->getType();
2512
2513 // Don't look into dependent bases, because name lookup can't look
2514 // there anyway.
2515 if (BaseType->isDependentType())
2516 continue;
2517
2518 const RecordType *Record = BaseType->getAs<RecordType>();
2519 if (!Record)
2520 continue;
2521
2522 // FIXME: It would be nice to be able to determine whether referencing
2523 // a particular member would be ambiguous. For example, given
2524 //
2525 // struct A { int member; };
2526 // struct B { int member; };
2527 // struct C : A, B { };
2528 //
2529 // void f(C *c) { c->### }
2530 //
2531 // accessing 'member' would result in an ambiguity. However, we
2532 // could be smart enough to qualify the member with the base
2533 // class, e.g.,
2534 //
2535 // c->B::member
2536 //
2537 // or
2538 //
2539 // c->A::member
2540
2541 // Find results in this base class (and its bases).
2542 ShadowContextRAII Shadow(Visited);
2543 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002544 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002545 }
2546 }
2547
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002548 // Traverse the contexts of Objective-C classes.
2549 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2550 // Traverse categories.
2551 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2552 Category; Category = Category->getNextClassCategory()) {
2553 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002554 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2555 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002556 }
2557
2558 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002559 for (ObjCInterfaceDecl::all_protocol_iterator
2560 I = IFace->all_referenced_protocol_begin(),
2561 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002562 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002563 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2564 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002565 }
2566
2567 // Traverse the superclass.
2568 if (IFace->getSuperClass()) {
2569 ShadowContextRAII Shadow(Visited);
2570 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002571 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002572 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002573
2574 // If there is an implementation, traverse it. We do this to find
2575 // synthesized ivars.
2576 if (IFace->getImplementation()) {
2577 ShadowContextRAII Shadow(Visited);
2578 LookupVisibleDecls(IFace->getImplementation(), Result,
2579 QualifiedNameLookup, true, Consumer, Visited);
2580 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002581 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2582 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2583 E = Protocol->protocol_end(); I != E; ++I) {
2584 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002585 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2586 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002587 }
2588 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2589 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2590 E = Category->protocol_end(); I != E; ++I) {
2591 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002592 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2593 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002594 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002595
2596 // If there is an implementation, traverse it.
2597 if (Category->getImplementation()) {
2598 ShadowContextRAII Shadow(Visited);
2599 LookupVisibleDecls(Category->getImplementation(), Result,
2600 QualifiedNameLookup, true, Consumer, Visited);
2601 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002602 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002603}
2604
2605static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2606 UnqualUsingDirectiveSet &UDirs,
2607 VisibleDeclConsumer &Consumer,
2608 VisibleDeclsRecord &Visited) {
2609 if (!S)
2610 return;
2611
Douglas Gregor39982192010-08-15 06:18:01 +00002612 if (!S->getEntity() ||
2613 (!S->getParent() &&
2614 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002615 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2616 // Walk through the declarations in this Scope.
2617 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2618 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002619 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002620 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002621 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002622 Visited.add(ND);
2623 }
2624 }
2625 }
2626
Douglas Gregor66230062010-03-15 14:33:29 +00002627 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002628 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002629 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002630 // Look into this scope's declaration context, along with any of its
2631 // parent lookup contexts (e.g., enclosing classes), up to the point
2632 // where we hit the context stored in the next outer scope.
2633 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002634 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor2d435302009-12-30 17:04:44 +00002635
Douglas Gregorea166062010-03-15 15:26:48 +00002636 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002637 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002638 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2639 if (Method->isInstanceMethod()) {
2640 // For instance methods, look for ivars in the method's interface.
2641 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2642 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002643 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002644 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2645 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002646
2647 // Look for properties from which we can synthesize ivars, if
2648 // permitted.
2649 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2650 IFace->getImplementation() &&
2651 Result.getLookupKind() == Sema::LookupOrdinaryName) {
2652 for (ObjCInterfaceDecl::prop_iterator
2653 P = IFace->prop_begin(),
2654 PEnd = IFace->prop_end();
2655 P != PEnd; ++P) {
2656 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2657 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2658 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2659 Visited.add(*P);
2660 }
2661 }
2662 }
2663 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002664 }
2665
2666 // We've already performed all of the name lookup that we need
2667 // to for Objective-C methods; the next context will be the
2668 // outer scope.
2669 break;
2670 }
2671
Douglas Gregor2d435302009-12-30 17:04:44 +00002672 if (Ctx->isFunctionOrMethod())
2673 continue;
2674
2675 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002676 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002677 }
2678 } else if (!S->getParent()) {
2679 // Look into the translation unit scope. We walk through the translation
2680 // unit's declaration context, because the Scope itself won't have all of
2681 // the declarations if we loaded a precompiled header.
2682 // FIXME: We would like the translation unit's Scope object to point to the
2683 // translation unit, so we don't need this special "if" branch. However,
2684 // doing so would force the normal C++ name-lookup code to look into the
2685 // translation unit decl when the IdentifierInfo chains would suffice.
2686 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002687 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002688 Entity = Result.getSema().Context.getTranslationUnitDecl();
2689 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002690 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002691 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002692
2693 if (Entity) {
2694 // Lookup visible declarations in any namespaces found by using
2695 // directives.
2696 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2697 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2698 for (; UI != UEnd; ++UI)
2699 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002700 Result, /*QualifiedNameLookup=*/false,
2701 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002702 }
2703
2704 // Lookup names in the parent scope.
2705 ShadowContextRAII Shadow(Visited);
2706 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2707}
2708
2709void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002710 VisibleDeclConsumer &Consumer,
2711 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002712 // Determine the set of using directives available during
2713 // unqualified name lookup.
2714 Scope *Initial = S;
2715 UnqualUsingDirectiveSet UDirs;
2716 if (getLangOptions().CPlusPlus) {
2717 // Find the first namespace or translation-unit scope.
2718 while (S && !isNamespaceOrTranslationUnitScope(S))
2719 S = S->getParent();
2720
2721 UDirs.visitScopeChain(Initial, S);
2722 }
2723 UDirs.done();
2724
2725 // Look for visible declarations.
2726 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2727 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002728 if (!IncludeGlobalScope)
2729 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002730 ShadowContextRAII Shadow(Visited);
2731 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2732}
2733
2734void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002735 VisibleDeclConsumer &Consumer,
2736 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002737 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2738 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002739 if (!IncludeGlobalScope)
2740 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002741 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002742 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2743 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002744}
2745
2746//----------------------------------------------------------------------------
2747// Typo correction
2748//----------------------------------------------------------------------------
2749
2750namespace {
2751class TypoCorrectionConsumer : public VisibleDeclConsumer {
2752 /// \brief The name written that is a typo in the source.
2753 llvm::StringRef Typo;
2754
2755 /// \brief The results found that have the smallest edit distance
2756 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002757 ///
2758 /// The boolean value indicates whether there is a keyword with this name.
2759 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00002760
2761 /// \brief The best edit distance found so far.
2762 unsigned BestEditDistance;
2763
2764public:
2765 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002766 : Typo(Typo->getName()),
2767 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00002768
Douglas Gregor09bbc652010-01-14 15:47:35 +00002769 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor57756ea2010-10-14 22:11:03 +00002770 void FoundName(llvm::StringRef Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002771 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002772
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002773 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2774 iterator begin() { return BestResults.begin(); }
2775 iterator end() { return BestResults.end(); }
2776 void erase(iterator I) { BestResults.erase(I); }
2777 unsigned size() const { return BestResults.size(); }
2778 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002779
Douglas Gregoraf9eb592010-10-15 13:35:25 +00002780 bool &operator[](llvm::StringRef Name) {
2781 return BestResults[Name];
2782 }
2783
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002784 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002785};
2786
2787}
2788
Douglas Gregor09bbc652010-01-14 15:47:35 +00002789void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2790 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002791 // Don't consider hidden names for typo correction.
2792 if (Hiding)
2793 return;
2794
2795 // Only consider entities with identifiers for names, ignoring
2796 // special names (constructors, overloaded operators, selectors,
2797 // etc.).
2798 IdentifierInfo *Name = ND->getIdentifier();
2799 if (!Name)
2800 return;
2801
Douglas Gregor57756ea2010-10-14 22:11:03 +00002802 FoundName(Name->getName());
2803}
2804
2805void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002806 using namespace std;
2807
Douglas Gregor93910a52010-10-19 19:39:10 +00002808 // Use a simple length-based heuristic to determine the minimum possible
2809 // edit distance. If the minimum isn't good enough, bail out early.
2810 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
2811 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
2812 return;
2813
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002814 // Compute an upper bound on the allowable edit distance, so that the
2815 // edit-distance algorithm can short-circuit.
2816 unsigned UpperBound = min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
2817
Douglas Gregor2d435302009-12-30 17:04:44 +00002818 // Compute the edit distance between the typo and the name of this
2819 // entity. If this edit distance is not worse than the best edit
2820 // distance we've seen so far, add it to the list of results.
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002821 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
Douglas Gregor57756ea2010-10-14 22:11:03 +00002822 if (ED == 0)
2823 return;
2824
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002825 if (ED < BestEditDistance) {
2826 // This result is better than any we've seen before; clear out
2827 // the previous results.
2828 BestResults.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002829 BestEditDistance = ED;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002830 } else if (ED > BestEditDistance) {
2831 // This result is worse than the best results we've seen so far;
2832 // ignore it.
2833 return;
2834 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00002835
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002836 // Add this name to the list of results. By not assigning a value, we
2837 // keep the current value if we've seen this name before (either as a
2838 // keyword or as a declaration), or get the default value (not a keyword)
2839 // if we haven't seen it before.
Douglas Gregor57756ea2010-10-14 22:11:03 +00002840 (void)BestResults[Name];
Douglas Gregor2d435302009-12-30 17:04:44 +00002841}
2842
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002843void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2844 llvm::StringRef Keyword) {
2845 // Compute the edit distance between the typo and this keyword.
2846 // If this edit distance is not worse than the best edit
2847 // distance we've seen so far, add it to the list of results.
2848 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002849 if (ED < BestEditDistance) {
2850 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002851 BestEditDistance = ED;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002852 } else if (ED > BestEditDistance) {
2853 // This result is worse than the best results we've seen so far;
2854 // ignore it.
2855 return;
2856 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002857
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002858 BestResults[Keyword] = true;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002859}
2860
Douglas Gregord507d772010-10-20 03:06:34 +00002861/// \brief Perform name lookup for a possible result for typo correction.
2862static void LookupPotentialTypoResult(Sema &SemaRef,
2863 LookupResult &Res,
2864 IdentifierInfo *Name,
2865 Scope *S, CXXScopeSpec *SS,
2866 DeclContext *MemberContext,
2867 bool EnteringContext,
2868 Sema::CorrectTypoContext CTC) {
2869 Res.suppressDiagnostics();
2870 Res.clear();
2871 Res.setLookupName(Name);
2872 if (MemberContext) {
2873 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
2874 if (CTC == Sema::CTC_ObjCIvarLookup) {
2875 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
2876 Res.addDecl(Ivar);
2877 Res.resolveKind();
2878 return;
2879 }
2880 }
2881
2882 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
2883 Res.addDecl(Prop);
2884 Res.resolveKind();
2885 return;
2886 }
2887 }
2888
2889 SemaRef.LookupQualifiedName(Res, MemberContext);
2890 return;
2891 }
2892
2893 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2894 EnteringContext);
2895
2896 // Fake ivar lookup; this should really be part of
2897 // LookupParsedName.
2898 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2899 if (Method->isInstanceMethod() && Method->getClassInterface() &&
2900 (Res.empty() ||
2901 (Res.isSingleResult() &&
2902 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
2903 if (ObjCIvarDecl *IV
2904 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
2905 Res.addDecl(IV);
2906 Res.resolveKind();
2907 }
2908 }
2909 }
2910}
2911
Douglas Gregor2d435302009-12-30 17:04:44 +00002912/// \brief Try to "correct" a typo in the source code by finding
2913/// visible declarations whose names are similar to the name that was
2914/// present in the source code.
2915///
2916/// \param Res the \c LookupResult structure that contains the name
2917/// that was present in the source code along with the name-lookup
2918/// criteria used to search for the name. On success, this structure
2919/// will contain the results of name lookup.
2920///
2921/// \param S the scope in which name lookup occurs.
2922///
2923/// \param SS the nested-name-specifier that precedes the name we're
2924/// looking for, if present.
2925///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002926/// \param MemberContext if non-NULL, the context in which to look for
2927/// a member access expression.
2928///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002929/// \param EnteringContext whether we're entering the context described by
2930/// the nested-name-specifier SS.
2931///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002932/// \param CTC The context in which typo correction occurs, which impacts the
2933/// set of keywords permitted.
2934///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002935/// \param OPT when non-NULL, the search for visible declarations will
2936/// also walk the protocols in the qualified interfaces of \p OPT.
2937///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002938/// \returns the corrected name if the typo was corrected, otherwise returns an
2939/// empty \c DeclarationName. When a typo was corrected, the result structure
2940/// may contain the results of name lookup for the correct name or it may be
2941/// empty.
2942DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002943 DeclContext *MemberContext,
2944 bool EnteringContext,
2945 CorrectTypoContext CTC,
2946 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00002947 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002948 return DeclarationName();
Ted Kremeneke51136e2010-01-06 00:23:04 +00002949
Douglas Gregor2d435302009-12-30 17:04:44 +00002950 // We only attempt to correct typos for identifiers.
2951 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2952 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002953 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002954
2955 // If the scope specifier itself was invalid, don't try to correct
2956 // typos.
2957 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002958 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002959
2960 // Never try to correct typos during template deduction or
2961 // instantiation.
2962 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002963 return DeclarationName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002964
Douglas Gregor2d435302009-12-30 17:04:44 +00002965 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002966
2967 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00002968 bool IsUnqualifiedLookup = false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002969 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002970 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002971
2972 // Look in qualified interfaces.
2973 if (OPT) {
2974 for (ObjCObjectPointerType::qual_iterator
2975 I = OPT->qual_begin(), E = OPT->qual_end();
2976 I != E; ++I)
2977 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2978 }
2979 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002980 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2981 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002982 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002983
Douglas Gregor87074f12010-10-20 01:32:02 +00002984 // Provide a stop gap for files that are just seriously broken. Trying
2985 // to correct all typos can turn into a HUGE performance penalty, causing
2986 // some files to take minutes to get rejected by the parser.
2987 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
2988 return DeclarationName();
2989 ++TyposCorrected;
2990
Douglas Gregor2d435302009-12-30 17:04:44 +00002991 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2992 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00002993 IsUnqualifiedLookup = true;
2994 UnqualifiedTyposCorrectedMap::iterator Cached
2995 = UnqualifiedTyposCorrected.find(Typo);
2996 if (Cached == UnqualifiedTyposCorrected.end()) {
2997 // Provide a stop gap for files that are just seriously broken. Trying
2998 // to correct all typos can turn into a HUGE performance penalty, causing
2999 // some files to take minutes to get rejected by the parser.
3000 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3001 return DeclarationName();
3002
3003 // For unqualified lookup, look through all of the names that we have
3004 // seen in this translation unit.
3005 for (IdentifierTable::iterator I = Context.Idents.begin(),
3006 IEnd = Context.Idents.end();
3007 I != IEnd; ++I)
3008 Consumer.FoundName(I->getKey());
3009
3010 // Walk through identifiers in external identifier sources.
3011 if (IdentifierInfoLookup *External
Douglas Gregor57756ea2010-10-14 22:11:03 +00003012 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenekb4ea9a82010-11-07 06:11:33 +00003013 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor87074f12010-10-20 01:32:02 +00003014 do {
3015 llvm::StringRef Name = Iter->Next();
3016 if (Name.empty())
3017 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003018
Douglas Gregor87074f12010-10-20 01:32:02 +00003019 Consumer.FoundName(Name);
3020 } while (true);
3021 }
3022 } else {
3023 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3024 // end up adding the keyword below.
3025 if (Cached->second.first.empty())
3026 return DeclarationName();
3027
3028 if (!Cached->second.second)
3029 Consumer.FoundName(Cached->second.first);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003030 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003031 }
3032
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003033 // Add context-dependent keywords.
3034 bool WantTypeSpecifiers = false;
3035 bool WantExpressionKeywords = false;
3036 bool WantCXXNamedCasts = false;
3037 bool WantRemainingKeywords = false;
3038 switch (CTC) {
3039 case CTC_Unknown:
3040 WantTypeSpecifiers = true;
3041 WantExpressionKeywords = true;
3042 WantCXXNamedCasts = true;
3043 WantRemainingKeywords = true;
Douglas Gregor5fd04d42010-05-18 16:14:23 +00003044
3045 if (ObjCMethodDecl *Method = getCurMethodDecl())
3046 if (Method->getClassInterface() &&
3047 Method->getClassInterface()->getSuperClass())
3048 Consumer.addKeywordResult(Context, "super");
3049
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003050 break;
3051
3052 case CTC_NoKeywords:
3053 break;
3054
3055 case CTC_Type:
3056 WantTypeSpecifiers = true;
3057 break;
3058
3059 case CTC_ObjCMessageReceiver:
3060 Consumer.addKeywordResult(Context, "super");
3061 // Fall through to handle message receivers like expressions.
3062
3063 case CTC_Expression:
3064 if (getLangOptions().CPlusPlus)
3065 WantTypeSpecifiers = true;
3066 WantExpressionKeywords = true;
3067 // Fall through to get C++ named casts.
3068
3069 case CTC_CXXCasts:
3070 WantCXXNamedCasts = true;
3071 break;
3072
Douglas Gregord507d772010-10-20 03:06:34 +00003073 case CTC_ObjCPropertyLookup:
3074 // FIXME: Add "isa"?
3075 break;
3076
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003077 case CTC_MemberLookup:
3078 if (getLangOptions().CPlusPlus)
3079 Consumer.addKeywordResult(Context, "template");
3080 break;
Douglas Gregord507d772010-10-20 03:06:34 +00003081
3082 case CTC_ObjCIvarLookup:
3083 break;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003084 }
3085
3086 if (WantTypeSpecifiers) {
3087 // Add type-specifier keywords to the set of results.
3088 const char *CTypeSpecs[] = {
3089 "char", "const", "double", "enum", "float", "int", "long", "short",
3090 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3091 "_Complex", "_Imaginary",
3092 // storage-specifiers as well
3093 "extern", "inline", "static", "typedef"
3094 };
3095
3096 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3097 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3098 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
3099
3100 if (getLangOptions().C99)
3101 Consumer.addKeywordResult(Context, "restrict");
3102 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3103 Consumer.addKeywordResult(Context, "bool");
3104
3105 if (getLangOptions().CPlusPlus) {
3106 Consumer.addKeywordResult(Context, "class");
3107 Consumer.addKeywordResult(Context, "typename");
3108 Consumer.addKeywordResult(Context, "wchar_t");
3109
3110 if (getLangOptions().CPlusPlus0x) {
3111 Consumer.addKeywordResult(Context, "char16_t");
3112 Consumer.addKeywordResult(Context, "char32_t");
3113 Consumer.addKeywordResult(Context, "constexpr");
3114 Consumer.addKeywordResult(Context, "decltype");
3115 Consumer.addKeywordResult(Context, "thread_local");
3116 }
3117 }
3118
3119 if (getLangOptions().GNUMode)
3120 Consumer.addKeywordResult(Context, "typeof");
3121 }
3122
Douglas Gregor86ad0852010-05-18 16:30:22 +00003123 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003124 Consumer.addKeywordResult(Context, "const_cast");
3125 Consumer.addKeywordResult(Context, "dynamic_cast");
3126 Consumer.addKeywordResult(Context, "reinterpret_cast");
3127 Consumer.addKeywordResult(Context, "static_cast");
3128 }
3129
3130 if (WantExpressionKeywords) {
3131 Consumer.addKeywordResult(Context, "sizeof");
3132 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3133 Consumer.addKeywordResult(Context, "false");
3134 Consumer.addKeywordResult(Context, "true");
3135 }
3136
3137 if (getLangOptions().CPlusPlus) {
3138 const char *CXXExprs[] = {
3139 "delete", "new", "operator", "throw", "typeid"
3140 };
3141 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3142 for (unsigned I = 0; I != NumCXXExprs; ++I)
3143 Consumer.addKeywordResult(Context, CXXExprs[I]);
3144
3145 if (isa<CXXMethodDecl>(CurContext) &&
3146 cast<CXXMethodDecl>(CurContext)->isInstance())
3147 Consumer.addKeywordResult(Context, "this");
3148
3149 if (getLangOptions().CPlusPlus0x) {
3150 Consumer.addKeywordResult(Context, "alignof");
3151 Consumer.addKeywordResult(Context, "nullptr");
3152 }
3153 }
3154 }
3155
3156 if (WantRemainingKeywords) {
3157 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3158 // Statements.
3159 const char *CStmts[] = {
3160 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3161 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3162 for (unsigned I = 0; I != NumCStmts; ++I)
3163 Consumer.addKeywordResult(Context, CStmts[I]);
3164
3165 if (getLangOptions().CPlusPlus) {
3166 Consumer.addKeywordResult(Context, "catch");
3167 Consumer.addKeywordResult(Context, "try");
3168 }
3169
3170 if (S && S->getBreakParent())
3171 Consumer.addKeywordResult(Context, "break");
3172
3173 if (S && S->getContinueParent())
3174 Consumer.addKeywordResult(Context, "continue");
3175
John McCallaab3e412010-08-25 08:40:02 +00003176 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003177 Consumer.addKeywordResult(Context, "case");
3178 Consumer.addKeywordResult(Context, "default");
3179 }
3180 } else {
3181 if (getLangOptions().CPlusPlus) {
3182 Consumer.addKeywordResult(Context, "namespace");
3183 Consumer.addKeywordResult(Context, "template");
3184 }
3185
3186 if (S && S->isClassScope()) {
3187 Consumer.addKeywordResult(Context, "explicit");
3188 Consumer.addKeywordResult(Context, "friend");
3189 Consumer.addKeywordResult(Context, "mutable");
3190 Consumer.addKeywordResult(Context, "private");
3191 Consumer.addKeywordResult(Context, "protected");
3192 Consumer.addKeywordResult(Context, "public");
3193 Consumer.addKeywordResult(Context, "virtual");
3194 }
3195 }
3196
3197 if (getLangOptions().CPlusPlus) {
3198 Consumer.addKeywordResult(Context, "using");
3199
3200 if (getLangOptions().CPlusPlus0x)
3201 Consumer.addKeywordResult(Context, "static_assert");
3202 }
3203 }
3204
3205 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003206 if (Consumer.empty()) {
3207 // If this was an unqualified lookup, note that no correction was found.
3208 if (IsUnqualifiedLookup)
3209 (void)UnqualifiedTyposCorrected[Typo];
3210
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003211 return DeclarationName();
Douglas Gregor87074f12010-10-20 01:32:02 +00003212 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003213
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003214 // Make sure that the user typed at least 3 characters for each correction
3215 // made. Otherwise, we don't even both looking at the results.
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003216
3217 // We also suppress exact matches; those should be handled by a
3218 // different mechanism (e.g., one that introduces qualification in
3219 // C++).
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003220 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor87074f12010-10-20 01:32:02 +00003221 if (ED > 0 && Typo->getName().size() / ED < 3) {
3222 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003223 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003224 (void)UnqualifiedTyposCorrected[Typo];
3225
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003226 return DeclarationName();
Douglas Gregor87074f12010-10-20 01:32:02 +00003227 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003228
3229 // Weed out any names that could not be found by name lookup.
Douglas Gregor26c55782010-10-15 16:49:56 +00003230 bool LastLookupWasAccepted = false;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003231 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3232 IEnd = Consumer.end();
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003233 I != IEnd; /* Increment in loop. */) {
3234 // Keywords are always found.
3235 if (I->second) {
3236 ++I;
3237 continue;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003238 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003239
3240 // Perform name lookup on this name.
3241 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
Douglas Gregord507d772010-10-20 03:06:34 +00003242 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3243 EnteringContext, CTC);
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003244
3245 switch (Res.getResultKind()) {
3246 case LookupResult::NotFound:
3247 case LookupResult::NotFoundInCurrentInstantiation:
3248 case LookupResult::Ambiguous:
3249 // We didn't find this name in our scope, or didn't like what we found;
3250 // ignore it.
3251 Res.suppressDiagnostics();
3252 {
3253 TypoCorrectionConsumer::iterator Next = I;
3254 ++Next;
3255 Consumer.erase(I);
3256 I = Next;
3257 }
Douglas Gregor26c55782010-10-15 16:49:56 +00003258 LastLookupWasAccepted = false;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003259 break;
3260
3261 case LookupResult::Found:
3262 case LookupResult::FoundOverloaded:
3263 case LookupResult::FoundUnresolvedValue:
3264 ++I;
Douglas Gregord507d772010-10-20 03:06:34 +00003265 LastLookupWasAccepted = true;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003266 break;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003267 }
3268
3269 if (Res.isAmbiguous()) {
3270 // We don't deal with ambiguities.
3271 Res.suppressDiagnostics();
3272 Res.clear();
3273 return DeclarationName();
3274 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003275 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003276
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003277 // If only a single name remains, return that result.
Douglas Gregor26c55782010-10-15 16:49:56 +00003278 if (Consumer.size() == 1) {
3279 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor1f32ebe2010-10-20 01:01:57 +00003280 if (Consumer.begin()->second) {
3281 Res.suppressDiagnostics();
3282 Res.clear();
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003283
3284 // Don't correct to a keyword that's the same as the typo; the keyword
3285 // wasn't actually in scope.
3286 if (ED == 0) {
3287 Res.setLookupName(Typo);
3288 return DeclarationName();
3289 }
3290
Douglas Gregor1f32ebe2010-10-20 01:01:57 +00003291 } else if (!LastLookupWasAccepted) {
Douglas Gregor26c55782010-10-15 16:49:56 +00003292 // Perform name lookup on this name.
Douglas Gregord507d772010-10-20 03:06:34 +00003293 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3294 EnteringContext, CTC);
Douglas Gregor26c55782010-10-15 16:49:56 +00003295 }
3296
Douglas Gregor87074f12010-10-20 01:32:02 +00003297 // Record the correction for unqualified lookup.
3298 if (IsUnqualifiedLookup)
3299 UnqualifiedTyposCorrected[Typo]
Douglas Gregord507d772010-10-20 03:06:34 +00003300 = std::make_pair(Name->getName(), Consumer.begin()->second);
Douglas Gregor87074f12010-10-20 01:32:02 +00003301
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003302 return &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor26c55782010-10-15 16:49:56 +00003303 }
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003304 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
3305 && Consumer["super"]) {
3306 // Prefix 'super' when we're completing in a message-receiver
3307 // context.
3308 Res.suppressDiagnostics();
3309 Res.clear();
Douglas Gregor87074f12010-10-20 01:32:02 +00003310
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003311 // Don't correct to a keyword that's the same as the typo; the keyword
3312 // wasn't actually in scope.
3313 if (ED == 0) {
3314 Res.setLookupName(Typo);
3315 return DeclarationName();
3316 }
3317
Douglas Gregor87074f12010-10-20 01:32:02 +00003318 // Record the correction for unqualified lookup.
3319 if (IsUnqualifiedLookup)
3320 UnqualifiedTyposCorrected[Typo]
Douglas Gregord507d772010-10-20 03:06:34 +00003321 = std::make_pair("super", Consumer.begin()->second);
Douglas Gregor87074f12010-10-20 01:32:02 +00003322
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003323 return &Context.Idents.get("super");
3324 }
3325
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003326 Res.suppressDiagnostics();
3327 Res.setLookupName(Typo);
Douglas Gregor2d435302009-12-30 17:04:44 +00003328 Res.clear();
Douglas Gregor87074f12010-10-20 01:32:02 +00003329 // Record the correction for unqualified lookup.
3330 if (IsUnqualifiedLookup)
3331 (void)UnqualifiedTyposCorrected[Typo];
3332
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003333 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003334}