blob: 6972536e8c28322a067f1329c7e6286ebee01a4b [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!
John McCalldb40c7f2010-12-14 08:05:40 +0000674 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
675 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
676 EPI.HasExceptionSpec = false;
677 EPI.HasAnyExceptionSpec = false;
678 EPI.NumExceptions = 0;
Chandler Carruth3a693b72010-01-31 11:44:02 +0000679 QualType ExpectedType
680 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCalldb40c7f2010-12-14 08:05:40 +0000681 0, 0, EPI);
Chandler Carruth3a693b72010-01-31 11:44:02 +0000682
683 // Perform template argument deduction against the type that we would
684 // expect the function to have.
685 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
686 Specialization, Info)
687 == Sema::TDK_Success) {
688 R.addDecl(Specialization);
689 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000690 }
691 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000692
John McCall9f3059a2009-10-09 21:13:30 +0000693 return Found;
694}
695
John McCallf6c8a4e2009-11-10 07:01:13 +0000696// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000697static bool
Douglas Gregord3a59182010-02-12 05:48:04 +0000698CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
699 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000700
701 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
702
John McCallf6c8a4e2009-11-10 07:01:13 +0000703 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000704 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000705
John McCallf6c8a4e2009-11-10 07:01:13 +0000706 // Perform direct name lookup into the namespaces nominated by the
707 // using directives whose common ancestor is this namespace.
708 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
709 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000710
John McCallf6c8a4e2009-11-10 07:01:13 +0000711 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000712 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000713 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000714
715 R.resolveKind();
716
717 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000718}
719
720static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000721 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000722 return Ctx->isFileContext();
723 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000724}
Douglas Gregored8f2882009-01-30 01:04:22 +0000725
Douglas Gregor66230062010-03-15 14:33:29 +0000726// Find the next outer declaration context from this scope. This
727// routine actually returns the semantic outer context, which may
728// differ from the lexical context (encoded directly in the Scope
729// stack) when we are parsing a member of a class template. In this
730// case, the second element of the pair will be true, to indicate that
731// name lookup should continue searching in this semantic context when
732// it leaves the current template parameter scope.
733static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
734 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
735 DeclContext *Lexical = 0;
736 for (Scope *OuterS = S->getParent(); OuterS;
737 OuterS = OuterS->getParent()) {
738 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000739 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000740 break;
741 }
742 }
743
744 // C++ [temp.local]p8:
745 // In the definition of a member of a class template that appears
746 // outside of the namespace containing the class template
747 // definition, the name of a template-parameter hides the name of
748 // a member of this namespace.
749 //
750 // Example:
751 //
752 // namespace N {
753 // class C { };
754 //
755 // template<class T> class B {
756 // void f(T);
757 // };
758 // }
759 //
760 // template<class C> void N::B<C>::f(C) {
761 // C b; // C is the template parameter, not N::C
762 // }
763 //
764 // In this example, the lexical context we return is the
765 // TranslationUnit, while the semantic context is the namespace N.
766 if (!Lexical || !DC || !S->getParent() ||
767 !S->getParent()->isTemplateParamScope())
768 return std::make_pair(Lexical, false);
769
770 // Find the outermost template parameter scope.
771 // For the example, this is the scope for the template parameters of
772 // template<class C>.
773 Scope *OutermostTemplateScope = S->getParent();
774 while (OutermostTemplateScope->getParent() &&
775 OutermostTemplateScope->getParent()->isTemplateParamScope())
776 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregor7f737c02009-09-10 16:57:35 +0000777
Douglas Gregor66230062010-03-15 14:33:29 +0000778 // Find the namespace context in which the original scope occurs. In
779 // the example, this is namespace N.
780 DeclContext *Semantic = DC;
781 while (!Semantic->isFileContext())
782 Semantic = Semantic->getParent();
783
784 // Find the declaration context just outside of the template
785 // parameter scope. This is the context in which the template is
786 // being lexically declaration (a namespace context). In the
787 // example, this is the global scope.
788 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
789 Lexical->Encloses(Semantic))
790 return std::make_pair(Semantic, true);
791
792 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000793}
794
John McCall27b18f82009-11-17 02:14:36 +0000795bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000796 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000797
798 DeclarationName Name = R.getLookupName();
799
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000800 // If this is the name of an implicitly-declared special member function,
801 // go through the scope stack to implicitly declare
802 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
803 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
804 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
805 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
806 }
807
808 // Implicitly declare member functions with the name we're looking for, if in
809 // fact we are in a scope where it matters.
810
Douglas Gregor889ceb72009-02-03 19:21:40 +0000811 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000812 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000813 I = IdResolver.begin(Name),
814 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000815
Douglas Gregor889ceb72009-02-03 19:21:40 +0000816 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000817 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000818 // ...During unqualified name lookup (3.4.1), the names appear as if
819 // they were declared in the nearest enclosing namespace which contains
820 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000821 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000822 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000823 //
824 // For example:
825 // namespace A { int i; }
826 // void foo() {
827 // int i;
828 // {
829 // using namespace A;
830 // ++i; // finds local 'i', A::i appears at global scope
831 // }
832 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000833 //
Douglas Gregor66230062010-03-15 14:33:29 +0000834 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000835 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000836 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
837
Douglas Gregor889ceb72009-02-03 19:21:40 +0000838 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000839 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000840 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000841 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000842 Found = true;
843 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000844 }
845 }
John McCall9f3059a2009-10-09 21:13:30 +0000846 if (Found) {
847 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000848 if (S->isClassScope())
849 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
850 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000851 return true;
852 }
853
Douglas Gregor66230062010-03-15 14:33:29 +0000854 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
855 S->getParent() && !S->getParent()->isTemplateParamScope()) {
856 // We've just searched the last template parameter scope and
857 // found nothing, so look into the the contexts between the
858 // lexical and semantic declaration contexts returned by
859 // findOuterContext(). This implements the name lookup behavior
860 // of C++ [temp.local]p8.
861 Ctx = OutsideOfTemplateParamDC;
862 OutsideOfTemplateParamDC = 0;
863 }
864
865 if (Ctx) {
866 DeclContext *OuterCtx;
867 bool SearchAfterTemplateScope;
868 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
869 if (SearchAfterTemplateScope)
870 OutsideOfTemplateParamDC = OuterCtx;
871
Douglas Gregorea166062010-03-15 15:26:48 +0000872 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000873 // We do not directly look into transparent contexts, since
874 // those entities will be found in the nearest enclosing
875 // non-transparent context.
876 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000877 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000878
879 // We do not look directly into function or method contexts,
880 // since all of the local variables and parameters of the
881 // function/method are present within the Scope.
882 if (Ctx->isFunctionOrMethod()) {
883 // If we have an Objective-C instance method, look for ivars
884 // in the corresponding interface.
885 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
886 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
887 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
888 ObjCInterfaceDecl *ClassDeclared;
889 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
890 Name.getAsIdentifierInfo(),
891 ClassDeclared)) {
892 if (R.isAcceptableDecl(Ivar)) {
893 R.addDecl(Ivar);
894 R.resolveKind();
895 return true;
896 }
897 }
898 }
899 }
900
901 continue;
902 }
903
Douglas Gregor7f737c02009-09-10 16:57:35 +0000904 // Perform qualified name lookup into this context.
905 // FIXME: In some cases, we know that every name that could be found by
906 // this qualified name lookup will also be on the identifier chain. For
907 // example, inside a class without any base classes, we never need to
908 // perform qualified lookup because all of the members are on top of the
909 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000910 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000911 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000912 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000913 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000914 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000915
John McCallf6c8a4e2009-11-10 07:01:13 +0000916 // Stop if we ran out of scopes.
917 // FIXME: This really, really shouldn't be happening.
918 if (!S) return false;
919
Argyrios Kyrtzidis706bbf82010-10-29 16:12:50 +0000920 // If we are looking for members, no need to look into global/namespace scope.
921 if (R.getLookupKind() == LookupMemberName)
922 return false;
923
Douglas Gregor700792c2009-02-05 19:25:20 +0000924 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000925 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000926 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000927 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
928 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000929
John McCallf6c8a4e2009-11-10 07:01:13 +0000930 UnqualUsingDirectiveSet UDirs;
931 UDirs.visitScopeChain(Initial, S);
932 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000933
Douglas Gregor700792c2009-02-05 19:25:20 +0000934 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000935 // Unqualified name lookup in C++ requires looking into scopes
936 // that aren't strictly lexical, and therefore we walk through the
937 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000938
Douglas Gregor889ceb72009-02-03 19:21:40 +0000939 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000940 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000941 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000942 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000943 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000944 // We found something. Look for anything else in our scope
945 // with this same name and in an acceptable identifier
946 // namespace, so that we can construct an overload set if we
947 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000948 Found = true;
949 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000950 }
951 }
952
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000953 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000954 R.resolveKind();
955 return true;
956 }
957
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000958 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
959 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
960 S->getParent() && !S->getParent()->isTemplateParamScope()) {
961 // We've just searched the last template parameter scope and
962 // found nothing, so look into the the contexts between the
963 // lexical and semantic declaration contexts returned by
964 // findOuterContext(). This implements the name lookup behavior
965 // of C++ [temp.local]p8.
966 Ctx = OutsideOfTemplateParamDC;
967 OutsideOfTemplateParamDC = 0;
968 }
969
970 if (Ctx) {
971 DeclContext *OuterCtx;
972 bool SearchAfterTemplateScope;
973 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
974 if (SearchAfterTemplateScope)
975 OutsideOfTemplateParamDC = OuterCtx;
976
977 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
978 // We do not directly look into transparent contexts, since
979 // those entities will be found in the nearest enclosing
980 // non-transparent context.
981 if (Ctx->isTransparentContext())
982 continue;
983
984 // If we have a context, and it's not a context stashed in the
985 // template parameter scope for an out-of-line definition, also
986 // look into that context.
987 if (!(Found && S && S->isTemplateParamScope())) {
988 assert(Ctx->isFileContext() &&
989 "We should have been looking only at file context here already.");
990
991 // Look into context considering using-directives.
992 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
993 Found = true;
994 }
995
996 if (Found) {
997 R.resolveKind();
998 return true;
999 }
1000
1001 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1002 return false;
1003 }
1004 }
1005
Douglas Gregor3ce74932010-02-05 07:07:10 +00001006 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +00001007 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001008 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001009
John McCall9f3059a2009-10-09 21:13:30 +00001010 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001011}
1012
Douglas Gregor34074322009-01-14 22:20:51 +00001013/// @brief Perform unqualified name lookup starting from a given
1014/// scope.
1015///
1016/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1017/// used to find names within the current scope. For example, 'x' in
1018/// @code
1019/// int x;
1020/// int f() {
1021/// return x; // unqualified name look finds 'x' in the global scope
1022/// }
1023/// @endcode
1024///
1025/// Different lookup criteria can find different names. For example, a
1026/// particular scope can have both a struct and a function of the same
1027/// name, and each can be found by certain lookup criteria. For more
1028/// information about lookup criteria, see the documentation for the
1029/// class LookupCriteria.
1030///
1031/// @param S The scope from which unqualified name lookup will
1032/// begin. If the lookup criteria permits, name lookup may also search
1033/// in the parent scopes.
1034///
1035/// @param Name The name of the entity that we are searching for.
1036///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001037/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001038/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001039/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001040///
1041/// @returns The result of name lookup, which includes zero or more
1042/// declarations and possibly additional information used to diagnose
1043/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001044bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1045 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001046 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001047
John McCall27b18f82009-11-17 02:14:36 +00001048 LookupNameKind NameKind = R.getLookupKind();
1049
Douglas Gregor34074322009-01-14 22:20:51 +00001050 if (!getLangOptions().CPlusPlus) {
1051 // Unqualified name lookup in C/Objective-C is purely lexical, so
1052 // search in the declarations attached to the name.
1053
John McCallea305ed2009-12-18 10:40:03 +00001054 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001055 // Find the nearest non-transparent declaration scope.
1056 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001057 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001058 static_cast<DeclContext *>(S->getEntity())
1059 ->isTransparentContext()))
1060 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001061 }
1062
John McCallea305ed2009-12-18 10:40:03 +00001063 unsigned IDNS = R.getIdentifierNamespace();
1064
Douglas Gregor34074322009-01-14 22:20:51 +00001065 // Scan up the scope chain looking for a decl that matches this
1066 // identifier that is in the appropriate namespace. This search
1067 // should not take long, as shadowing of names is uncommon, and
1068 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001069 bool LeftStartingScope = false;
1070
Douglas Gregored8f2882009-01-30 01:04:22 +00001071 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001072 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001073 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001074 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001075 if (NameKind == LookupRedeclarationWithLinkage) {
1076 // Determine whether this (or a previous) declaration is
1077 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001078 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001079 LeftStartingScope = true;
1080
1081 // If we found something outside of our starting scope that
1082 // does not have linkage, skip it.
1083 if (LeftStartingScope && !((*I)->hasLinkage()))
1084 continue;
1085 }
1086
John McCall9f3059a2009-10-09 21:13:30 +00001087 R.addDecl(*I);
1088
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001089 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001090 // If this declaration has the "overloadable" attribute, we
1091 // might have a set of overloaded functions.
1092
1093 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001094 while (!(S->getFlags() & Scope::DeclScope) ||
John McCall48871652010-08-21 09:40:31 +00001095 !S->isDeclScope(*I))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001096 S = S->getParent();
1097
1098 // Find the last declaration in this scope (with the same
1099 // name, naturally).
1100 IdentifierResolver::iterator LastI = I;
1101 for (++LastI; LastI != IEnd; ++LastI) {
John McCall48871652010-08-21 09:40:31 +00001102 if (!S->isDeclScope(*LastI))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001103 break;
John McCall9f3059a2009-10-09 21:13:30 +00001104 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001105 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001106 }
1107
John McCall9f3059a2009-10-09 21:13:30 +00001108 R.resolveKind();
1109
1110 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001111 }
Douglas Gregor34074322009-01-14 22:20:51 +00001112 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001113 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001114 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001115 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001116 }
1117
1118 // If we didn't find a use of this identifier, and if the identifier
1119 // corresponds to a compiler builtin, create the decl object for the builtin
1120 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +00001121 if (AllowBuiltinCreation)
1122 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001123
John McCall9f3059a2009-10-09 21:13:30 +00001124 return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001125}
1126
John McCall6538c932009-10-10 05:48:19 +00001127/// @brief Perform qualified name lookup in the namespaces nominated by
1128/// using directives by the given context.
1129///
1130/// C++98 [namespace.qual]p2:
1131/// Given X::m (where X is a user-declared namespace), or given ::m
1132/// (where X is the global namespace), let S be the set of all
1133/// declarations of m in X and in the transitive closure of all
1134/// namespaces nominated by using-directives in X and its used
1135/// namespaces, except that using-directives are ignored in any
1136/// namespace, including X, directly containing one or more
1137/// declarations of m. No namespace is searched more than once in
1138/// the lookup of a name. If S is the empty set, the program is
1139/// ill-formed. Otherwise, if S has exactly one member, or if the
1140/// context of the reference is a using-declaration
1141/// (namespace.udecl), S is the required set of declarations of
1142/// m. Otherwise if the use of m is not one that allows a unique
1143/// declaration to be chosen from S, the program is ill-formed.
1144/// C++98 [namespace.qual]p5:
1145/// During the lookup of a qualified namespace member name, if the
1146/// lookup finds more than one declaration of the member, and if one
1147/// declaration introduces a class name or enumeration name and the
1148/// other declarations either introduce the same object, the same
1149/// enumerator or a set of functions, the non-type name hides the
1150/// class or enumeration name if and only if the declarations are
1151/// from the same namespace; otherwise (the declarations are from
1152/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001153static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001154 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001155 assert(StartDC->isFileContext() && "start context is not a file context");
1156
1157 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1158 DeclContext::udir_iterator E = StartDC->using_directives_end();
1159
1160 if (I == E) return false;
1161
1162 // We have at least added all these contexts to the queue.
1163 llvm::DenseSet<DeclContext*> Visited;
1164 Visited.insert(StartDC);
1165
1166 // We have not yet looked into these namespaces, much less added
1167 // their "using-children" to the queue.
1168 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1169
1170 // We have already looked into the initial namespace; seed the queue
1171 // with its using-children.
1172 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001173 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001174 if (Visited.insert(ND).second)
1175 Queue.push_back(ND);
1176 }
1177
1178 // The easiest way to implement the restriction in [namespace.qual]p5
1179 // is to check whether any of the individual results found a tag
1180 // and, if so, to declare an ambiguity if the final result is not
1181 // a tag.
1182 bool FoundTag = false;
1183 bool FoundNonTag = false;
1184
John McCall5cebab12009-11-18 07:57:50 +00001185 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001186
1187 bool Found = false;
1188 while (!Queue.empty()) {
1189 NamespaceDecl *ND = Queue.back();
1190 Queue.pop_back();
1191
1192 // We go through some convolutions here to avoid copying results
1193 // between LookupResults.
1194 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001195 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001196 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001197
1198 if (FoundDirect) {
1199 // First do any local hiding.
1200 DirectR.resolveKind();
1201
1202 // If the local result is a tag, remember that.
1203 if (DirectR.isSingleTagDecl())
1204 FoundTag = true;
1205 else
1206 FoundNonTag = true;
1207
1208 // Append the local results to the total results if necessary.
1209 if (UseLocal) {
1210 R.addAllDecls(LocalR);
1211 LocalR.clear();
1212 }
1213 }
1214
1215 // If we find names in this namespace, ignore its using directives.
1216 if (FoundDirect) {
1217 Found = true;
1218 continue;
1219 }
1220
1221 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1222 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1223 if (Visited.insert(Nom).second)
1224 Queue.push_back(Nom);
1225 }
1226 }
1227
1228 if (Found) {
1229 if (FoundTag && FoundNonTag)
1230 R.setAmbiguousQualifiedTagHiding();
1231 else
1232 R.resolveKind();
1233 }
1234
1235 return Found;
1236}
1237
Douglas Gregor39982192010-08-15 06:18:01 +00001238/// \brief Callback that looks for any member of a class with the given name.
1239static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1240 CXXBasePath &Path,
1241 void *Name) {
1242 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1243
1244 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1245 Path.Decls = BaseRecord->lookup(N);
1246 return Path.Decls.first != Path.Decls.second;
1247}
1248
Douglas Gregorc0d24902010-10-22 22:08:47 +00001249/// \brief Determine whether the given set of member declarations contains only
1250/// static members, nested types, and enumerators.
1251template<typename InputIterator>
1252static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1253 Decl *D = (*First)->getUnderlyingDecl();
1254 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1255 return true;
1256
1257 if (isa<CXXMethodDecl>(D)) {
1258 // Determine whether all of the methods are static.
1259 bool AllMethodsAreStatic = true;
1260 for(; First != Last; ++First) {
1261 D = (*First)->getUnderlyingDecl();
1262
1263 if (!isa<CXXMethodDecl>(D)) {
1264 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1265 break;
1266 }
1267
1268 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1269 AllMethodsAreStatic = false;
1270 break;
1271 }
1272 }
1273
1274 if (AllMethodsAreStatic)
1275 return true;
1276 }
1277
1278 return false;
1279}
1280
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001281/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001282///
1283/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1284/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001285/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001286///
1287/// Different lookup criteria can find different names. For example, a
1288/// particular scope can have both a struct and a function of the same
1289/// name, and each can be found by certain lookup criteria. For more
1290/// information about lookup criteria, see the documentation for the
1291/// class LookupCriteria.
1292///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001293/// \param R captures both the lookup criteria and any lookup results found.
1294///
1295/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001296/// search. If the lookup criteria permits, name lookup may also search
1297/// in the parent contexts or (for C++ classes) base classes.
1298///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001299/// \param InUnqualifiedLookup true if this is qualified name lookup that
1300/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001301///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001302/// \returns true if lookup succeeded, false if it failed.
1303bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1304 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001305 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001306
John McCall27b18f82009-11-17 02:14:36 +00001307 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001308 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001309
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001310 // Make sure that the declaration context is complete.
1311 assert((!isa<TagDecl>(LookupCtx) ||
1312 LookupCtx->isDependentContext() ||
1313 cast<TagDecl>(LookupCtx)->isDefinition() ||
1314 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1315 ->isBeingDefined()) &&
1316 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001317
Douglas Gregor34074322009-01-14 22:20:51 +00001318 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001319 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001320 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001321 if (isa<CXXRecordDecl>(LookupCtx))
1322 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001323 return true;
1324 }
Douglas Gregor34074322009-01-14 22:20:51 +00001325
John McCall6538c932009-10-10 05:48:19 +00001326 // Don't descend into implied contexts for redeclarations.
1327 // C++98 [namespace.qual]p6:
1328 // In a declaration for a namespace member in which the
1329 // declarator-id is a qualified-id, given that the qualified-id
1330 // for the namespace member has the form
1331 // nested-name-specifier unqualified-id
1332 // the unqualified-id shall name a member of the namespace
1333 // designated by the nested-name-specifier.
1334 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001335 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001336 return false;
1337
John McCall27b18f82009-11-17 02:14:36 +00001338 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001339 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001340 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001341
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001342 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001343 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001344 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001345 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001346 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001347
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001348 // If we're performing qualified name lookup into a dependent class,
1349 // then we are actually looking into a current instantiation. If we have any
1350 // dependent base classes, then we either have to delay lookup until
1351 // template instantiation time (at which point all bases will be available)
1352 // or we have to fail.
1353 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1354 LookupRec->hasAnyDependentBases()) {
1355 R.setNotFoundInCurrentInstantiation();
1356 return false;
1357 }
1358
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001359 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001360 CXXBasePaths Paths;
1361 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001362
1363 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001364 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001365 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001366 case LookupOrdinaryName:
1367 case LookupMemberName:
1368 case LookupRedeclarationWithLinkage:
1369 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1370 break;
1371
1372 case LookupTagName:
1373 BaseCallback = &CXXRecordDecl::FindTagMember;
1374 break;
John McCall84d87672009-12-10 09:41:52 +00001375
Douglas Gregor39982192010-08-15 06:18:01 +00001376 case LookupAnyName:
1377 BaseCallback = &LookupAnyMember;
1378 break;
1379
John McCall84d87672009-12-10 09:41:52 +00001380 case LookupUsingDeclName:
1381 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001382
1383 case LookupOperatorName:
1384 case LookupNamespaceName:
1385 case LookupObjCProtocolName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001386 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001387 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001388
1389 case LookupNestedNameSpecifierName:
1390 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1391 break;
1392 }
1393
John McCall27b18f82009-11-17 02:14:36 +00001394 if (!LookupRec->lookupInBases(BaseCallback,
1395 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001396 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001397
John McCall553c0792010-01-23 00:46:32 +00001398 R.setNamingClass(LookupRec);
1399
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001400 // C++ [class.member.lookup]p2:
1401 // [...] If the resulting set of declarations are not all from
1402 // sub-objects of the same type, or the set has a nonstatic member
1403 // and includes members from distinct sub-objects, there is an
1404 // ambiguity and the program is ill-formed. Otherwise that set is
1405 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001406 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001407 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001408 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001409
Douglas Gregor36d1b142009-10-06 17:59:45 +00001410 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001411 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001412 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001413
John McCall401982f2010-01-20 21:53:11 +00001414 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1415 // across all paths.
1416 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1417
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001418 // Determine whether we're looking at a distinct sub-object or not.
1419 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001420 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001421 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1422 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001423 continue;
1424 }
1425
1426 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001427 != Context.getCanonicalType(PathElement.Base->getType())) {
1428 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001429 // different types. If the declaration sets aren't the same, this
1430 // this lookup is ambiguous.
1431 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1432 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1433 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1434 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
1435
1436 while (FirstD != FirstPath->Decls.second &&
1437 CurrentD != Path->Decls.second) {
1438 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1439 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1440 break;
1441
1442 ++FirstD;
1443 ++CurrentD;
1444 }
1445
1446 if (FirstD == FirstPath->Decls.second &&
1447 CurrentD == Path->Decls.second)
1448 continue;
1449 }
1450
John McCall9f3059a2009-10-09 21:13:30 +00001451 R.setAmbiguousBaseSubobjectTypes(Paths);
1452 return true;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001453 }
1454
1455 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001456 // We have a different subobject of the same type.
1457
1458 // C++ [class.member.lookup]p5:
1459 // A static member, a nested type or an enumerator defined in
1460 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001461 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001462 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001463 continue;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001464
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001465 // We have found a nonstatic member name in multiple, distinct
1466 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001467 R.setAmbiguousBaseSubobjects(Paths);
1468 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001469 }
1470 }
1471
1472 // Lookup in a base class succeeded; return these results.
1473
John McCall9f3059a2009-10-09 21:13:30 +00001474 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001475 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1476 NamedDecl *D = *I;
1477 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1478 D->getAccess());
1479 R.addDecl(D, AS);
1480 }
John McCall9f3059a2009-10-09 21:13:30 +00001481 R.resolveKind();
1482 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001483}
1484
1485/// @brief Performs name lookup for a name that was parsed in the
1486/// source code, and may contain a C++ scope specifier.
1487///
1488/// This routine is a convenience routine meant to be called from
1489/// contexts that receive a name and an optional C++ scope specifier
1490/// (e.g., "N::M::x"). It will then perform either qualified or
1491/// unqualified name lookup (with LookupQualifiedName or LookupName,
1492/// respectively) on the given name and return those results.
1493///
1494/// @param S The scope from which unqualified name lookup will
1495/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001496///
Douglas Gregore861bac2009-08-25 22:51:20 +00001497/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001498///
Douglas Gregore861bac2009-08-25 22:51:20 +00001499/// @param EnteringContext Indicates whether we are going to enter the
1500/// context of the scope-specifier SS (if present).
1501///
John McCall9f3059a2009-10-09 21:13:30 +00001502/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001503bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001504 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001505 if (SS && SS->isInvalid()) {
1506 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001507 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001508 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001509 }
Mike Stump11289f42009-09-09 15:08:12 +00001510
Douglas Gregore861bac2009-08-25 22:51:20 +00001511 if (SS && SS->isSet()) {
1512 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001513 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001514 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001515 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001516 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001517
John McCall27b18f82009-11-17 02:14:36 +00001518 R.setContextRange(SS->getRange());
1519
1520 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001521 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001522
Douglas Gregore861bac2009-08-25 22:51:20 +00001523 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001524 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001525 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001526 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001527 }
1528
Mike Stump11289f42009-09-09 15:08:12 +00001529 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001530 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001531}
1532
Douglas Gregor889ceb72009-02-03 19:21:40 +00001533
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001534/// @brief Produce a diagnostic describing the ambiguity that resulted
1535/// from name lookup.
1536///
1537/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001538///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001539/// @param Name The name of the entity that name lookup was
1540/// searching for.
1541///
1542/// @param NameLoc The location of the name within the source code.
1543///
1544/// @param LookupRange A source range that provides more
1545/// source-location information concerning the lookup itself. For
1546/// example, this range might highlight a nested-name-specifier that
1547/// precedes the name.
1548///
1549/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001550bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001551 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1552
John McCall27b18f82009-11-17 02:14:36 +00001553 DeclarationName Name = Result.getLookupName();
1554 SourceLocation NameLoc = Result.getNameLoc();
1555 SourceRange LookupRange = Result.getContextRange();
1556
John McCall6538c932009-10-10 05:48:19 +00001557 switch (Result.getAmbiguityKind()) {
1558 case LookupResult::AmbiguousBaseSubobjects: {
1559 CXXBasePaths *Paths = Result.getBasePaths();
1560 QualType SubobjectType = Paths->front().back().Base->getType();
1561 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1562 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1563 << LookupRange;
1564
1565 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1566 while (isa<CXXMethodDecl>(*Found) &&
1567 cast<CXXMethodDecl>(*Found)->isStatic())
1568 ++Found;
1569
1570 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1571
1572 return true;
1573 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001574
John McCall6538c932009-10-10 05:48:19 +00001575 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001576 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1577 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001578
1579 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001580 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001581 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1582 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001583 Path != PathEnd; ++Path) {
1584 Decl *D = *Path->Decls.first;
1585 if (DeclsPrinted.insert(D).second)
1586 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1587 }
1588
Douglas Gregor1c846b02009-01-16 00:38:09 +00001589 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001590 }
1591
John McCall6538c932009-10-10 05:48:19 +00001592 case LookupResult::AmbiguousTagHiding: {
1593 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001594
John McCall6538c932009-10-10 05:48:19 +00001595 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1596
1597 LookupResult::iterator DI, DE = Result.end();
1598 for (DI = Result.begin(); DI != DE; ++DI)
1599 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1600 TagDecls.insert(TD);
1601 Diag(TD->getLocation(), diag::note_hidden_tag);
1602 }
1603
1604 for (DI = Result.begin(); DI != DE; ++DI)
1605 if (!isa<TagDecl>(*DI))
1606 Diag((*DI)->getLocation(), diag::note_hiding_object);
1607
1608 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001609 LookupResult::Filter F = Result.makeFilter();
1610 while (F.hasNext()) {
1611 if (TagDecls.count(F.next()))
1612 F.erase();
1613 }
1614 F.done();
John McCall6538c932009-10-10 05:48:19 +00001615
1616 return true;
1617 }
1618
1619 case LookupResult::AmbiguousReference: {
1620 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001621
John McCall6538c932009-10-10 05:48:19 +00001622 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1623 for (; DI != DE; ++DI)
1624 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001625
John McCall6538c932009-10-10 05:48:19 +00001626 return true;
1627 }
1628 }
1629
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001630 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001631 return true;
1632}
Douglas Gregore254f902009-02-04 00:32:51 +00001633
John McCallf24d7bb2010-05-28 18:45:08 +00001634namespace {
1635 struct AssociatedLookup {
1636 AssociatedLookup(Sema &S,
1637 Sema::AssociatedNamespaceSet &Namespaces,
1638 Sema::AssociatedClassSet &Classes)
1639 : S(S), Namespaces(Namespaces), Classes(Classes) {
1640 }
1641
1642 Sema &S;
1643 Sema::AssociatedNamespaceSet &Namespaces;
1644 Sema::AssociatedClassSet &Classes;
1645 };
1646}
1647
Mike Stump11289f42009-09-09 15:08:12 +00001648static void
John McCallf24d7bb2010-05-28 18:45:08 +00001649addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001650
Douglas Gregor8b895222010-04-30 07:08:38 +00001651static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1652 DeclContext *Ctx) {
1653 // Add the associated namespace for this class.
1654
1655 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1656 // be a locally scoped record.
1657
Sebastian Redlbd595762010-08-31 20:53:31 +00001658 // We skip out of inline namespaces. The innermost non-inline namespace
1659 // contains all names of all its nested inline namespaces anyway, so we can
1660 // replace the entire inline namespace tree with its root.
1661 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1662 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001663 Ctx = Ctx->getParent();
1664
John McCallc7e8e792009-08-07 22:18:02 +00001665 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001666 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001667}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001668
Mike Stump11289f42009-09-09 15:08:12 +00001669// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001670// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001671static void
John McCallf24d7bb2010-05-28 18:45:08 +00001672addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1673 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001674 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001675 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001676 switch (Arg.getKind()) {
1677 case TemplateArgument::Null:
1678 break;
Mike Stump11289f42009-09-09 15:08:12 +00001679
Douglas Gregor197e5f72009-07-08 07:51:57 +00001680 case TemplateArgument::Type:
1681 // [...] the namespaces and classes associated with the types of the
1682 // template arguments provided for template type parameters (excluding
1683 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001684 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001685 break;
Mike Stump11289f42009-09-09 15:08:12 +00001686
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001687 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001688 // [...] the namespaces in which any template template arguments are
1689 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001690 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001691 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001692 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001693 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001694 DeclContext *Ctx = ClassTemplate->getDeclContext();
1695 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001696 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001697 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001698 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001699 }
1700 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001701 }
1702
1703 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001704 case TemplateArgument::Integral:
1705 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001706 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001707 // associated namespaces. ]
1708 break;
Mike Stump11289f42009-09-09 15:08:12 +00001709
Douglas Gregor197e5f72009-07-08 07:51:57 +00001710 case TemplateArgument::Pack:
1711 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1712 PEnd = Arg.pack_end();
1713 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001714 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001715 break;
1716 }
1717}
1718
Douglas Gregore254f902009-02-04 00:32:51 +00001719// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001720// argument-dependent lookup with an argument of class type
1721// (C++ [basic.lookup.koenig]p2).
1722static void
John McCallf24d7bb2010-05-28 18:45:08 +00001723addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1724 CXXRecordDecl *Class) {
1725
1726 // Just silently ignore anything whose name is __va_list_tag.
1727 if (Class->getDeclName() == Result.S.VAListTagName)
1728 return;
1729
Douglas Gregore254f902009-02-04 00:32:51 +00001730 // C++ [basic.lookup.koenig]p2:
1731 // [...]
1732 // -- If T is a class type (including unions), its associated
1733 // classes are: the class itself; the class of which it is a
1734 // member, if any; and its direct and indirect base
1735 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001736 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001737
1738 // Add the class of which it is a member, if any.
1739 DeclContext *Ctx = Class->getDeclContext();
1740 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001741 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001742 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001743 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001744
Douglas Gregore254f902009-02-04 00:32:51 +00001745 // Add the class itself. If we've already seen this class, we don't
1746 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001747 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001748 return;
1749
Mike Stump11289f42009-09-09 15:08:12 +00001750 // -- If T is a template-id, its associated namespaces and classes are
1751 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001752 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001753 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001754 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001755 // namespaces in which any template template arguments are defined; and
1756 // the classes in which any member templates used as template template
1757 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001758 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001759 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001760 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1761 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1762 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001763 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001764 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001765 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001766
Douglas Gregor197e5f72009-07-08 07:51:57 +00001767 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1768 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001769 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001770 }
Mike Stump11289f42009-09-09 15:08:12 +00001771
John McCall67da35c2010-02-04 22:26:26 +00001772 // Only recurse into base classes for complete types.
1773 if (!Class->hasDefinition()) {
1774 // FIXME: we might need to instantiate templates here
1775 return;
1776 }
1777
Douglas Gregore254f902009-02-04 00:32:51 +00001778 // Add direct and indirect base classes along with their associated
1779 // namespaces.
1780 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1781 Bases.push_back(Class);
1782 while (!Bases.empty()) {
1783 // Pop this class off the stack.
1784 Class = Bases.back();
1785 Bases.pop_back();
1786
1787 // Visit the base classes.
1788 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1789 BaseEnd = Class->bases_end();
1790 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001791 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001792 // In dependent contexts, we do ADL twice, and the first time around,
1793 // the base type might be a dependent TemplateSpecializationType, or a
1794 // TemplateTypeParmType. If that happens, simply ignore it.
1795 // FIXME: If we want to support export, we probably need to add the
1796 // namespace of the template in a TemplateSpecializationType, or even
1797 // the classes and namespaces of known non-dependent arguments.
1798 if (!BaseType)
1799 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001800 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001801 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001802 // Find the associated namespace for this base class.
1803 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001804 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001805
1806 // Make sure we visit the bases of this base class.
1807 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1808 Bases.push_back(BaseDecl);
1809 }
1810 }
1811 }
1812}
1813
1814// \brief Add the associated classes and namespaces for
1815// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001816// (C++ [basic.lookup.koenig]p2).
1817static void
John McCallf24d7bb2010-05-28 18:45:08 +00001818addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001819 // C++ [basic.lookup.koenig]p2:
1820 //
1821 // For each argument type T in the function call, there is a set
1822 // of zero or more associated namespaces and a set of zero or more
1823 // associated classes to be considered. The sets of namespaces and
1824 // classes is determined entirely by the types of the function
1825 // arguments (and the namespace of any template template
1826 // argument). Typedef names and using-declarations used to specify
1827 // the types do not contribute to this set. The sets of namespaces
1828 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001829
John McCall0af3d3b2010-05-28 06:08:54 +00001830 llvm::SmallVector<const Type *, 16> Queue;
1831 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1832
Douglas Gregore254f902009-02-04 00:32:51 +00001833 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001834 switch (T->getTypeClass()) {
1835
1836#define TYPE(Class, Base)
1837#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1838#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1839#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1840#define ABSTRACT_TYPE(Class, Base)
1841#include "clang/AST/TypeNodes.def"
1842 // T is canonical. We can also ignore dependent types because
1843 // we don't need to do ADL at the definition point, but if we
1844 // wanted to implement template export (or if we find some other
1845 // use for associated classes and namespaces...) this would be
1846 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001847 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001848
John McCall0af3d3b2010-05-28 06:08:54 +00001849 // -- If T is a pointer to U or an array of U, its associated
1850 // namespaces and classes are those associated with U.
1851 case Type::Pointer:
1852 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1853 continue;
1854 case Type::ConstantArray:
1855 case Type::IncompleteArray:
1856 case Type::VariableArray:
1857 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1858 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001859
John McCall0af3d3b2010-05-28 06:08:54 +00001860 // -- If T is a fundamental type, its associated sets of
1861 // namespaces and classes are both empty.
1862 case Type::Builtin:
1863 break;
1864
1865 // -- If T is a class type (including unions), its associated
1866 // classes are: the class itself; the class of which it is a
1867 // member, if any; and its direct and indirect base
1868 // classes. Its associated namespaces are the namespaces in
1869 // which its associated classes are defined.
1870 case Type::Record: {
1871 CXXRecordDecl *Class
1872 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001873 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001874 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001875 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001876
John McCall0af3d3b2010-05-28 06:08:54 +00001877 // -- If T is an enumeration type, its associated namespace is
1878 // the namespace in which it is defined. If it is class
1879 // member, its associated class is the member’s class; else
1880 // it has no associated class.
1881 case Type::Enum: {
1882 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001883
John McCall0af3d3b2010-05-28 06:08:54 +00001884 DeclContext *Ctx = Enum->getDeclContext();
1885 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001886 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001887
John McCall0af3d3b2010-05-28 06:08:54 +00001888 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001889 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001890
John McCall0af3d3b2010-05-28 06:08:54 +00001891 break;
1892 }
1893
1894 // -- If T is a function type, its associated namespaces and
1895 // classes are those associated with the function parameter
1896 // types and those associated with the return type.
1897 case Type::FunctionProto: {
1898 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1899 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1900 ArgEnd = Proto->arg_type_end();
1901 Arg != ArgEnd; ++Arg)
1902 Queue.push_back(Arg->getTypePtr());
1903 // fallthrough
1904 }
1905 case Type::FunctionNoProto: {
1906 const FunctionType *FnType = cast<FunctionType>(T);
1907 T = FnType->getResultType().getTypePtr();
1908 continue;
1909 }
1910
1911 // -- If T is a pointer to a member function of a class X, its
1912 // associated namespaces and classes are those associated
1913 // with the function parameter types and return type,
1914 // together with those associated with X.
1915 //
1916 // -- If T is a pointer to a data member of class X, its
1917 // associated namespaces and classes are those associated
1918 // with the member type together with those associated with
1919 // X.
1920 case Type::MemberPointer: {
1921 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1922
1923 // Queue up the class type into which this points.
1924 Queue.push_back(MemberPtr->getClass());
1925
1926 // And directly continue with the pointee type.
1927 T = MemberPtr->getPointeeType().getTypePtr();
1928 continue;
1929 }
1930
1931 // As an extension, treat this like a normal pointer.
1932 case Type::BlockPointer:
1933 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1934 continue;
1935
1936 // References aren't covered by the standard, but that's such an
1937 // obvious defect that we cover them anyway.
1938 case Type::LValueReference:
1939 case Type::RValueReference:
1940 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1941 continue;
1942
1943 // These are fundamental types.
1944 case Type::Vector:
1945 case Type::ExtVector:
1946 case Type::Complex:
1947 break;
1948
1949 // These are ignored by ADL.
1950 case Type::ObjCObject:
1951 case Type::ObjCInterface:
1952 case Type::ObjCObjectPointer:
1953 break;
1954 }
1955
1956 if (Queue.empty()) break;
1957 T = Queue.back();
1958 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001959 }
Douglas Gregore254f902009-02-04 00:32:51 +00001960}
1961
1962/// \brief Find the associated classes and namespaces for
1963/// argument-dependent lookup for a call with the given set of
1964/// arguments.
1965///
1966/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001967/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001968/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001969void
Douglas Gregore254f902009-02-04 00:32:51 +00001970Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1971 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001972 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001973 AssociatedNamespaces.clear();
1974 AssociatedClasses.clear();
1975
John McCallf24d7bb2010-05-28 18:45:08 +00001976 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1977
Douglas Gregore254f902009-02-04 00:32:51 +00001978 // C++ [basic.lookup.koenig]p2:
1979 // For each argument type T in the function call, there is a set
1980 // of zero or more associated namespaces and a set of zero or more
1981 // associated classes to be considered. The sets of namespaces and
1982 // classes is determined entirely by the types of the function
1983 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001984 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001985 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1986 Expr *Arg = Args[ArgIdx];
1987
1988 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00001989 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001990 continue;
1991 }
1992
1993 // [...] In addition, if the argument is the name or address of a
1994 // set of overloaded functions and/or function templates, its
1995 // associated classes and namespaces are the union of those
1996 // associated with each of the members of the set: the namespace
1997 // in which the function or function template is defined and the
1998 // classes and namespaces associated with its (non-dependent)
1999 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00002000 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002001 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002002 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002003 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002004
John McCallf24d7bb2010-05-28 18:45:08 +00002005 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2006 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002007
John McCallf24d7bb2010-05-28 18:45:08 +00002008 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2009 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002010 // Look through any using declarations to find the underlying function.
2011 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002012
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002013 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2014 if (!FDecl)
2015 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002016
2017 // Add the classes and namespaces associated with the parameter
2018 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002019 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002020 }
2021 }
2022}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002023
2024/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2025/// an acceptable non-member overloaded operator for a call whose
2026/// arguments have types T1 (and, if non-empty, T2). This routine
2027/// implements the check in C++ [over.match.oper]p3b2 concerning
2028/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002029static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002030IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2031 QualType T1, QualType T2,
2032 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002033 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2034 return true;
2035
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002036 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2037 return true;
2038
John McCall9dd450b2009-09-21 23:43:11 +00002039 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002040 if (Proto->getNumArgs() < 1)
2041 return false;
2042
2043 if (T1->isEnumeralType()) {
2044 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002045 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002046 return true;
2047 }
2048
2049 if (Proto->getNumArgs() < 2)
2050 return false;
2051
2052 if (!T2.isNull() && T2->isEnumeralType()) {
2053 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002054 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002055 return true;
2056 }
2057
2058 return false;
2059}
2060
John McCall5cebab12009-11-18 07:57:50 +00002061NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002062 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002063 LookupNameKind NameKind,
2064 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002065 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002066 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002067 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002068}
2069
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002070/// \brief Find the protocol with the given name, if any.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002071ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2072 SourceLocation IdLoc) {
2073 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2074 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002075 return cast_or_null<ObjCProtocolDecl>(D);
2076}
2077
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002078void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002079 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002080 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002081 // C++ [over.match.oper]p3:
2082 // -- The set of non-member candidates is the result of the
2083 // unqualified lookup of operator@ in the context of the
2084 // expression according to the usual rules for name lookup in
2085 // unqualified function calls (3.4.2) except that all member
2086 // functions are ignored. However, if no operand has a class
2087 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002088 // that have a first parameter of type T1 or "reference to
2089 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002090 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002091 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002092 // when T2 is an enumeration type, are candidate functions.
2093 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002094 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2095 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002096
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002097 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2098
John McCall9f3059a2009-10-09 21:13:30 +00002099 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002100 return;
2101
2102 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2103 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002104 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2105 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002106 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002107 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002108 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002109 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002110 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002111 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002112 // later?
2113 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002114 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002115 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002116 }
2117}
2118
Douglas Gregor52b72822010-07-02 23:12:18 +00002119/// \brief Look up the constructors for the given class.
2120DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +00002121 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002122 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2123 if (!Class->hasDeclaredDefaultConstructor())
2124 DeclareImplicitDefaultConstructor(Class);
2125 if (!Class->hasDeclaredCopyConstructor())
2126 DeclareImplicitCopyConstructor(Class);
2127 }
Douglas Gregora6d69502010-07-02 23:41:54 +00002128
Douglas Gregor52b72822010-07-02 23:12:18 +00002129 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2130 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2131 return Class->lookup(Name);
2132}
2133
Douglas Gregore71edda2010-07-01 22:47:18 +00002134/// \brief Look for the destructor of the given class.
2135///
2136/// During semantic analysis, this routine should be used in lieu of
2137/// CXXRecordDecl::getDestructor().
2138///
2139/// \returns The destructor for this class.
2140CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +00002141 // If the destructor has not yet been declared, do so now.
2142 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2143 !Class->hasDeclaredDestructor())
2144 DeclareImplicitDestructor(Class);
2145
Douglas Gregore71edda2010-07-01 22:47:18 +00002146 return Class->getDestructor();
2147}
2148
John McCall8fe68082010-01-26 07:16:45 +00002149void ADLResult::insert(NamedDecl *New) {
2150 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2151
2152 // If we haven't yet seen a decl for this key, or the last decl
2153 // was exactly this one, we're done.
2154 if (Old == 0 || Old == New) {
2155 Old = New;
2156 return;
2157 }
2158
2159 // Otherwise, decide which is a more recent redeclaration.
2160 FunctionDecl *OldFD, *NewFD;
2161 if (isa<FunctionTemplateDecl>(New)) {
2162 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2163 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2164 } else {
2165 OldFD = cast<FunctionDecl>(Old);
2166 NewFD = cast<FunctionDecl>(New);
2167 }
2168
2169 FunctionDecl *Cursor = NewFD;
2170 while (true) {
2171 Cursor = Cursor->getPreviousDeclaration();
2172
2173 // If we got to the end without finding OldFD, OldFD is the newer
2174 // declaration; leave things as they are.
2175 if (!Cursor) return;
2176
2177 // If we do find OldFD, then NewFD is newer.
2178 if (Cursor == OldFD) break;
2179
2180 // Otherwise, keep looking.
2181 }
2182
2183 Old = New;
2184}
2185
Sebastian Redlc057f422009-10-23 19:23:15 +00002186void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002187 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00002188 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002189 // Find all of the associated namespaces and classes based on the
2190 // arguments we have.
2191 AssociatedNamespaceSet AssociatedNamespaces;
2192 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002193 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002194 AssociatedNamespaces,
2195 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002196
Sebastian Redlc057f422009-10-23 19:23:15 +00002197 QualType T1, T2;
2198 if (Operator) {
2199 T1 = Args[0]->getType();
2200 if (NumArgs >= 2)
2201 T2 = Args[1]->getType();
2202 }
2203
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002204 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002205 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2206 // and let Y be the lookup set produced by argument dependent
2207 // lookup (defined as follows). If X contains [...] then Y is
2208 // empty. Otherwise Y is the set of declarations found in the
2209 // namespaces associated with the argument types as described
2210 // below. The set of declarations found by the lookup of the name
2211 // is the union of X and Y.
2212 //
2213 // Here, we compute Y and add its members to the overloaded
2214 // candidate set.
2215 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002216 NSEnd = AssociatedNamespaces.end();
2217 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002218 // When considering an associated namespace, the lookup is the
2219 // same as the lookup performed when the associated namespace is
2220 // used as a qualifier (3.4.3.2) except that:
2221 //
2222 // -- Any using-directives in the associated namespace are
2223 // ignored.
2224 //
John McCallc7e8e792009-08-07 22:18:02 +00002225 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002226 // associated classes are visible within their respective
2227 // namespaces even if they are not visible during an ordinary
2228 // lookup (11.4).
2229 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002230 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002231 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002232 // If the only declaration here is an ordinary friend, consider
2233 // it only if it was declared in an associated classes.
2234 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002235 DeclContext *LexDC = D->getLexicalDeclContext();
2236 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2237 continue;
2238 }
Mike Stump11289f42009-09-09 15:08:12 +00002239
John McCall91f61fc2010-01-26 06:04:06 +00002240 if (isa<UsingShadowDecl>(D))
2241 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002242
John McCall91f61fc2010-01-26 06:04:06 +00002243 if (isa<FunctionDecl>(D)) {
2244 if (Operator &&
2245 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2246 T1, T2, Context))
2247 continue;
John McCall8fe68082010-01-26 07:16:45 +00002248 } else if (!isa<FunctionTemplateDecl>(D))
2249 continue;
2250
2251 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002252 }
2253 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002254}
Douglas Gregor2d435302009-12-30 17:04:44 +00002255
2256//----------------------------------------------------------------------------
2257// Search for all visible declarations.
2258//----------------------------------------------------------------------------
2259VisibleDeclConsumer::~VisibleDeclConsumer() { }
2260
2261namespace {
2262
2263class ShadowContextRAII;
2264
2265class VisibleDeclsRecord {
2266public:
2267 /// \brief An entry in the shadow map, which is optimized to store a
2268 /// single declaration (the common case) but can also store a list
2269 /// of declarations.
2270 class ShadowMapEntry {
2271 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2272
2273 /// \brief Contains either the solitary NamedDecl * or a vector
2274 /// of declarations.
2275 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2276
2277 public:
2278 ShadowMapEntry() : DeclOrVector() { }
2279
2280 void Add(NamedDecl *ND);
2281 void Destroy();
2282
2283 // Iteration.
2284 typedef NamedDecl **iterator;
2285 iterator begin();
2286 iterator end();
2287 };
2288
2289private:
2290 /// \brief A mapping from declaration names to the declarations that have
2291 /// this name within a particular scope.
2292 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2293
2294 /// \brief A list of shadow maps, which is used to model name hiding.
2295 std::list<ShadowMap> ShadowMaps;
2296
2297 /// \brief The declaration contexts we have already visited.
2298 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2299
2300 friend class ShadowContextRAII;
2301
2302public:
2303 /// \brief Determine whether we have already visited this context
2304 /// (and, if not, note that we are going to visit that context now).
2305 bool visitedContext(DeclContext *Ctx) {
2306 return !VisitedContexts.insert(Ctx);
2307 }
2308
Douglas Gregor39982192010-08-15 06:18:01 +00002309 bool alreadyVisitedContext(DeclContext *Ctx) {
2310 return VisitedContexts.count(Ctx);
2311 }
2312
Douglas Gregor2d435302009-12-30 17:04:44 +00002313 /// \brief Determine whether the given declaration is hidden in the
2314 /// current scope.
2315 ///
2316 /// \returns the declaration that hides the given declaration, or
2317 /// NULL if no such declaration exists.
2318 NamedDecl *checkHidden(NamedDecl *ND);
2319
2320 /// \brief Add a declaration to the current shadow map.
2321 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2322};
2323
2324/// \brief RAII object that records when we've entered a shadow context.
2325class ShadowContextRAII {
2326 VisibleDeclsRecord &Visible;
2327
2328 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2329
2330public:
2331 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2332 Visible.ShadowMaps.push_back(ShadowMap());
2333 }
2334
2335 ~ShadowContextRAII() {
2336 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2337 EEnd = Visible.ShadowMaps.back().end();
2338 E != EEnd;
2339 ++E)
2340 E->second.Destroy();
2341
2342 Visible.ShadowMaps.pop_back();
2343 }
2344};
2345
2346} // end anonymous namespace
2347
2348void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2349 if (DeclOrVector.isNull()) {
2350 // 0 - > 1 elements: just set the single element information.
2351 DeclOrVector = ND;
2352 return;
2353 }
2354
2355 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2356 // 1 -> 2 elements: create the vector of results and push in the
2357 // existing declaration.
2358 DeclVector *Vec = new DeclVector;
2359 Vec->push_back(PrevND);
2360 DeclOrVector = Vec;
2361 }
2362
2363 // Add the new element to the end of the vector.
2364 DeclOrVector.get<DeclVector*>()->push_back(ND);
2365}
2366
2367void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2368 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2369 delete Vec;
2370 DeclOrVector = ((NamedDecl *)0);
2371 }
2372}
2373
2374VisibleDeclsRecord::ShadowMapEntry::iterator
2375VisibleDeclsRecord::ShadowMapEntry::begin() {
2376 if (DeclOrVector.isNull())
2377 return 0;
2378
2379 if (DeclOrVector.dyn_cast<NamedDecl *>())
2380 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2381
2382 return DeclOrVector.get<DeclVector *>()->begin();
2383}
2384
2385VisibleDeclsRecord::ShadowMapEntry::iterator
2386VisibleDeclsRecord::ShadowMapEntry::end() {
2387 if (DeclOrVector.isNull())
2388 return 0;
2389
2390 if (DeclOrVector.dyn_cast<NamedDecl *>())
2391 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2392
2393 return DeclOrVector.get<DeclVector *>()->end();
2394}
2395
2396NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002397 // Look through using declarations.
2398 ND = ND->getUnderlyingDecl();
2399
Douglas Gregor2d435302009-12-30 17:04:44 +00002400 unsigned IDNS = ND->getIdentifierNamespace();
2401 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2402 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2403 SM != SMEnd; ++SM) {
2404 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2405 if (Pos == SM->end())
2406 continue;
2407
2408 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2409 IEnd = Pos->second.end();
2410 I != IEnd; ++I) {
2411 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002412 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor2d435302009-12-30 17:04:44 +00002413 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2414 Decl::IDNS_ObjCProtocol)))
2415 continue;
2416
2417 // Protocols are in distinct namespaces from everything else.
2418 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2419 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2420 (*I)->getIdentifierNamespace() != IDNS)
2421 continue;
2422
Douglas Gregor09bbc652010-01-14 15:47:35 +00002423 // Functions and function templates in the same scope overload
2424 // rather than hide. FIXME: Look for hiding based on function
2425 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002426 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002427 ND->isFunctionOrFunctionTemplate() &&
2428 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002429 continue;
2430
Douglas Gregor2d435302009-12-30 17:04:44 +00002431 // We've found a declaration that hides this one.
2432 return *I;
2433 }
2434 }
2435
2436 return 0;
2437}
2438
2439static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2440 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002441 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002442 VisibleDeclConsumer &Consumer,
2443 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002444 if (!Ctx)
2445 return;
2446
Douglas Gregor2d435302009-12-30 17:04:44 +00002447 // Make sure we don't visit the same context twice.
2448 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2449 return;
2450
Douglas Gregor7454c562010-07-02 20:37:36 +00002451 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2452 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2453
Douglas Gregor2d435302009-12-30 17:04:44 +00002454 // Enumerate all of the results in this context.
2455 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2456 CurCtx = CurCtx->getNextContext()) {
2457 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2458 DEnd = CurCtx->decls_end();
2459 D != DEnd; ++D) {
Douglas Gregora3b23b02010-12-09 21:44:02 +00002460 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002461 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002462 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002463 Visited.add(ND);
2464 }
Douglas Gregora3b23b02010-12-09 21:44:02 +00002465 } else if (ObjCForwardProtocolDecl *ForwardProto
2466 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2467 for (ObjCForwardProtocolDecl::protocol_iterator
2468 P = ForwardProto->protocol_begin(),
2469 PEnd = ForwardProto->protocol_end();
2470 P != PEnd;
2471 ++P) {
2472 if (Result.isAcceptableDecl(*P)) {
2473 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2474 Visited.add(*P);
2475 }
2476 }
2477 }
Sebastian Redlbd595762010-08-31 20:53:31 +00002478 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002479 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002480 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002481 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002482 Consumer, Visited);
2483 }
2484 }
2485 }
2486
2487 // Traverse using directives for qualified name lookup.
2488 if (QualifiedNameLookup) {
2489 ShadowContextRAII Shadow(Visited);
2490 DeclContext::udir_iterator I, E;
2491 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2492 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002493 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002494 }
2495 }
2496
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002497 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002498 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002499 if (!Record->hasDefinition())
2500 return;
2501
Douglas Gregor2d435302009-12-30 17:04:44 +00002502 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2503 BEnd = Record->bases_end();
2504 B != BEnd; ++B) {
2505 QualType BaseType = B->getType();
2506
2507 // Don't look into dependent bases, because name lookup can't look
2508 // there anyway.
2509 if (BaseType->isDependentType())
2510 continue;
2511
2512 const RecordType *Record = BaseType->getAs<RecordType>();
2513 if (!Record)
2514 continue;
2515
2516 // FIXME: It would be nice to be able to determine whether referencing
2517 // a particular member would be ambiguous. For example, given
2518 //
2519 // struct A { int member; };
2520 // struct B { int member; };
2521 // struct C : A, B { };
2522 //
2523 // void f(C *c) { c->### }
2524 //
2525 // accessing 'member' would result in an ambiguity. However, we
2526 // could be smart enough to qualify the member with the base
2527 // class, e.g.,
2528 //
2529 // c->B::member
2530 //
2531 // or
2532 //
2533 // c->A::member
2534
2535 // Find results in this base class (and its bases).
2536 ShadowContextRAII Shadow(Visited);
2537 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002538 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002539 }
2540 }
2541
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002542 // Traverse the contexts of Objective-C classes.
2543 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2544 // Traverse categories.
2545 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2546 Category; Category = Category->getNextClassCategory()) {
2547 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002548 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2549 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002550 }
2551
2552 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002553 for (ObjCInterfaceDecl::all_protocol_iterator
2554 I = IFace->all_referenced_protocol_begin(),
2555 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002556 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002557 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2558 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002559 }
2560
2561 // Traverse the superclass.
2562 if (IFace->getSuperClass()) {
2563 ShadowContextRAII Shadow(Visited);
2564 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002565 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002566 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002567
2568 // If there is an implementation, traverse it. We do this to find
2569 // synthesized ivars.
2570 if (IFace->getImplementation()) {
2571 ShadowContextRAII Shadow(Visited);
2572 LookupVisibleDecls(IFace->getImplementation(), Result,
2573 QualifiedNameLookup, true, Consumer, Visited);
2574 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002575 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2576 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2577 E = Protocol->protocol_end(); I != E; ++I) {
2578 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002579 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2580 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002581 }
2582 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2583 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2584 E = Category->protocol_end(); I != E; ++I) {
2585 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002586 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2587 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002588 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002589
2590 // If there is an implementation, traverse it.
2591 if (Category->getImplementation()) {
2592 ShadowContextRAII Shadow(Visited);
2593 LookupVisibleDecls(Category->getImplementation(), Result,
2594 QualifiedNameLookup, true, Consumer, Visited);
2595 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002596 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002597}
2598
2599static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2600 UnqualUsingDirectiveSet &UDirs,
2601 VisibleDeclConsumer &Consumer,
2602 VisibleDeclsRecord &Visited) {
2603 if (!S)
2604 return;
2605
Douglas Gregor39982192010-08-15 06:18:01 +00002606 if (!S->getEntity() ||
2607 (!S->getParent() &&
2608 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002609 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2610 // Walk through the declarations in this Scope.
2611 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2612 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002613 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002614 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002615 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002616 Visited.add(ND);
2617 }
2618 }
2619 }
2620
Douglas Gregor66230062010-03-15 14:33:29 +00002621 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002622 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002623 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002624 // Look into this scope's declaration context, along with any of its
2625 // parent lookup contexts (e.g., enclosing classes), up to the point
2626 // where we hit the context stored in the next outer scope.
2627 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002628 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor2d435302009-12-30 17:04:44 +00002629
Douglas Gregorea166062010-03-15 15:26:48 +00002630 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002631 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002632 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2633 if (Method->isInstanceMethod()) {
2634 // For instance methods, look for ivars in the method's interface.
2635 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2636 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002637 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002638 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2639 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor05fcf842010-11-02 20:36:02 +00002640
2641 // Look for properties from which we can synthesize ivars, if
2642 // permitted.
2643 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2644 IFace->getImplementation() &&
2645 Result.getLookupKind() == Sema::LookupOrdinaryName) {
2646 for (ObjCInterfaceDecl::prop_iterator
2647 P = IFace->prop_begin(),
2648 PEnd = IFace->prop_end();
2649 P != PEnd; ++P) {
2650 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2651 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2652 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2653 Visited.add(*P);
2654 }
2655 }
2656 }
2657 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002658 }
2659
2660 // We've already performed all of the name lookup that we need
2661 // to for Objective-C methods; the next context will be the
2662 // outer scope.
2663 break;
2664 }
2665
Douglas Gregor2d435302009-12-30 17:04:44 +00002666 if (Ctx->isFunctionOrMethod())
2667 continue;
2668
2669 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002670 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002671 }
2672 } else if (!S->getParent()) {
2673 // Look into the translation unit scope. We walk through the translation
2674 // unit's declaration context, because the Scope itself won't have all of
2675 // the declarations if we loaded a precompiled header.
2676 // FIXME: We would like the translation unit's Scope object to point to the
2677 // translation unit, so we don't need this special "if" branch. However,
2678 // doing so would force the normal C++ name-lookup code to look into the
2679 // translation unit decl when the IdentifierInfo chains would suffice.
2680 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002681 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002682 Entity = Result.getSema().Context.getTranslationUnitDecl();
2683 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002684 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002685 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002686
2687 if (Entity) {
2688 // Lookup visible declarations in any namespaces found by using
2689 // directives.
2690 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2691 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2692 for (; UI != UEnd; ++UI)
2693 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002694 Result, /*QualifiedNameLookup=*/false,
2695 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002696 }
2697
2698 // Lookup names in the parent scope.
2699 ShadowContextRAII Shadow(Visited);
2700 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2701}
2702
2703void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002704 VisibleDeclConsumer &Consumer,
2705 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002706 // Determine the set of using directives available during
2707 // unqualified name lookup.
2708 Scope *Initial = S;
2709 UnqualUsingDirectiveSet UDirs;
2710 if (getLangOptions().CPlusPlus) {
2711 // Find the first namespace or translation-unit scope.
2712 while (S && !isNamespaceOrTranslationUnitScope(S))
2713 S = S->getParent();
2714
2715 UDirs.visitScopeChain(Initial, S);
2716 }
2717 UDirs.done();
2718
2719 // Look for visible declarations.
2720 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2721 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002722 if (!IncludeGlobalScope)
2723 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002724 ShadowContextRAII Shadow(Visited);
2725 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2726}
2727
2728void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002729 VisibleDeclConsumer &Consumer,
2730 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002731 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2732 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002733 if (!IncludeGlobalScope)
2734 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002735 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002736 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2737 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002738}
2739
2740//----------------------------------------------------------------------------
2741// Typo correction
2742//----------------------------------------------------------------------------
2743
2744namespace {
2745class TypoCorrectionConsumer : public VisibleDeclConsumer {
2746 /// \brief The name written that is a typo in the source.
2747 llvm::StringRef Typo;
2748
2749 /// \brief The results found that have the smallest edit distance
2750 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002751 ///
2752 /// The boolean value indicates whether there is a keyword with this name.
2753 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00002754
2755 /// \brief The best edit distance found so far.
2756 unsigned BestEditDistance;
2757
2758public:
2759 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002760 : Typo(Typo->getName()),
2761 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00002762
Douglas Gregor09bbc652010-01-14 15:47:35 +00002763 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor57756ea2010-10-14 22:11:03 +00002764 void FoundName(llvm::StringRef Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002765 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002766
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002767 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2768 iterator begin() { return BestResults.begin(); }
2769 iterator end() { return BestResults.end(); }
2770 void erase(iterator I) { BestResults.erase(I); }
2771 unsigned size() const { return BestResults.size(); }
2772 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002773
Douglas Gregoraf9eb592010-10-15 13:35:25 +00002774 bool &operator[](llvm::StringRef Name) {
2775 return BestResults[Name];
2776 }
2777
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002778 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002779};
2780
2781}
2782
Douglas Gregor09bbc652010-01-14 15:47:35 +00002783void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2784 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002785 // Don't consider hidden names for typo correction.
2786 if (Hiding)
2787 return;
2788
2789 // Only consider entities with identifiers for names, ignoring
2790 // special names (constructors, overloaded operators, selectors,
2791 // etc.).
2792 IdentifierInfo *Name = ND->getIdentifier();
2793 if (!Name)
2794 return;
2795
Douglas Gregor57756ea2010-10-14 22:11:03 +00002796 FoundName(Name->getName());
2797}
2798
2799void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002800 using namespace std;
2801
Douglas Gregor93910a52010-10-19 19:39:10 +00002802 // Use a simple length-based heuristic to determine the minimum possible
2803 // edit distance. If the minimum isn't good enough, bail out early.
2804 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
2805 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
2806 return;
2807
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002808 // Compute an upper bound on the allowable edit distance, so that the
2809 // edit-distance algorithm can short-circuit.
2810 unsigned UpperBound = min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
2811
Douglas Gregor2d435302009-12-30 17:04:44 +00002812 // Compute the edit distance between the typo and the name of this
2813 // entity. If this edit distance is not worse than the best edit
2814 // distance we've seen so far, add it to the list of results.
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002815 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
Douglas Gregor57756ea2010-10-14 22:11:03 +00002816 if (ED == 0)
2817 return;
2818
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002819 if (ED < BestEditDistance) {
2820 // This result is better than any we've seen before; clear out
2821 // the previous results.
2822 BestResults.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002823 BestEditDistance = ED;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002824 } else if (ED > BestEditDistance) {
2825 // This result is worse than the best results we've seen so far;
2826 // ignore it.
2827 return;
2828 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00002829
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002830 // Add this name to the list of results. By not assigning a value, we
2831 // keep the current value if we've seen this name before (either as a
2832 // keyword or as a declaration), or get the default value (not a keyword)
2833 // if we haven't seen it before.
Douglas Gregor57756ea2010-10-14 22:11:03 +00002834 (void)BestResults[Name];
Douglas Gregor2d435302009-12-30 17:04:44 +00002835}
2836
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002837void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2838 llvm::StringRef Keyword) {
2839 // Compute the edit distance between the typo and this keyword.
2840 // If this edit distance is not worse than the best edit
2841 // distance we've seen so far, add it to the list of results.
2842 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002843 if (ED < BestEditDistance) {
2844 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002845 BestEditDistance = ED;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002846 } else if (ED > BestEditDistance) {
2847 // This result is worse than the best results we've seen so far;
2848 // ignore it.
2849 return;
2850 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002851
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002852 BestResults[Keyword] = true;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002853}
2854
Douglas Gregord507d772010-10-20 03:06:34 +00002855/// \brief Perform name lookup for a possible result for typo correction.
2856static void LookupPotentialTypoResult(Sema &SemaRef,
2857 LookupResult &Res,
2858 IdentifierInfo *Name,
2859 Scope *S, CXXScopeSpec *SS,
2860 DeclContext *MemberContext,
2861 bool EnteringContext,
2862 Sema::CorrectTypoContext CTC) {
2863 Res.suppressDiagnostics();
2864 Res.clear();
2865 Res.setLookupName(Name);
2866 if (MemberContext) {
2867 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
2868 if (CTC == Sema::CTC_ObjCIvarLookup) {
2869 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
2870 Res.addDecl(Ivar);
2871 Res.resolveKind();
2872 return;
2873 }
2874 }
2875
2876 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
2877 Res.addDecl(Prop);
2878 Res.resolveKind();
2879 return;
2880 }
2881 }
2882
2883 SemaRef.LookupQualifiedName(Res, MemberContext);
2884 return;
2885 }
2886
2887 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2888 EnteringContext);
2889
2890 // Fake ivar lookup; this should really be part of
2891 // LookupParsedName.
2892 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2893 if (Method->isInstanceMethod() && Method->getClassInterface() &&
2894 (Res.empty() ||
2895 (Res.isSingleResult() &&
2896 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
2897 if (ObjCIvarDecl *IV
2898 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
2899 Res.addDecl(IV);
2900 Res.resolveKind();
2901 }
2902 }
2903 }
2904}
2905
Douglas Gregor2d435302009-12-30 17:04:44 +00002906/// \brief Try to "correct" a typo in the source code by finding
2907/// visible declarations whose names are similar to the name that was
2908/// present in the source code.
2909///
2910/// \param Res the \c LookupResult structure that contains the name
2911/// that was present in the source code along with the name-lookup
2912/// criteria used to search for the name. On success, this structure
2913/// will contain the results of name lookup.
2914///
2915/// \param S the scope in which name lookup occurs.
2916///
2917/// \param SS the nested-name-specifier that precedes the name we're
2918/// looking for, if present.
2919///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002920/// \param MemberContext if non-NULL, the context in which to look for
2921/// a member access expression.
2922///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002923/// \param EnteringContext whether we're entering the context described by
2924/// the nested-name-specifier SS.
2925///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002926/// \param CTC The context in which typo correction occurs, which impacts the
2927/// set of keywords permitted.
2928///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002929/// \param OPT when non-NULL, the search for visible declarations will
2930/// also walk the protocols in the qualified interfaces of \p OPT.
2931///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002932/// \returns the corrected name if the typo was corrected, otherwise returns an
2933/// empty \c DeclarationName. When a typo was corrected, the result structure
2934/// may contain the results of name lookup for the correct name or it may be
2935/// empty.
2936DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002937 DeclContext *MemberContext,
2938 bool EnteringContext,
2939 CorrectTypoContext CTC,
2940 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00002941 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002942 return DeclarationName();
Ted Kremeneke51136e2010-01-06 00:23:04 +00002943
Douglas Gregor2d435302009-12-30 17:04:44 +00002944 // We only attempt to correct typos for identifiers.
2945 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2946 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002947 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002948
2949 // If the scope specifier itself was invalid, don't try to correct
2950 // typos.
2951 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002952 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002953
2954 // Never try to correct typos during template deduction or
2955 // instantiation.
2956 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002957 return DeclarationName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002958
Douglas Gregor2d435302009-12-30 17:04:44 +00002959 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002960
2961 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00002962 bool IsUnqualifiedLookup = false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002963 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002964 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002965
2966 // Look in qualified interfaces.
2967 if (OPT) {
2968 for (ObjCObjectPointerType::qual_iterator
2969 I = OPT->qual_begin(), E = OPT->qual_end();
2970 I != E; ++I)
2971 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2972 }
2973 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002974 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2975 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002976 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002977
Douglas Gregor87074f12010-10-20 01:32:02 +00002978 // Provide a stop gap for files that are just seriously broken. Trying
2979 // to correct all typos can turn into a HUGE performance penalty, causing
2980 // some files to take minutes to get rejected by the parser.
2981 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
2982 return DeclarationName();
2983 ++TyposCorrected;
2984
Douglas Gregor2d435302009-12-30 17:04:44 +00002985 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2986 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00002987 IsUnqualifiedLookup = true;
2988 UnqualifiedTyposCorrectedMap::iterator Cached
2989 = UnqualifiedTyposCorrected.find(Typo);
2990 if (Cached == UnqualifiedTyposCorrected.end()) {
2991 // Provide a stop gap for files that are just seriously broken. Trying
2992 // to correct all typos can turn into a HUGE performance penalty, causing
2993 // some files to take minutes to get rejected by the parser.
2994 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
2995 return DeclarationName();
2996
2997 // For unqualified lookup, look through all of the names that we have
2998 // seen in this translation unit.
2999 for (IdentifierTable::iterator I = Context.Idents.begin(),
3000 IEnd = Context.Idents.end();
3001 I != IEnd; ++I)
3002 Consumer.FoundName(I->getKey());
3003
3004 // Walk through identifiers in external identifier sources.
3005 if (IdentifierInfoLookup *External
Douglas Gregor57756ea2010-10-14 22:11:03 +00003006 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenekb4ea9a82010-11-07 06:11:33 +00003007 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor87074f12010-10-20 01:32:02 +00003008 do {
3009 llvm::StringRef Name = Iter->Next();
3010 if (Name.empty())
3011 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00003012
Douglas Gregor87074f12010-10-20 01:32:02 +00003013 Consumer.FoundName(Name);
3014 } while (true);
3015 }
3016 } else {
3017 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3018 // end up adding the keyword below.
3019 if (Cached->second.first.empty())
3020 return DeclarationName();
3021
3022 if (!Cached->second.second)
3023 Consumer.FoundName(Cached->second.first);
Douglas Gregor57756ea2010-10-14 22:11:03 +00003024 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003025 }
3026
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003027 // Add context-dependent keywords.
3028 bool WantTypeSpecifiers = false;
3029 bool WantExpressionKeywords = false;
3030 bool WantCXXNamedCasts = false;
3031 bool WantRemainingKeywords = false;
3032 switch (CTC) {
3033 case CTC_Unknown:
3034 WantTypeSpecifiers = true;
3035 WantExpressionKeywords = true;
3036 WantCXXNamedCasts = true;
3037 WantRemainingKeywords = true;
Douglas Gregor5fd04d42010-05-18 16:14:23 +00003038
3039 if (ObjCMethodDecl *Method = getCurMethodDecl())
3040 if (Method->getClassInterface() &&
3041 Method->getClassInterface()->getSuperClass())
3042 Consumer.addKeywordResult(Context, "super");
3043
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003044 break;
3045
3046 case CTC_NoKeywords:
3047 break;
3048
3049 case CTC_Type:
3050 WantTypeSpecifiers = true;
3051 break;
3052
3053 case CTC_ObjCMessageReceiver:
3054 Consumer.addKeywordResult(Context, "super");
3055 // Fall through to handle message receivers like expressions.
3056
3057 case CTC_Expression:
3058 if (getLangOptions().CPlusPlus)
3059 WantTypeSpecifiers = true;
3060 WantExpressionKeywords = true;
3061 // Fall through to get C++ named casts.
3062
3063 case CTC_CXXCasts:
3064 WantCXXNamedCasts = true;
3065 break;
3066
Douglas Gregord507d772010-10-20 03:06:34 +00003067 case CTC_ObjCPropertyLookup:
3068 // FIXME: Add "isa"?
3069 break;
3070
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003071 case CTC_MemberLookup:
3072 if (getLangOptions().CPlusPlus)
3073 Consumer.addKeywordResult(Context, "template");
3074 break;
Douglas Gregord507d772010-10-20 03:06:34 +00003075
3076 case CTC_ObjCIvarLookup:
3077 break;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003078 }
3079
3080 if (WantTypeSpecifiers) {
3081 // Add type-specifier keywords to the set of results.
3082 const char *CTypeSpecs[] = {
3083 "char", "const", "double", "enum", "float", "int", "long", "short",
3084 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3085 "_Complex", "_Imaginary",
3086 // storage-specifiers as well
3087 "extern", "inline", "static", "typedef"
3088 };
3089
3090 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3091 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3092 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
3093
3094 if (getLangOptions().C99)
3095 Consumer.addKeywordResult(Context, "restrict");
3096 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3097 Consumer.addKeywordResult(Context, "bool");
3098
3099 if (getLangOptions().CPlusPlus) {
3100 Consumer.addKeywordResult(Context, "class");
3101 Consumer.addKeywordResult(Context, "typename");
3102 Consumer.addKeywordResult(Context, "wchar_t");
3103
3104 if (getLangOptions().CPlusPlus0x) {
3105 Consumer.addKeywordResult(Context, "char16_t");
3106 Consumer.addKeywordResult(Context, "char32_t");
3107 Consumer.addKeywordResult(Context, "constexpr");
3108 Consumer.addKeywordResult(Context, "decltype");
3109 Consumer.addKeywordResult(Context, "thread_local");
3110 }
3111 }
3112
3113 if (getLangOptions().GNUMode)
3114 Consumer.addKeywordResult(Context, "typeof");
3115 }
3116
Douglas Gregor86ad0852010-05-18 16:30:22 +00003117 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003118 Consumer.addKeywordResult(Context, "const_cast");
3119 Consumer.addKeywordResult(Context, "dynamic_cast");
3120 Consumer.addKeywordResult(Context, "reinterpret_cast");
3121 Consumer.addKeywordResult(Context, "static_cast");
3122 }
3123
3124 if (WantExpressionKeywords) {
3125 Consumer.addKeywordResult(Context, "sizeof");
3126 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3127 Consumer.addKeywordResult(Context, "false");
3128 Consumer.addKeywordResult(Context, "true");
3129 }
3130
3131 if (getLangOptions().CPlusPlus) {
3132 const char *CXXExprs[] = {
3133 "delete", "new", "operator", "throw", "typeid"
3134 };
3135 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3136 for (unsigned I = 0; I != NumCXXExprs; ++I)
3137 Consumer.addKeywordResult(Context, CXXExprs[I]);
3138
3139 if (isa<CXXMethodDecl>(CurContext) &&
3140 cast<CXXMethodDecl>(CurContext)->isInstance())
3141 Consumer.addKeywordResult(Context, "this");
3142
3143 if (getLangOptions().CPlusPlus0x) {
3144 Consumer.addKeywordResult(Context, "alignof");
3145 Consumer.addKeywordResult(Context, "nullptr");
3146 }
3147 }
3148 }
3149
3150 if (WantRemainingKeywords) {
3151 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3152 // Statements.
3153 const char *CStmts[] = {
3154 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3155 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3156 for (unsigned I = 0; I != NumCStmts; ++I)
3157 Consumer.addKeywordResult(Context, CStmts[I]);
3158
3159 if (getLangOptions().CPlusPlus) {
3160 Consumer.addKeywordResult(Context, "catch");
3161 Consumer.addKeywordResult(Context, "try");
3162 }
3163
3164 if (S && S->getBreakParent())
3165 Consumer.addKeywordResult(Context, "break");
3166
3167 if (S && S->getContinueParent())
3168 Consumer.addKeywordResult(Context, "continue");
3169
John McCallaab3e412010-08-25 08:40:02 +00003170 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003171 Consumer.addKeywordResult(Context, "case");
3172 Consumer.addKeywordResult(Context, "default");
3173 }
3174 } else {
3175 if (getLangOptions().CPlusPlus) {
3176 Consumer.addKeywordResult(Context, "namespace");
3177 Consumer.addKeywordResult(Context, "template");
3178 }
3179
3180 if (S && S->isClassScope()) {
3181 Consumer.addKeywordResult(Context, "explicit");
3182 Consumer.addKeywordResult(Context, "friend");
3183 Consumer.addKeywordResult(Context, "mutable");
3184 Consumer.addKeywordResult(Context, "private");
3185 Consumer.addKeywordResult(Context, "protected");
3186 Consumer.addKeywordResult(Context, "public");
3187 Consumer.addKeywordResult(Context, "virtual");
3188 }
3189 }
3190
3191 if (getLangOptions().CPlusPlus) {
3192 Consumer.addKeywordResult(Context, "using");
3193
3194 if (getLangOptions().CPlusPlus0x)
3195 Consumer.addKeywordResult(Context, "static_assert");
3196 }
3197 }
3198
3199 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003200 if (Consumer.empty()) {
3201 // If this was an unqualified lookup, note that no correction was found.
3202 if (IsUnqualifiedLookup)
3203 (void)UnqualifiedTyposCorrected[Typo];
3204
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003205 return DeclarationName();
Douglas Gregor87074f12010-10-20 01:32:02 +00003206 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003207
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003208 // Make sure that the user typed at least 3 characters for each correction
3209 // made. Otherwise, we don't even both looking at the results.
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003210
3211 // We also suppress exact matches; those should be handled by a
3212 // different mechanism (e.g., one that introduces qualification in
3213 // C++).
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003214 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor87074f12010-10-20 01:32:02 +00003215 if (ED > 0 && Typo->getName().size() / ED < 3) {
3216 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregoraf1daa92010-10-27 14:20:34 +00003217 if (IsUnqualifiedLookup)
Douglas Gregor87074f12010-10-20 01:32:02 +00003218 (void)UnqualifiedTyposCorrected[Typo];
3219
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003220 return DeclarationName();
Douglas Gregor87074f12010-10-20 01:32:02 +00003221 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003222
3223 // Weed out any names that could not be found by name lookup.
Douglas Gregor26c55782010-10-15 16:49:56 +00003224 bool LastLookupWasAccepted = false;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003225 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3226 IEnd = Consumer.end();
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003227 I != IEnd; /* Increment in loop. */) {
3228 // Keywords are always found.
3229 if (I->second) {
3230 ++I;
3231 continue;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003232 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003233
3234 // Perform name lookup on this name.
3235 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
Douglas Gregord507d772010-10-20 03:06:34 +00003236 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3237 EnteringContext, CTC);
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003238
3239 switch (Res.getResultKind()) {
3240 case LookupResult::NotFound:
3241 case LookupResult::NotFoundInCurrentInstantiation:
3242 case LookupResult::Ambiguous:
3243 // We didn't find this name in our scope, or didn't like what we found;
3244 // ignore it.
3245 Res.suppressDiagnostics();
3246 {
3247 TypoCorrectionConsumer::iterator Next = I;
3248 ++Next;
3249 Consumer.erase(I);
3250 I = Next;
3251 }
Douglas Gregor26c55782010-10-15 16:49:56 +00003252 LastLookupWasAccepted = false;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003253 break;
3254
3255 case LookupResult::Found:
3256 case LookupResult::FoundOverloaded:
3257 case LookupResult::FoundUnresolvedValue:
3258 ++I;
Douglas Gregord507d772010-10-20 03:06:34 +00003259 LastLookupWasAccepted = true;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003260 break;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003261 }
3262
3263 if (Res.isAmbiguous()) {
3264 // We don't deal with ambiguities.
3265 Res.suppressDiagnostics();
3266 Res.clear();
3267 return DeclarationName();
3268 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003269 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003270
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003271 // If only a single name remains, return that result.
Douglas Gregor26c55782010-10-15 16:49:56 +00003272 if (Consumer.size() == 1) {
3273 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor1f32ebe2010-10-20 01:01:57 +00003274 if (Consumer.begin()->second) {
3275 Res.suppressDiagnostics();
3276 Res.clear();
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003277
3278 // Don't correct to a keyword that's the same as the typo; the keyword
3279 // wasn't actually in scope.
3280 if (ED == 0) {
3281 Res.setLookupName(Typo);
3282 return DeclarationName();
3283 }
3284
Douglas Gregor1f32ebe2010-10-20 01:01:57 +00003285 } else if (!LastLookupWasAccepted) {
Douglas Gregor26c55782010-10-15 16:49:56 +00003286 // Perform name lookup on this name.
Douglas Gregord507d772010-10-20 03:06:34 +00003287 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3288 EnteringContext, CTC);
Douglas Gregor26c55782010-10-15 16:49:56 +00003289 }
3290
Douglas Gregor87074f12010-10-20 01:32:02 +00003291 // Record the correction for unqualified lookup.
3292 if (IsUnqualifiedLookup)
3293 UnqualifiedTyposCorrected[Typo]
Douglas Gregord507d772010-10-20 03:06:34 +00003294 = std::make_pair(Name->getName(), Consumer.begin()->second);
Douglas Gregor87074f12010-10-20 01:32:02 +00003295
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003296 return &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor26c55782010-10-15 16:49:56 +00003297 }
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003298 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
3299 && Consumer["super"]) {
3300 // Prefix 'super' when we're completing in a message-receiver
3301 // context.
3302 Res.suppressDiagnostics();
3303 Res.clear();
Douglas Gregor87074f12010-10-20 01:32:02 +00003304
Douglas Gregor2a1d72d2010-10-26 17:18:00 +00003305 // Don't correct to a keyword that's the same as the typo; the keyword
3306 // wasn't actually in scope.
3307 if (ED == 0) {
3308 Res.setLookupName(Typo);
3309 return DeclarationName();
3310 }
3311
Douglas Gregor87074f12010-10-20 01:32:02 +00003312 // Record the correction for unqualified lookup.
3313 if (IsUnqualifiedLookup)
3314 UnqualifiedTyposCorrected[Typo]
Douglas Gregord507d772010-10-20 03:06:34 +00003315 = std::make_pair("super", Consumer.begin()->second);
Douglas Gregor87074f12010-10-20 01:32:02 +00003316
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003317 return &Context.Idents.get("super");
3318 }
3319
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003320 Res.suppressDiagnostics();
3321 Res.setLookupName(Typo);
Douglas Gregor2d435302009-12-30 17:04:44 +00003322 Res.clear();
Douglas Gregor87074f12010-10-20 01:32:02 +00003323 // Record the correction for unqualified lookup.
3324 if (IsUnqualifiedLookup)
3325 (void)UnqualifiedTyposCorrected[Typo];
3326
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003327 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003328}