blob: cc27e35bb089d233bb5fc6743e9d644e14509bec [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 +0000295#ifndef NDEBUG
296void LookupResult::sanity() const {
297 assert(ResultKind != NotFound || Decls.size() == 0);
298 assert(ResultKind != Found || Decls.size() == 1);
299 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
300 (Decls.size() == 1 &&
301 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
302 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
303 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorc0d24902010-10-22 22:08:47 +0000304 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
305 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall19c1bfd2010-08-25 05:32:35 +0000306 assert((Paths != NULL) == (ResultKind == Ambiguous &&
307 (Ambiguity == AmbiguousBaseSubobjectTypes ||
308 Ambiguity == AmbiguousBaseSubobjects)));
309}
310#endif
311
John McCall9f3059a2009-10-09 21:13:30 +0000312// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000313void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000314 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000315}
316
John McCall283b9012009-11-22 00:44:51 +0000317/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000318void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000319 unsigned N = Decls.size();
John McCall84d87672009-12-10 09:41:52 +0000320
John McCall9f3059a2009-10-09 21:13:30 +0000321 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000322 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000323 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000324 return;
325 }
326
John McCall283b9012009-11-22 00:44:51 +0000327 // If there's a single decl, we need to examine it to decide what
328 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000329 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000330 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
331 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000332 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000333 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000334 ResultKind = FoundUnresolvedValue;
335 return;
336 }
John McCall9f3059a2009-10-09 21:13:30 +0000337
John McCall6538c932009-10-10 05:48:19 +0000338 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000339 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000340
John McCall9f3059a2009-10-09 21:13:30 +0000341 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000342 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
343
John McCall9f3059a2009-10-09 21:13:30 +0000344 bool Ambiguous = false;
345 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000346 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000347
348 unsigned UniqueTagIndex = 0;
349
350 unsigned I = 0;
351 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000352 NamedDecl *D = Decls[I]->getUnderlyingDecl();
353 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000354
Douglas Gregor13e65872010-08-11 14:45:53 +0000355 // Redeclarations of types via typedef can occur both within a scope
356 // and, through using declarations and directives, across scopes. There is
357 // no ambiguity if they all refer to the same type, so unique based on the
358 // canonical type.
359 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
360 if (!TD->getDeclContext()->isRecord()) {
361 QualType T = SemaRef.Context.getTypeDeclType(TD);
362 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
363 // The type is not unique; pull something off the back and continue
364 // at this index.
365 Decls[I] = Decls[--N];
366 continue;
367 }
368 }
369 }
370
John McCallf0f1cf02009-11-17 07:50:12 +0000371 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000372 // If it's not unique, pull something off the back (and
373 // continue at this index).
374 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000375 continue;
376 }
377
378 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000379
Douglas Gregor13e65872010-08-11 14:45:53 +0000380 if (isa<UnresolvedUsingValueDecl>(D)) {
381 HasUnresolved = true;
382 } else if (isa<TagDecl>(D)) {
383 if (HasTag)
384 Ambiguous = true;
385 UniqueTagIndex = I;
386 HasTag = true;
387 } else if (isa<FunctionTemplateDecl>(D)) {
388 HasFunction = true;
389 HasFunctionTemplate = true;
390 } else if (isa<FunctionDecl>(D)) {
391 HasFunction = true;
392 } else {
393 if (HasNonFunction)
394 Ambiguous = true;
395 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000396 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000397 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000398 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000399
John McCall9f3059a2009-10-09 21:13:30 +0000400 // C++ [basic.scope.hiding]p2:
401 // A class name or enumeration name can be hidden by the name of
402 // an object, function, or enumerator declared in the same
403 // scope. If a class or enumeration name and an object, function,
404 // or enumerator are declared in the same scope (in any order)
405 // with the same name, the class or enumeration name is hidden
406 // wherever the object, function, or enumerator name is visible.
407 // But it's still an error if there are distinct tag types found,
408 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000409 if (HideTags && HasTag && !Ambiguous &&
410 (HasFunction || HasNonFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000411 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000412
John McCall9f3059a2009-10-09 21:13:30 +0000413 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000414
John McCall80053822009-12-03 00:58:24 +0000415 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000416 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000417
John McCall9f3059a2009-10-09 21:13:30 +0000418 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000419 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000420 else if (HasUnresolved)
421 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000422 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000423 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000424 else
John McCall27b18f82009-11-17 02:14:36 +0000425 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000426}
427
John McCall5cebab12009-11-18 07:57:50 +0000428void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000429 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000430 DeclContext::lookup_iterator DI, DE;
431 for (I = P.begin(), E = P.end(); I != E; ++I)
432 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
433 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000434}
435
John McCall5cebab12009-11-18 07:57:50 +0000436void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000437 Paths = new CXXBasePaths;
438 Paths->swap(P);
439 addDeclsFromBasePaths(*Paths);
440 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000441 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000442}
443
John McCall5cebab12009-11-18 07:57:50 +0000444void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000445 Paths = new CXXBasePaths;
446 Paths->swap(P);
447 addDeclsFromBasePaths(*Paths);
448 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000449 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000450}
451
John McCall5cebab12009-11-18 07:57:50 +0000452void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000453 Out << Decls.size() << " result(s)";
454 if (isAmbiguous()) Out << ", ambiguous";
455 if (Paths) Out << ", base paths present";
456
457 for (iterator I = begin(), E = end(); I != E; ++I) {
458 Out << "\n";
459 (*I)->print(Out, 2);
460 }
461}
462
Douglas Gregord3a59182010-02-12 05:48:04 +0000463/// \brief Lookup a builtin function, when name lookup would otherwise
464/// fail.
465static bool LookupBuiltin(Sema &S, LookupResult &R) {
466 Sema::LookupNameKind NameKind = R.getLookupKind();
467
468 // If we didn't find a use of this identifier, and if the identifier
469 // corresponds to a compiler builtin, create the decl object for the builtin
470 // now, injecting it into translation unit scope, and return it.
471 if (NameKind == Sema::LookupOrdinaryName ||
472 NameKind == Sema::LookupRedeclarationWithLinkage) {
473 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
474 if (II) {
475 // If this is a builtin on this (or all) targets, create the decl.
476 if (unsigned BuiltinID = II->getBuiltinID()) {
477 // In C++, we don't have any predefined library functions like
478 // 'malloc'. Instead, we'll just error.
479 if (S.getLangOptions().CPlusPlus &&
480 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
481 return false;
482
483 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
484 S.TUScope, R.isForRedeclaration(),
485 R.getNameLoc());
486 if (D)
487 R.addDecl(D);
488 return (D != NULL);
489 }
490 }
491 }
492
493 return false;
494}
495
Douglas Gregor7454c562010-07-02 20:37:36 +0000496/// \brief Determine whether we can declare a special member function within
497/// the class at this point.
498static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
499 const CXXRecordDecl *Class) {
John McCall2ded5d22010-08-11 23:52:36 +0000500 // Don't do it if the class is invalid.
501 if (Class->isInvalidDecl())
502 return false;
503
Douglas Gregor7454c562010-07-02 20:37:36 +0000504 // We need to have a definition for the class.
505 if (!Class->getDefinition() || Class->isDependentContext())
506 return false;
507
508 // We can't be in the middle of defining the class.
509 if (const RecordType *RecordTy
510 = Context.getTypeDeclType(Class)->getAs<RecordType>())
511 return !RecordTy->isBeingDefined();
512
513 return false;
514}
515
516void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000517 if (!CanDeclareSpecialMemberFunction(Context, Class))
518 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000519
520 // If the default constructor has not yet been declared, do so now.
521 if (!Class->hasDeclaredDefaultConstructor())
522 DeclareImplicitDefaultConstructor(Class);
Douglas Gregora6d69502010-07-02 23:41:54 +0000523
524 // If the copy constructor has not yet been declared, do so now.
525 if (!Class->hasDeclaredCopyConstructor())
526 DeclareImplicitCopyConstructor(Class);
527
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000528 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000529 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000530 DeclareImplicitCopyAssignment(Class);
531
Douglas Gregor7454c562010-07-02 20:37:36 +0000532 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000533 if (!Class->hasDeclaredDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +0000534 DeclareImplicitDestructor(Class);
535}
536
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000537/// \brief Determine whether this is the name of an implicitly-declared
538/// special member function.
539static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
540 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000541 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000542 case DeclarationName::CXXDestructorName:
543 return true;
544
545 case DeclarationName::CXXOperatorName:
546 return Name.getCXXOverloadedOperator() == OO_Equal;
547
548 default:
549 break;
550 }
551
552 return false;
553}
554
555/// \brief If there are any implicit member functions with the given name
556/// that need to be declared in the given declaration context, do so.
557static void DeclareImplicitMemberFunctionsWithName(Sema &S,
558 DeclarationName Name,
559 const DeclContext *DC) {
560 if (!DC)
561 return;
562
563 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000564 case DeclarationName::CXXConstructorName:
565 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000566 if (Record->getDefinition() &&
567 CanDeclareSpecialMemberFunction(S.Context, Record)) {
568 if (!Record->hasDeclaredDefaultConstructor())
569 S.DeclareImplicitDefaultConstructor(
570 const_cast<CXXRecordDecl *>(Record));
571 if (!Record->hasDeclaredCopyConstructor())
572 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
573 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000574 break;
575
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000576 case DeclarationName::CXXDestructorName:
577 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
578 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
579 CanDeclareSpecialMemberFunction(S.Context, Record))
580 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000581 break;
582
583 case DeclarationName::CXXOperatorName:
584 if (Name.getCXXOverloadedOperator() != OO_Equal)
585 break;
586
587 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
588 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
589 CanDeclareSpecialMemberFunction(S.Context, Record))
590 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
591 break;
592
593 default:
594 break;
595 }
596}
Douglas Gregor7454c562010-07-02 20:37:36 +0000597
John McCall9f3059a2009-10-09 21:13:30 +0000598// Adds all qualifying matches for a name within a decl context to the
599// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000600static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000601 bool Found = false;
602
Douglas Gregor7454c562010-07-02 20:37:36 +0000603 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000604 if (S.getLangOptions().CPlusPlus)
605 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor7454c562010-07-02 20:37:36 +0000606
607 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000608 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000609 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000610 NamedDecl *D = *I;
611 if (R.isAcceptableDecl(D)) {
612 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000613 Found = true;
614 }
615 }
John McCall9f3059a2009-10-09 21:13:30 +0000616
Douglas Gregord3a59182010-02-12 05:48:04 +0000617 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
618 return true;
619
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000620 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000621 != DeclarationName::CXXConversionFunctionName ||
622 R.getLookupName().getCXXNameType()->isDependentType() ||
623 !isa<CXXRecordDecl>(DC))
624 return Found;
625
626 // C++ [temp.mem]p6:
627 // A specialization of a conversion function template is not found by
628 // name lookup. Instead, any conversion function templates visible in the
629 // context of the use are considered. [...]
630 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
631 if (!Record->isDefinition())
632 return Found;
633
634 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
635 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
636 UEnd = Unresolved->end(); U != UEnd; ++U) {
637 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
638 if (!ConvTemplate)
639 continue;
640
641 // When we're performing lookup for the purposes of redeclaration, just
642 // add the conversion function template. When we deduce template
643 // arguments for specializations, we'll end up unifying the return
644 // type of the new declaration with the type of the function template.
645 if (R.isForRedeclaration()) {
646 R.addDecl(ConvTemplate);
647 Found = true;
648 continue;
649 }
650
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000651 // C++ [temp.mem]p6:
Chandler Carruth3a693b72010-01-31 11:44:02 +0000652 // [...] For each such operator, if argument deduction succeeds
653 // (14.9.2.3), the resulting specialization is used as if found by
654 // name lookup.
655 //
656 // When referencing a conversion function for any purpose other than
657 // a redeclaration (such that we'll be building an expression with the
658 // result), perform template argument deduction and place the
659 // specialization into the result set. We do this to avoid forcing all
660 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000661 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000662 FunctionDecl *Specialization = 0;
663
664 const FunctionProtoType *ConvProto
665 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
666 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000667
Chandler Carruth3a693b72010-01-31 11:44:02 +0000668 // Compute the type of the function that we would expect the conversion
669 // function to have, if it were to match the name given.
670 // FIXME: Calling convention!
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000671 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruth3a693b72010-01-31 11:44:02 +0000672 QualType ExpectedType
673 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
674 0, 0, ConvProto->isVariadic(),
675 ConvProto->getTypeQuals(),
676 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000677 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruth3a693b72010-01-31 11:44:02 +0000678
679 // Perform template argument deduction against the type that we would
680 // expect the function to have.
681 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
682 Specialization, Info)
683 == Sema::TDK_Success) {
684 R.addDecl(Specialization);
685 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000686 }
687 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000688
John McCall9f3059a2009-10-09 21:13:30 +0000689 return Found;
690}
691
John McCallf6c8a4e2009-11-10 07:01:13 +0000692// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000693static bool
Douglas Gregord3a59182010-02-12 05:48:04 +0000694CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
695 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000696
697 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
698
John McCallf6c8a4e2009-11-10 07:01:13 +0000699 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000700 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000701
John McCallf6c8a4e2009-11-10 07:01:13 +0000702 // Perform direct name lookup into the namespaces nominated by the
703 // using directives whose common ancestor is this namespace.
704 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
705 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000706
John McCallf6c8a4e2009-11-10 07:01:13 +0000707 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000708 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000709 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000710
711 R.resolveKind();
712
713 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000714}
715
716static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000717 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000718 return Ctx->isFileContext();
719 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000720}
Douglas Gregored8f2882009-01-30 01:04:22 +0000721
Douglas Gregor66230062010-03-15 14:33:29 +0000722// Find the next outer declaration context from this scope. This
723// routine actually returns the semantic outer context, which may
724// differ from the lexical context (encoded directly in the Scope
725// stack) when we are parsing a member of a class template. In this
726// case, the second element of the pair will be true, to indicate that
727// name lookup should continue searching in this semantic context when
728// it leaves the current template parameter scope.
729static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
730 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
731 DeclContext *Lexical = 0;
732 for (Scope *OuterS = S->getParent(); OuterS;
733 OuterS = OuterS->getParent()) {
734 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000735 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000736 break;
737 }
738 }
739
740 // C++ [temp.local]p8:
741 // In the definition of a member of a class template that appears
742 // outside of the namespace containing the class template
743 // definition, the name of a template-parameter hides the name of
744 // a member of this namespace.
745 //
746 // Example:
747 //
748 // namespace N {
749 // class C { };
750 //
751 // template<class T> class B {
752 // void f(T);
753 // };
754 // }
755 //
756 // template<class C> void N::B<C>::f(C) {
757 // C b; // C is the template parameter, not N::C
758 // }
759 //
760 // In this example, the lexical context we return is the
761 // TranslationUnit, while the semantic context is the namespace N.
762 if (!Lexical || !DC || !S->getParent() ||
763 !S->getParent()->isTemplateParamScope())
764 return std::make_pair(Lexical, false);
765
766 // Find the outermost template parameter scope.
767 // For the example, this is the scope for the template parameters of
768 // template<class C>.
769 Scope *OutermostTemplateScope = S->getParent();
770 while (OutermostTemplateScope->getParent() &&
771 OutermostTemplateScope->getParent()->isTemplateParamScope())
772 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregor7f737c02009-09-10 16:57:35 +0000773
Douglas Gregor66230062010-03-15 14:33:29 +0000774 // Find the namespace context in which the original scope occurs. In
775 // the example, this is namespace N.
776 DeclContext *Semantic = DC;
777 while (!Semantic->isFileContext())
778 Semantic = Semantic->getParent();
779
780 // Find the declaration context just outside of the template
781 // parameter scope. This is the context in which the template is
782 // being lexically declaration (a namespace context). In the
783 // example, this is the global scope.
784 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
785 Lexical->Encloses(Semantic))
786 return std::make_pair(Semantic, true);
787
788 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000789}
790
John McCall27b18f82009-11-17 02:14:36 +0000791bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000792 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000793
794 DeclarationName Name = R.getLookupName();
795
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000796 // If this is the name of an implicitly-declared special member function,
797 // go through the scope stack to implicitly declare
798 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
799 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
800 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
801 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
802 }
803
804 // Implicitly declare member functions with the name we're looking for, if in
805 // fact we are in a scope where it matters.
806
Douglas Gregor889ceb72009-02-03 19:21:40 +0000807 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000808 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000809 I = IdResolver.begin(Name),
810 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000811
Douglas Gregor889ceb72009-02-03 19:21:40 +0000812 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000813 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000814 // ...During unqualified name lookup (3.4.1), the names appear as if
815 // they were declared in the nearest enclosing namespace which contains
816 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000817 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000818 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000819 //
820 // For example:
821 // namespace A { int i; }
822 // void foo() {
823 // int i;
824 // {
825 // using namespace A;
826 // ++i; // finds local 'i', A::i appears at global scope
827 // }
828 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000829 //
Douglas Gregor66230062010-03-15 14:33:29 +0000830 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000831 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000832 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
833
Douglas Gregor889ceb72009-02-03 19:21:40 +0000834 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000835 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000836 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000837 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000838 Found = true;
839 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000840 }
841 }
John McCall9f3059a2009-10-09 21:13:30 +0000842 if (Found) {
843 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000844 if (S->isClassScope())
845 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
846 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000847 return true;
848 }
849
Douglas Gregor66230062010-03-15 14:33:29 +0000850 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
851 S->getParent() && !S->getParent()->isTemplateParamScope()) {
852 // We've just searched the last template parameter scope and
853 // found nothing, so look into the the contexts between the
854 // lexical and semantic declaration contexts returned by
855 // findOuterContext(). This implements the name lookup behavior
856 // of C++ [temp.local]p8.
857 Ctx = OutsideOfTemplateParamDC;
858 OutsideOfTemplateParamDC = 0;
859 }
860
861 if (Ctx) {
862 DeclContext *OuterCtx;
863 bool SearchAfterTemplateScope;
864 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
865 if (SearchAfterTemplateScope)
866 OutsideOfTemplateParamDC = OuterCtx;
867
Douglas Gregorea166062010-03-15 15:26:48 +0000868 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000869 // We do not directly look into transparent contexts, since
870 // those entities will be found in the nearest enclosing
871 // non-transparent context.
872 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000873 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000874
875 // We do not look directly into function or method contexts,
876 // since all of the local variables and parameters of the
877 // function/method are present within the Scope.
878 if (Ctx->isFunctionOrMethod()) {
879 // If we have an Objective-C instance method, look for ivars
880 // in the corresponding interface.
881 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
882 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
883 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
884 ObjCInterfaceDecl *ClassDeclared;
885 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
886 Name.getAsIdentifierInfo(),
887 ClassDeclared)) {
888 if (R.isAcceptableDecl(Ivar)) {
889 R.addDecl(Ivar);
890 R.resolveKind();
891 return true;
892 }
893 }
894 }
895 }
896
897 continue;
898 }
899
Douglas Gregor7f737c02009-09-10 16:57:35 +0000900 // Perform qualified name lookup into this context.
901 // FIXME: In some cases, we know that every name that could be found by
902 // this qualified name lookup will also be on the identifier chain. For
903 // example, inside a class without any base classes, we never need to
904 // perform qualified lookup because all of the members are on top of the
905 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000906 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000907 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000908 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000909 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000910 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000911
John McCallf6c8a4e2009-11-10 07:01:13 +0000912 // Stop if we ran out of scopes.
913 // FIXME: This really, really shouldn't be happening.
914 if (!S) return false;
915
Douglas Gregor700792c2009-02-05 19:25:20 +0000916 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000917 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000918 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000919 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
920 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000921
John McCallf6c8a4e2009-11-10 07:01:13 +0000922 UnqualUsingDirectiveSet UDirs;
923 UDirs.visitScopeChain(Initial, S);
924 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000925
Douglas Gregor700792c2009-02-05 19:25:20 +0000926 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000927 // Unqualified name lookup in C++ requires looking into scopes
928 // that aren't strictly lexical, and therefore we walk through the
929 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000930
Douglas Gregor889ceb72009-02-03 19:21:40 +0000931 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000932 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000933 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000934 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000935 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000936 // We found something. Look for anything else in our scope
937 // with this same name and in an acceptable identifier
938 // namespace, so that we can construct an overload set if we
939 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000940 Found = true;
941 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000942 }
943 }
944
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000945 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000946 R.resolveKind();
947 return true;
948 }
949
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000950 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
951 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
952 S->getParent() && !S->getParent()->isTemplateParamScope()) {
953 // We've just searched the last template parameter scope and
954 // found nothing, so look into the the contexts between the
955 // lexical and semantic declaration contexts returned by
956 // findOuterContext(). This implements the name lookup behavior
957 // of C++ [temp.local]p8.
958 Ctx = OutsideOfTemplateParamDC;
959 OutsideOfTemplateParamDC = 0;
960 }
961
962 if (Ctx) {
963 DeclContext *OuterCtx;
964 bool SearchAfterTemplateScope;
965 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
966 if (SearchAfterTemplateScope)
967 OutsideOfTemplateParamDC = OuterCtx;
968
969 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
970 // We do not directly look into transparent contexts, since
971 // those entities will be found in the nearest enclosing
972 // non-transparent context.
973 if (Ctx->isTransparentContext())
974 continue;
975
976 // If we have a context, and it's not a context stashed in the
977 // template parameter scope for an out-of-line definition, also
978 // look into that context.
979 if (!(Found && S && S->isTemplateParamScope())) {
980 assert(Ctx->isFileContext() &&
981 "We should have been looking only at file context here already.");
982
983 // Look into context considering using-directives.
984 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
985 Found = true;
986 }
987
988 if (Found) {
989 R.resolveKind();
990 return true;
991 }
992
993 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
994 return false;
995 }
996 }
997
Douglas Gregor3ce74932010-02-05 07:07:10 +0000998 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000999 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +00001000 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001001
John McCall9f3059a2009-10-09 21:13:30 +00001002 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001003}
1004
Douglas Gregor34074322009-01-14 22:20:51 +00001005/// @brief Perform unqualified name lookup starting from a given
1006/// scope.
1007///
1008/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1009/// used to find names within the current scope. For example, 'x' in
1010/// @code
1011/// int x;
1012/// int f() {
1013/// return x; // unqualified name look finds 'x' in the global scope
1014/// }
1015/// @endcode
1016///
1017/// Different lookup criteria can find different names. For example, a
1018/// particular scope can have both a struct and a function of the same
1019/// name, and each can be found by certain lookup criteria. For more
1020/// information about lookup criteria, see the documentation for the
1021/// class LookupCriteria.
1022///
1023/// @param S The scope from which unqualified name lookup will
1024/// begin. If the lookup criteria permits, name lookup may also search
1025/// in the parent scopes.
1026///
1027/// @param Name The name of the entity that we are searching for.
1028///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001029/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001030/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001031/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001032///
1033/// @returns The result of name lookup, which includes zero or more
1034/// declarations and possibly additional information used to diagnose
1035/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001036bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1037 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001038 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001039
John McCall27b18f82009-11-17 02:14:36 +00001040 LookupNameKind NameKind = R.getLookupKind();
1041
Douglas Gregor34074322009-01-14 22:20:51 +00001042 if (!getLangOptions().CPlusPlus) {
1043 // Unqualified name lookup in C/Objective-C is purely lexical, so
1044 // search in the declarations attached to the name.
1045
John McCallea305ed2009-12-18 10:40:03 +00001046 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001047 // Find the nearest non-transparent declaration scope.
1048 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001049 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001050 static_cast<DeclContext *>(S->getEntity())
1051 ->isTransparentContext()))
1052 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001053 }
1054
John McCallea305ed2009-12-18 10:40:03 +00001055 unsigned IDNS = R.getIdentifierNamespace();
1056
Douglas Gregor34074322009-01-14 22:20:51 +00001057 // Scan up the scope chain looking for a decl that matches this
1058 // identifier that is in the appropriate namespace. This search
1059 // should not take long, as shadowing of names is uncommon, and
1060 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001061 bool LeftStartingScope = false;
1062
Douglas Gregored8f2882009-01-30 01:04:22 +00001063 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001064 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001065 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001066 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001067 if (NameKind == LookupRedeclarationWithLinkage) {
1068 // Determine whether this (or a previous) declaration is
1069 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001070 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001071 LeftStartingScope = true;
1072
1073 // If we found something outside of our starting scope that
1074 // does not have linkage, skip it.
1075 if (LeftStartingScope && !((*I)->hasLinkage()))
1076 continue;
1077 }
1078
John McCall9f3059a2009-10-09 21:13:30 +00001079 R.addDecl(*I);
1080
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001081 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001082 // If this declaration has the "overloadable" attribute, we
1083 // might have a set of overloaded functions.
1084
1085 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001086 while (!(S->getFlags() & Scope::DeclScope) ||
John McCall48871652010-08-21 09:40:31 +00001087 !S->isDeclScope(*I))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001088 S = S->getParent();
1089
1090 // Find the last declaration in this scope (with the same
1091 // name, naturally).
1092 IdentifierResolver::iterator LastI = I;
1093 for (++LastI; LastI != IEnd; ++LastI) {
John McCall48871652010-08-21 09:40:31 +00001094 if (!S->isDeclScope(*LastI))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001095 break;
John McCall9f3059a2009-10-09 21:13:30 +00001096 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001097 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001098 }
1099
John McCall9f3059a2009-10-09 21:13:30 +00001100 R.resolveKind();
1101
1102 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001103 }
Douglas Gregor34074322009-01-14 22:20:51 +00001104 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001105 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001106 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001107 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001108 }
1109
1110 // If we didn't find a use of this identifier, and if the identifier
1111 // corresponds to a compiler builtin, create the decl object for the builtin
1112 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +00001113 if (AllowBuiltinCreation)
1114 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001115
John McCall9f3059a2009-10-09 21:13:30 +00001116 return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001117}
1118
John McCall6538c932009-10-10 05:48:19 +00001119/// @brief Perform qualified name lookup in the namespaces nominated by
1120/// using directives by the given context.
1121///
1122/// C++98 [namespace.qual]p2:
1123/// Given X::m (where X is a user-declared namespace), or given ::m
1124/// (where X is the global namespace), let S be the set of all
1125/// declarations of m in X and in the transitive closure of all
1126/// namespaces nominated by using-directives in X and its used
1127/// namespaces, except that using-directives are ignored in any
1128/// namespace, including X, directly containing one or more
1129/// declarations of m. No namespace is searched more than once in
1130/// the lookup of a name. If S is the empty set, the program is
1131/// ill-formed. Otherwise, if S has exactly one member, or if the
1132/// context of the reference is a using-declaration
1133/// (namespace.udecl), S is the required set of declarations of
1134/// m. Otherwise if the use of m is not one that allows a unique
1135/// declaration to be chosen from S, the program is ill-formed.
1136/// C++98 [namespace.qual]p5:
1137/// During the lookup of a qualified namespace member name, if the
1138/// lookup finds more than one declaration of the member, and if one
1139/// declaration introduces a class name or enumeration name and the
1140/// other declarations either introduce the same object, the same
1141/// enumerator or a set of functions, the non-type name hides the
1142/// class or enumeration name if and only if the declarations are
1143/// from the same namespace; otherwise (the declarations are from
1144/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001145static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001146 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001147 assert(StartDC->isFileContext() && "start context is not a file context");
1148
1149 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1150 DeclContext::udir_iterator E = StartDC->using_directives_end();
1151
1152 if (I == E) return false;
1153
1154 // We have at least added all these contexts to the queue.
1155 llvm::DenseSet<DeclContext*> Visited;
1156 Visited.insert(StartDC);
1157
1158 // We have not yet looked into these namespaces, much less added
1159 // their "using-children" to the queue.
1160 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1161
1162 // We have already looked into the initial namespace; seed the queue
1163 // with its using-children.
1164 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001165 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001166 if (Visited.insert(ND).second)
1167 Queue.push_back(ND);
1168 }
1169
1170 // The easiest way to implement the restriction in [namespace.qual]p5
1171 // is to check whether any of the individual results found a tag
1172 // and, if so, to declare an ambiguity if the final result is not
1173 // a tag.
1174 bool FoundTag = false;
1175 bool FoundNonTag = false;
1176
John McCall5cebab12009-11-18 07:57:50 +00001177 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001178
1179 bool Found = false;
1180 while (!Queue.empty()) {
1181 NamespaceDecl *ND = Queue.back();
1182 Queue.pop_back();
1183
1184 // We go through some convolutions here to avoid copying results
1185 // between LookupResults.
1186 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001187 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001188 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001189
1190 if (FoundDirect) {
1191 // First do any local hiding.
1192 DirectR.resolveKind();
1193
1194 // If the local result is a tag, remember that.
1195 if (DirectR.isSingleTagDecl())
1196 FoundTag = true;
1197 else
1198 FoundNonTag = true;
1199
1200 // Append the local results to the total results if necessary.
1201 if (UseLocal) {
1202 R.addAllDecls(LocalR);
1203 LocalR.clear();
1204 }
1205 }
1206
1207 // If we find names in this namespace, ignore its using directives.
1208 if (FoundDirect) {
1209 Found = true;
1210 continue;
1211 }
1212
1213 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1214 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1215 if (Visited.insert(Nom).second)
1216 Queue.push_back(Nom);
1217 }
1218 }
1219
1220 if (Found) {
1221 if (FoundTag && FoundNonTag)
1222 R.setAmbiguousQualifiedTagHiding();
1223 else
1224 R.resolveKind();
1225 }
1226
1227 return Found;
1228}
1229
Douglas Gregor39982192010-08-15 06:18:01 +00001230/// \brief Callback that looks for any member of a class with the given name.
1231static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1232 CXXBasePath &Path,
1233 void *Name) {
1234 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1235
1236 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1237 Path.Decls = BaseRecord->lookup(N);
1238 return Path.Decls.first != Path.Decls.second;
1239}
1240
Douglas Gregorc0d24902010-10-22 22:08:47 +00001241/// \brief Determine whether the given set of member declarations contains only
1242/// static members, nested types, and enumerators.
1243template<typename InputIterator>
1244static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1245 Decl *D = (*First)->getUnderlyingDecl();
1246 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1247 return true;
1248
1249 if (isa<CXXMethodDecl>(D)) {
1250 // Determine whether all of the methods are static.
1251 bool AllMethodsAreStatic = true;
1252 for(; First != Last; ++First) {
1253 D = (*First)->getUnderlyingDecl();
1254
1255 if (!isa<CXXMethodDecl>(D)) {
1256 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1257 break;
1258 }
1259
1260 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1261 AllMethodsAreStatic = false;
1262 break;
1263 }
1264 }
1265
1266 if (AllMethodsAreStatic)
1267 return true;
1268 }
1269
1270 return false;
1271}
1272
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001273/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001274///
1275/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1276/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001277/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001278///
1279/// Different lookup criteria can find different names. For example, a
1280/// particular scope can have both a struct and a function of the same
1281/// name, and each can be found by certain lookup criteria. For more
1282/// information about lookup criteria, see the documentation for the
1283/// class LookupCriteria.
1284///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001285/// \param R captures both the lookup criteria and any lookup results found.
1286///
1287/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001288/// search. If the lookup criteria permits, name lookup may also search
1289/// in the parent contexts or (for C++ classes) base classes.
1290///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001291/// \param InUnqualifiedLookup true if this is qualified name lookup that
1292/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001293///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001294/// \returns true if lookup succeeded, false if it failed.
1295bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1296 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001297 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001298
John McCall27b18f82009-11-17 02:14:36 +00001299 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001300 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001301
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001302 // Make sure that the declaration context is complete.
1303 assert((!isa<TagDecl>(LookupCtx) ||
1304 LookupCtx->isDependentContext() ||
1305 cast<TagDecl>(LookupCtx)->isDefinition() ||
1306 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1307 ->isBeingDefined()) &&
1308 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001309
Douglas Gregor34074322009-01-14 22:20:51 +00001310 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001311 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001312 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001313 if (isa<CXXRecordDecl>(LookupCtx))
1314 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001315 return true;
1316 }
Douglas Gregor34074322009-01-14 22:20:51 +00001317
John McCall6538c932009-10-10 05:48:19 +00001318 // Don't descend into implied contexts for redeclarations.
1319 // C++98 [namespace.qual]p6:
1320 // In a declaration for a namespace member in which the
1321 // declarator-id is a qualified-id, given that the qualified-id
1322 // for the namespace member has the form
1323 // nested-name-specifier unqualified-id
1324 // the unqualified-id shall name a member of the namespace
1325 // designated by the nested-name-specifier.
1326 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001327 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001328 return false;
1329
John McCall27b18f82009-11-17 02:14:36 +00001330 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001331 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001332 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001333
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001334 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001335 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001336 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001337 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001338 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001339
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001340 // If we're performing qualified name lookup into a dependent class,
1341 // then we are actually looking into a current instantiation. If we have any
1342 // dependent base classes, then we either have to delay lookup until
1343 // template instantiation time (at which point all bases will be available)
1344 // or we have to fail.
1345 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1346 LookupRec->hasAnyDependentBases()) {
1347 R.setNotFoundInCurrentInstantiation();
1348 return false;
1349 }
1350
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001351 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001352 CXXBasePaths Paths;
1353 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001354
1355 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001356 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001357 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001358 case LookupOrdinaryName:
1359 case LookupMemberName:
1360 case LookupRedeclarationWithLinkage:
1361 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1362 break;
1363
1364 case LookupTagName:
1365 BaseCallback = &CXXRecordDecl::FindTagMember;
1366 break;
John McCall84d87672009-12-10 09:41:52 +00001367
Douglas Gregor39982192010-08-15 06:18:01 +00001368 case LookupAnyName:
1369 BaseCallback = &LookupAnyMember;
1370 break;
1371
John McCall84d87672009-12-10 09:41:52 +00001372 case LookupUsingDeclName:
1373 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001374
1375 case LookupOperatorName:
1376 case LookupNamespaceName:
1377 case LookupObjCProtocolName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001378 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001379 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001380
1381 case LookupNestedNameSpecifierName:
1382 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1383 break;
1384 }
1385
John McCall27b18f82009-11-17 02:14:36 +00001386 if (!LookupRec->lookupInBases(BaseCallback,
1387 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001388 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001389
John McCall553c0792010-01-23 00:46:32 +00001390 R.setNamingClass(LookupRec);
1391
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001392 // C++ [class.member.lookup]p2:
1393 // [...] If the resulting set of declarations are not all from
1394 // sub-objects of the same type, or the set has a nonstatic member
1395 // and includes members from distinct sub-objects, there is an
1396 // ambiguity and the program is ill-formed. Otherwise that set is
1397 // the result of the lookup.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001398 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001399 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001400 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001401
Douglas Gregor36d1b142009-10-06 17:59:45 +00001402 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001403 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001404 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001405
John McCall401982f2010-01-20 21:53:11 +00001406 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1407 // across all paths.
1408 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1409
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001410 // Determine whether we're looking at a distinct sub-object or not.
1411 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001412 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001413 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1414 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001415 continue;
1416 }
1417
1418 if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001419 != Context.getCanonicalType(PathElement.Base->getType())) {
1420 // We found members of the given name in two subobjects of
Douglas Gregorc0d24902010-10-22 22:08:47 +00001421 // different types. If the declaration sets aren't the same, this
1422 // this lookup is ambiguous.
1423 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1424 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1425 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1426 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
1427
1428 while (FirstD != FirstPath->Decls.second &&
1429 CurrentD != Path->Decls.second) {
1430 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1431 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1432 break;
1433
1434 ++FirstD;
1435 ++CurrentD;
1436 }
1437
1438 if (FirstD == FirstPath->Decls.second &&
1439 CurrentD == Path->Decls.second)
1440 continue;
1441 }
1442
John McCall9f3059a2009-10-09 21:13:30 +00001443 R.setAmbiguousBaseSubobjectTypes(Paths);
1444 return true;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001445 }
1446
1447 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001448 // We have a different subobject of the same type.
1449
1450 // C++ [class.member.lookup]p5:
1451 // A static member, a nested type or an enumerator defined in
1452 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001453 // has more than one base class subobject of type T.
Douglas Gregorc0d24902010-10-22 22:08:47 +00001454 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001455 continue;
Douglas Gregorc0d24902010-10-22 22:08:47 +00001456
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001457 // We have found a nonstatic member name in multiple, distinct
1458 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001459 R.setAmbiguousBaseSubobjects(Paths);
1460 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001461 }
1462 }
1463
1464 // Lookup in a base class succeeded; return these results.
1465
John McCall9f3059a2009-10-09 21:13:30 +00001466 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001467 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1468 NamedDecl *D = *I;
1469 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1470 D->getAccess());
1471 R.addDecl(D, AS);
1472 }
John McCall9f3059a2009-10-09 21:13:30 +00001473 R.resolveKind();
1474 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001475}
1476
1477/// @brief Performs name lookup for a name that was parsed in the
1478/// source code, and may contain a C++ scope specifier.
1479///
1480/// This routine is a convenience routine meant to be called from
1481/// contexts that receive a name and an optional C++ scope specifier
1482/// (e.g., "N::M::x"). It will then perform either qualified or
1483/// unqualified name lookup (with LookupQualifiedName or LookupName,
1484/// respectively) on the given name and return those results.
1485///
1486/// @param S The scope from which unqualified name lookup will
1487/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001488///
Douglas Gregore861bac2009-08-25 22:51:20 +00001489/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001490///
1491/// @param Name The name of the entity that name lookup will
1492/// search for.
1493///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001494/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001495/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001496/// C library functions (like "malloc") are implicitly declared.
1497///
Douglas Gregore861bac2009-08-25 22:51:20 +00001498/// @param EnteringContext Indicates whether we are going to enter the
1499/// context of the scope-specifier SS (if present).
1500///
John McCall9f3059a2009-10-09 21:13:30 +00001501/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001502bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001503 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001504 if (SS && SS->isInvalid()) {
1505 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001506 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001507 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001508 }
Mike Stump11289f42009-09-09 15:08:12 +00001509
Douglas Gregore861bac2009-08-25 22:51:20 +00001510 if (SS && SS->isSet()) {
1511 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001512 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001513 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001514 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001515 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001516
John McCall27b18f82009-11-17 02:14:36 +00001517 R.setContextRange(SS->getRange());
1518
1519 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001520 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001521
Douglas Gregore861bac2009-08-25 22:51:20 +00001522 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001523 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001524 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001525 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001526 }
1527
Mike Stump11289f42009-09-09 15:08:12 +00001528 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001529 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001530}
1531
Douglas Gregor889ceb72009-02-03 19:21:40 +00001532
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001533/// @brief Produce a diagnostic describing the ambiguity that resulted
1534/// from name lookup.
1535///
1536/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001537///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001538/// @param Name The name of the entity that name lookup was
1539/// searching for.
1540///
1541/// @param NameLoc The location of the name within the source code.
1542///
1543/// @param LookupRange A source range that provides more
1544/// source-location information concerning the lookup itself. For
1545/// example, this range might highlight a nested-name-specifier that
1546/// precedes the name.
1547///
1548/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001549bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001550 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1551
John McCall27b18f82009-11-17 02:14:36 +00001552 DeclarationName Name = Result.getLookupName();
1553 SourceLocation NameLoc = Result.getNameLoc();
1554 SourceRange LookupRange = Result.getContextRange();
1555
John McCall6538c932009-10-10 05:48:19 +00001556 switch (Result.getAmbiguityKind()) {
1557 case LookupResult::AmbiguousBaseSubobjects: {
1558 CXXBasePaths *Paths = Result.getBasePaths();
1559 QualType SubobjectType = Paths->front().back().Base->getType();
1560 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1561 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1562 << LookupRange;
1563
1564 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1565 while (isa<CXXMethodDecl>(*Found) &&
1566 cast<CXXMethodDecl>(*Found)->isStatic())
1567 ++Found;
1568
1569 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1570
1571 return true;
1572 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001573
John McCall6538c932009-10-10 05:48:19 +00001574 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001575 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1576 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001577
1578 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001579 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001580 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1581 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001582 Path != PathEnd; ++Path) {
1583 Decl *D = *Path->Decls.first;
1584 if (DeclsPrinted.insert(D).second)
1585 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1586 }
1587
Douglas Gregor1c846b02009-01-16 00:38:09 +00001588 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001589 }
1590
John McCall6538c932009-10-10 05:48:19 +00001591 case LookupResult::AmbiguousTagHiding: {
1592 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001593
John McCall6538c932009-10-10 05:48:19 +00001594 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1595
1596 LookupResult::iterator DI, DE = Result.end();
1597 for (DI = Result.begin(); DI != DE; ++DI)
1598 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1599 TagDecls.insert(TD);
1600 Diag(TD->getLocation(), diag::note_hidden_tag);
1601 }
1602
1603 for (DI = Result.begin(); DI != DE; ++DI)
1604 if (!isa<TagDecl>(*DI))
1605 Diag((*DI)->getLocation(), diag::note_hiding_object);
1606
1607 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001608 LookupResult::Filter F = Result.makeFilter();
1609 while (F.hasNext()) {
1610 if (TagDecls.count(F.next()))
1611 F.erase();
1612 }
1613 F.done();
John McCall6538c932009-10-10 05:48:19 +00001614
1615 return true;
1616 }
1617
1618 case LookupResult::AmbiguousReference: {
1619 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001620
John McCall6538c932009-10-10 05:48:19 +00001621 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1622 for (; DI != DE; ++DI)
1623 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001624
John McCall6538c932009-10-10 05:48:19 +00001625 return true;
1626 }
1627 }
1628
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001629 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001630 return true;
1631}
Douglas Gregore254f902009-02-04 00:32:51 +00001632
John McCallf24d7bb2010-05-28 18:45:08 +00001633namespace {
1634 struct AssociatedLookup {
1635 AssociatedLookup(Sema &S,
1636 Sema::AssociatedNamespaceSet &Namespaces,
1637 Sema::AssociatedClassSet &Classes)
1638 : S(S), Namespaces(Namespaces), Classes(Classes) {
1639 }
1640
1641 Sema &S;
1642 Sema::AssociatedNamespaceSet &Namespaces;
1643 Sema::AssociatedClassSet &Classes;
1644 };
1645}
1646
Mike Stump11289f42009-09-09 15:08:12 +00001647static void
John McCallf24d7bb2010-05-28 18:45:08 +00001648addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001649
Douglas Gregor8b895222010-04-30 07:08:38 +00001650static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1651 DeclContext *Ctx) {
1652 // Add the associated namespace for this class.
1653
1654 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1655 // be a locally scoped record.
1656
Sebastian Redlbd595762010-08-31 20:53:31 +00001657 // We skip out of inline namespaces. The innermost non-inline namespace
1658 // contains all names of all its nested inline namespaces anyway, so we can
1659 // replace the entire inline namespace tree with its root.
1660 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1661 Ctx->isInlineNamespace())
Douglas Gregor8b895222010-04-30 07:08:38 +00001662 Ctx = Ctx->getParent();
1663
John McCallc7e8e792009-08-07 22:18:02 +00001664 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001665 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001666}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001667
Mike Stump11289f42009-09-09 15:08:12 +00001668// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001669// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001670static void
John McCallf24d7bb2010-05-28 18:45:08 +00001671addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1672 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001673 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001674 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001675 switch (Arg.getKind()) {
1676 case TemplateArgument::Null:
1677 break;
Mike Stump11289f42009-09-09 15:08:12 +00001678
Douglas Gregor197e5f72009-07-08 07:51:57 +00001679 case TemplateArgument::Type:
1680 // [...] the namespaces and classes associated with the types of the
1681 // template arguments provided for template type parameters (excluding
1682 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001683 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001684 break;
Mike Stump11289f42009-09-09 15:08:12 +00001685
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001686 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001687 // [...] the namespaces in which any template template arguments are
1688 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001689 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001690 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001691 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001692 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001693 DeclContext *Ctx = ClassTemplate->getDeclContext();
1694 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001695 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001696 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001697 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001698 }
1699 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001700 }
1701
1702 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001703 case TemplateArgument::Integral:
1704 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001705 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001706 // associated namespaces. ]
1707 break;
Mike Stump11289f42009-09-09 15:08:12 +00001708
Douglas Gregor197e5f72009-07-08 07:51:57 +00001709 case TemplateArgument::Pack:
1710 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1711 PEnd = Arg.pack_end();
1712 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001713 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001714 break;
1715 }
1716}
1717
Douglas Gregore254f902009-02-04 00:32:51 +00001718// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001719// argument-dependent lookup with an argument of class type
1720// (C++ [basic.lookup.koenig]p2).
1721static void
John McCallf24d7bb2010-05-28 18:45:08 +00001722addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1723 CXXRecordDecl *Class) {
1724
1725 // Just silently ignore anything whose name is __va_list_tag.
1726 if (Class->getDeclName() == Result.S.VAListTagName)
1727 return;
1728
Douglas Gregore254f902009-02-04 00:32:51 +00001729 // C++ [basic.lookup.koenig]p2:
1730 // [...]
1731 // -- If T is a class type (including unions), its associated
1732 // classes are: the class itself; the class of which it is a
1733 // member, if any; and its direct and indirect base
1734 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001735 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001736
1737 // Add the class of which it is a member, if any.
1738 DeclContext *Ctx = Class->getDeclContext();
1739 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001740 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001741 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001742 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001743
Douglas Gregore254f902009-02-04 00:32:51 +00001744 // Add the class itself. If we've already seen this class, we don't
1745 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001746 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001747 return;
1748
Mike Stump11289f42009-09-09 15:08:12 +00001749 // -- If T is a template-id, its associated namespaces and classes are
1750 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001751 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001752 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001753 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001754 // namespaces in which any template template arguments are defined; and
1755 // the classes in which any member templates used as template template
1756 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001757 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001758 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001759 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1760 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1761 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001762 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001763 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001764 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001765
Douglas Gregor197e5f72009-07-08 07:51:57 +00001766 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1767 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001768 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001769 }
Mike Stump11289f42009-09-09 15:08:12 +00001770
John McCall67da35c2010-02-04 22:26:26 +00001771 // Only recurse into base classes for complete types.
1772 if (!Class->hasDefinition()) {
1773 // FIXME: we might need to instantiate templates here
1774 return;
1775 }
1776
Douglas Gregore254f902009-02-04 00:32:51 +00001777 // Add direct and indirect base classes along with their associated
1778 // namespaces.
1779 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1780 Bases.push_back(Class);
1781 while (!Bases.empty()) {
1782 // Pop this class off the stack.
1783 Class = Bases.back();
1784 Bases.pop_back();
1785
1786 // Visit the base classes.
1787 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1788 BaseEnd = Class->bases_end();
1789 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001790 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001791 // In dependent contexts, we do ADL twice, and the first time around,
1792 // the base type might be a dependent TemplateSpecializationType, or a
1793 // TemplateTypeParmType. If that happens, simply ignore it.
1794 // FIXME: If we want to support export, we probably need to add the
1795 // namespace of the template in a TemplateSpecializationType, or even
1796 // the classes and namespaces of known non-dependent arguments.
1797 if (!BaseType)
1798 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001799 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001800 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001801 // Find the associated namespace for this base class.
1802 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001803 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001804
1805 // Make sure we visit the bases of this base class.
1806 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1807 Bases.push_back(BaseDecl);
1808 }
1809 }
1810 }
1811}
1812
1813// \brief Add the associated classes and namespaces for
1814// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001815// (C++ [basic.lookup.koenig]p2).
1816static void
John McCallf24d7bb2010-05-28 18:45:08 +00001817addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001818 // C++ [basic.lookup.koenig]p2:
1819 //
1820 // For each argument type T in the function call, there is a set
1821 // of zero or more associated namespaces and a set of zero or more
1822 // associated classes to be considered. The sets of namespaces and
1823 // classes is determined entirely by the types of the function
1824 // arguments (and the namespace of any template template
1825 // argument). Typedef names and using-declarations used to specify
1826 // the types do not contribute to this set. The sets of namespaces
1827 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001828
John McCall0af3d3b2010-05-28 06:08:54 +00001829 llvm::SmallVector<const Type *, 16> Queue;
1830 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1831
Douglas Gregore254f902009-02-04 00:32:51 +00001832 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001833 switch (T->getTypeClass()) {
1834
1835#define TYPE(Class, Base)
1836#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1837#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1838#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1839#define ABSTRACT_TYPE(Class, Base)
1840#include "clang/AST/TypeNodes.def"
1841 // T is canonical. We can also ignore dependent types because
1842 // we don't need to do ADL at the definition point, but if we
1843 // wanted to implement template export (or if we find some other
1844 // use for associated classes and namespaces...) this would be
1845 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001846 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001847
John McCall0af3d3b2010-05-28 06:08:54 +00001848 // -- If T is a pointer to U or an array of U, its associated
1849 // namespaces and classes are those associated with U.
1850 case Type::Pointer:
1851 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1852 continue;
1853 case Type::ConstantArray:
1854 case Type::IncompleteArray:
1855 case Type::VariableArray:
1856 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1857 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001858
John McCall0af3d3b2010-05-28 06:08:54 +00001859 // -- If T is a fundamental type, its associated sets of
1860 // namespaces and classes are both empty.
1861 case Type::Builtin:
1862 break;
1863
1864 // -- If T is a class type (including unions), its associated
1865 // classes are: the class itself; the class of which it is a
1866 // member, if any; and its direct and indirect base
1867 // classes. Its associated namespaces are the namespaces in
1868 // which its associated classes are defined.
1869 case Type::Record: {
1870 CXXRecordDecl *Class
1871 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001872 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001873 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001874 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001875
John McCall0af3d3b2010-05-28 06:08:54 +00001876 // -- If T is an enumeration type, its associated namespace is
1877 // the namespace in which it is defined. If it is class
1878 // member, its associated class is the member’s class; else
1879 // it has no associated class.
1880 case Type::Enum: {
1881 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001882
John McCall0af3d3b2010-05-28 06:08:54 +00001883 DeclContext *Ctx = Enum->getDeclContext();
1884 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001885 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001886
John McCall0af3d3b2010-05-28 06:08:54 +00001887 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001888 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001889
John McCall0af3d3b2010-05-28 06:08:54 +00001890 break;
1891 }
1892
1893 // -- If T is a function type, its associated namespaces and
1894 // classes are those associated with the function parameter
1895 // types and those associated with the return type.
1896 case Type::FunctionProto: {
1897 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1898 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1899 ArgEnd = Proto->arg_type_end();
1900 Arg != ArgEnd; ++Arg)
1901 Queue.push_back(Arg->getTypePtr());
1902 // fallthrough
1903 }
1904 case Type::FunctionNoProto: {
1905 const FunctionType *FnType = cast<FunctionType>(T);
1906 T = FnType->getResultType().getTypePtr();
1907 continue;
1908 }
1909
1910 // -- If T is a pointer to a member function of a class X, its
1911 // associated namespaces and classes are those associated
1912 // with the function parameter types and return type,
1913 // together with those associated with X.
1914 //
1915 // -- If T is a pointer to a data member of class X, its
1916 // associated namespaces and classes are those associated
1917 // with the member type together with those associated with
1918 // X.
1919 case Type::MemberPointer: {
1920 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1921
1922 // Queue up the class type into which this points.
1923 Queue.push_back(MemberPtr->getClass());
1924
1925 // And directly continue with the pointee type.
1926 T = MemberPtr->getPointeeType().getTypePtr();
1927 continue;
1928 }
1929
1930 // As an extension, treat this like a normal pointer.
1931 case Type::BlockPointer:
1932 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1933 continue;
1934
1935 // References aren't covered by the standard, but that's such an
1936 // obvious defect that we cover them anyway.
1937 case Type::LValueReference:
1938 case Type::RValueReference:
1939 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1940 continue;
1941
1942 // These are fundamental types.
1943 case Type::Vector:
1944 case Type::ExtVector:
1945 case Type::Complex:
1946 break;
1947
1948 // These are ignored by ADL.
1949 case Type::ObjCObject:
1950 case Type::ObjCInterface:
1951 case Type::ObjCObjectPointer:
1952 break;
1953 }
1954
1955 if (Queue.empty()) break;
1956 T = Queue.back();
1957 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001958 }
Douglas Gregore254f902009-02-04 00:32:51 +00001959}
1960
1961/// \brief Find the associated classes and namespaces for
1962/// argument-dependent lookup for a call with the given set of
1963/// arguments.
1964///
1965/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001966/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001967/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001968void
Douglas Gregore254f902009-02-04 00:32:51 +00001969Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1970 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001971 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001972 AssociatedNamespaces.clear();
1973 AssociatedClasses.clear();
1974
John McCallf24d7bb2010-05-28 18:45:08 +00001975 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1976
Douglas Gregore254f902009-02-04 00:32:51 +00001977 // C++ [basic.lookup.koenig]p2:
1978 // For each argument type T in the function call, there is a set
1979 // of zero or more associated namespaces and a set of zero or more
1980 // associated classes to be considered. The sets of namespaces and
1981 // classes is determined entirely by the types of the function
1982 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001983 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001984 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1985 Expr *Arg = Args[ArgIdx];
1986
1987 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00001988 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001989 continue;
1990 }
1991
1992 // [...] In addition, if the argument is the name or address of a
1993 // set of overloaded functions and/or function templates, its
1994 // associated classes and namespaces are the union of those
1995 // associated with each of the members of the set: the namespace
1996 // in which the function or function template is defined and the
1997 // classes and namespaces associated with its (non-dependent)
1998 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001999 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00002000 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00002001 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00002002 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002003
John McCallf24d7bb2010-05-28 18:45:08 +00002004 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2005 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00002006
John McCallf24d7bb2010-05-28 18:45:08 +00002007 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2008 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002009 // Look through any using declarations to find the underlying function.
2010 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002011
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00002012 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2013 if (!FDecl)
2014 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00002015
2016 // Add the classes and namespaces associated with the parameter
2017 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00002018 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00002019 }
2020 }
2021}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002022
2023/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2024/// an acceptable non-member overloaded operator for a call whose
2025/// arguments have types T1 (and, if non-empty, T2). This routine
2026/// implements the check in C++ [over.match.oper]p3b2 concerning
2027/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00002028static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002029IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2030 QualType T1, QualType T2,
2031 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002032 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2033 return true;
2034
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002035 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2036 return true;
2037
John McCall9dd450b2009-09-21 23:43:11 +00002038 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002039 if (Proto->getNumArgs() < 1)
2040 return false;
2041
2042 if (T1->isEnumeralType()) {
2043 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002044 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002045 return true;
2046 }
2047
2048 if (Proto->getNumArgs() < 2)
2049 return false;
2050
2051 if (!T2.isNull() && T2->isEnumeralType()) {
2052 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002053 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002054 return true;
2055 }
2056
2057 return false;
2058}
2059
John McCall5cebab12009-11-18 07:57:50 +00002060NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002061 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002062 LookupNameKind NameKind,
2063 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002064 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002065 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002066 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002067}
2068
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002069/// \brief Find the protocol with the given name, if any.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002070ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2071 SourceLocation IdLoc) {
2072 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2073 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002074 return cast_or_null<ObjCProtocolDecl>(D);
2075}
2076
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002077void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002078 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002079 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002080 // C++ [over.match.oper]p3:
2081 // -- The set of non-member candidates is the result of the
2082 // unqualified lookup of operator@ in the context of the
2083 // expression according to the usual rules for name lookup in
2084 // unqualified function calls (3.4.2) except that all member
2085 // functions are ignored. However, if no operand has a class
2086 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002087 // that have a first parameter of type T1 or "reference to
2088 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002089 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002090 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002091 // when T2 is an enumeration type, are candidate functions.
2092 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002093 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2094 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002095
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002096 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2097
John McCall9f3059a2009-10-09 21:13:30 +00002098 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002099 return;
2100
2101 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2102 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002103 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2104 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002105 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002106 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002107 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002108 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002109 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002110 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002111 // later?
2112 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002113 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002114 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002115 }
2116}
2117
Douglas Gregor52b72822010-07-02 23:12:18 +00002118/// \brief Look up the constructors for the given class.
2119DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +00002120 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002121 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2122 if (!Class->hasDeclaredDefaultConstructor())
2123 DeclareImplicitDefaultConstructor(Class);
2124 if (!Class->hasDeclaredCopyConstructor())
2125 DeclareImplicitCopyConstructor(Class);
2126 }
Douglas Gregora6d69502010-07-02 23:41:54 +00002127
Douglas Gregor52b72822010-07-02 23:12:18 +00002128 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2129 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2130 return Class->lookup(Name);
2131}
2132
Douglas Gregore71edda2010-07-01 22:47:18 +00002133/// \brief Look for the destructor of the given class.
2134///
2135/// During semantic analysis, this routine should be used in lieu of
2136/// CXXRecordDecl::getDestructor().
2137///
2138/// \returns The destructor for this class.
2139CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +00002140 // If the destructor has not yet been declared, do so now.
2141 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2142 !Class->hasDeclaredDestructor())
2143 DeclareImplicitDestructor(Class);
2144
Douglas Gregore71edda2010-07-01 22:47:18 +00002145 return Class->getDestructor();
2146}
2147
John McCall8fe68082010-01-26 07:16:45 +00002148void ADLResult::insert(NamedDecl *New) {
2149 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2150
2151 // If we haven't yet seen a decl for this key, or the last decl
2152 // was exactly this one, we're done.
2153 if (Old == 0 || Old == New) {
2154 Old = New;
2155 return;
2156 }
2157
2158 // Otherwise, decide which is a more recent redeclaration.
2159 FunctionDecl *OldFD, *NewFD;
2160 if (isa<FunctionTemplateDecl>(New)) {
2161 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2162 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2163 } else {
2164 OldFD = cast<FunctionDecl>(Old);
2165 NewFD = cast<FunctionDecl>(New);
2166 }
2167
2168 FunctionDecl *Cursor = NewFD;
2169 while (true) {
2170 Cursor = Cursor->getPreviousDeclaration();
2171
2172 // If we got to the end without finding OldFD, OldFD is the newer
2173 // declaration; leave things as they are.
2174 if (!Cursor) return;
2175
2176 // If we do find OldFD, then NewFD is newer.
2177 if (Cursor == OldFD) break;
2178
2179 // Otherwise, keep looking.
2180 }
2181
2182 Old = New;
2183}
2184
Sebastian Redlc057f422009-10-23 19:23:15 +00002185void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002186 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00002187 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002188 // Find all of the associated namespaces and classes based on the
2189 // arguments we have.
2190 AssociatedNamespaceSet AssociatedNamespaces;
2191 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002192 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002193 AssociatedNamespaces,
2194 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002195
Sebastian Redlc057f422009-10-23 19:23:15 +00002196 QualType T1, T2;
2197 if (Operator) {
2198 T1 = Args[0]->getType();
2199 if (NumArgs >= 2)
2200 T2 = Args[1]->getType();
2201 }
2202
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002203 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002204 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2205 // and let Y be the lookup set produced by argument dependent
2206 // lookup (defined as follows). If X contains [...] then Y is
2207 // empty. Otherwise Y is the set of declarations found in the
2208 // namespaces associated with the argument types as described
2209 // below. The set of declarations found by the lookup of the name
2210 // is the union of X and Y.
2211 //
2212 // Here, we compute Y and add its members to the overloaded
2213 // candidate set.
2214 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002215 NSEnd = AssociatedNamespaces.end();
2216 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002217 // When considering an associated namespace, the lookup is the
2218 // same as the lookup performed when the associated namespace is
2219 // used as a qualifier (3.4.3.2) except that:
2220 //
2221 // -- Any using-directives in the associated namespace are
2222 // ignored.
2223 //
John McCallc7e8e792009-08-07 22:18:02 +00002224 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002225 // associated classes are visible within their respective
2226 // namespaces even if they are not visible during an ordinary
2227 // lookup (11.4).
2228 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002229 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002230 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002231 // If the only declaration here is an ordinary friend, consider
2232 // it only if it was declared in an associated classes.
2233 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002234 DeclContext *LexDC = D->getLexicalDeclContext();
2235 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2236 continue;
2237 }
Mike Stump11289f42009-09-09 15:08:12 +00002238
John McCall91f61fc2010-01-26 06:04:06 +00002239 if (isa<UsingShadowDecl>(D))
2240 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002241
John McCall91f61fc2010-01-26 06:04:06 +00002242 if (isa<FunctionDecl>(D)) {
2243 if (Operator &&
2244 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2245 T1, T2, Context))
2246 continue;
John McCall8fe68082010-01-26 07:16:45 +00002247 } else if (!isa<FunctionTemplateDecl>(D))
2248 continue;
2249
2250 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002251 }
2252 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002253}
Douglas Gregor2d435302009-12-30 17:04:44 +00002254
2255//----------------------------------------------------------------------------
2256// Search for all visible declarations.
2257//----------------------------------------------------------------------------
2258VisibleDeclConsumer::~VisibleDeclConsumer() { }
2259
2260namespace {
2261
2262class ShadowContextRAII;
2263
2264class VisibleDeclsRecord {
2265public:
2266 /// \brief An entry in the shadow map, which is optimized to store a
2267 /// single declaration (the common case) but can also store a list
2268 /// of declarations.
2269 class ShadowMapEntry {
2270 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2271
2272 /// \brief Contains either the solitary NamedDecl * or a vector
2273 /// of declarations.
2274 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2275
2276 public:
2277 ShadowMapEntry() : DeclOrVector() { }
2278
2279 void Add(NamedDecl *ND);
2280 void Destroy();
2281
2282 // Iteration.
2283 typedef NamedDecl **iterator;
2284 iterator begin();
2285 iterator end();
2286 };
2287
2288private:
2289 /// \brief A mapping from declaration names to the declarations that have
2290 /// this name within a particular scope.
2291 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2292
2293 /// \brief A list of shadow maps, which is used to model name hiding.
2294 std::list<ShadowMap> ShadowMaps;
2295
2296 /// \brief The declaration contexts we have already visited.
2297 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2298
2299 friend class ShadowContextRAII;
2300
2301public:
2302 /// \brief Determine whether we have already visited this context
2303 /// (and, if not, note that we are going to visit that context now).
2304 bool visitedContext(DeclContext *Ctx) {
2305 return !VisitedContexts.insert(Ctx);
2306 }
2307
Douglas Gregor39982192010-08-15 06:18:01 +00002308 bool alreadyVisitedContext(DeclContext *Ctx) {
2309 return VisitedContexts.count(Ctx);
2310 }
2311
Douglas Gregor2d435302009-12-30 17:04:44 +00002312 /// \brief Determine whether the given declaration is hidden in the
2313 /// current scope.
2314 ///
2315 /// \returns the declaration that hides the given declaration, or
2316 /// NULL if no such declaration exists.
2317 NamedDecl *checkHidden(NamedDecl *ND);
2318
2319 /// \brief Add a declaration to the current shadow map.
2320 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2321};
2322
2323/// \brief RAII object that records when we've entered a shadow context.
2324class ShadowContextRAII {
2325 VisibleDeclsRecord &Visible;
2326
2327 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2328
2329public:
2330 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2331 Visible.ShadowMaps.push_back(ShadowMap());
2332 }
2333
2334 ~ShadowContextRAII() {
2335 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2336 EEnd = Visible.ShadowMaps.back().end();
2337 E != EEnd;
2338 ++E)
2339 E->second.Destroy();
2340
2341 Visible.ShadowMaps.pop_back();
2342 }
2343};
2344
2345} // end anonymous namespace
2346
2347void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2348 if (DeclOrVector.isNull()) {
2349 // 0 - > 1 elements: just set the single element information.
2350 DeclOrVector = ND;
2351 return;
2352 }
2353
2354 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2355 // 1 -> 2 elements: create the vector of results and push in the
2356 // existing declaration.
2357 DeclVector *Vec = new DeclVector;
2358 Vec->push_back(PrevND);
2359 DeclOrVector = Vec;
2360 }
2361
2362 // Add the new element to the end of the vector.
2363 DeclOrVector.get<DeclVector*>()->push_back(ND);
2364}
2365
2366void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2367 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2368 delete Vec;
2369 DeclOrVector = ((NamedDecl *)0);
2370 }
2371}
2372
2373VisibleDeclsRecord::ShadowMapEntry::iterator
2374VisibleDeclsRecord::ShadowMapEntry::begin() {
2375 if (DeclOrVector.isNull())
2376 return 0;
2377
2378 if (DeclOrVector.dyn_cast<NamedDecl *>())
2379 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2380
2381 return DeclOrVector.get<DeclVector *>()->begin();
2382}
2383
2384VisibleDeclsRecord::ShadowMapEntry::iterator
2385VisibleDeclsRecord::ShadowMapEntry::end() {
2386 if (DeclOrVector.isNull())
2387 return 0;
2388
2389 if (DeclOrVector.dyn_cast<NamedDecl *>())
2390 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2391
2392 return DeclOrVector.get<DeclVector *>()->end();
2393}
2394
2395NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002396 // Look through using declarations.
2397 ND = ND->getUnderlyingDecl();
2398
Douglas Gregor2d435302009-12-30 17:04:44 +00002399 unsigned IDNS = ND->getIdentifierNamespace();
2400 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2401 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2402 SM != SMEnd; ++SM) {
2403 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2404 if (Pos == SM->end())
2405 continue;
2406
2407 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2408 IEnd = Pos->second.end();
2409 I != IEnd; ++I) {
2410 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002411 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor2d435302009-12-30 17:04:44 +00002412 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2413 Decl::IDNS_ObjCProtocol)))
2414 continue;
2415
2416 // Protocols are in distinct namespaces from everything else.
2417 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2418 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2419 (*I)->getIdentifierNamespace() != IDNS)
2420 continue;
2421
Douglas Gregor09bbc652010-01-14 15:47:35 +00002422 // Functions and function templates in the same scope overload
2423 // rather than hide. FIXME: Look for hiding based on function
2424 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002425 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002426 ND->isFunctionOrFunctionTemplate() &&
2427 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002428 continue;
2429
Douglas Gregor2d435302009-12-30 17:04:44 +00002430 // We've found a declaration that hides this one.
2431 return *I;
2432 }
2433 }
2434
2435 return 0;
2436}
2437
2438static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2439 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002440 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002441 VisibleDeclConsumer &Consumer,
2442 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002443 if (!Ctx)
2444 return;
2445
Douglas Gregor2d435302009-12-30 17:04:44 +00002446 // Make sure we don't visit the same context twice.
2447 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2448 return;
2449
Douglas Gregor7454c562010-07-02 20:37:36 +00002450 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2451 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2452
Douglas Gregor2d435302009-12-30 17:04:44 +00002453 // Enumerate all of the results in this context.
2454 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2455 CurCtx = CurCtx->getNextContext()) {
2456 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2457 DEnd = CurCtx->decls_end();
2458 D != DEnd; ++D) {
2459 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2460 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002461 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002462 Visited.add(ND);
2463 }
2464
Sebastian Redlbd595762010-08-31 20:53:31 +00002465 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor2d435302009-12-30 17:04:44 +00002466 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redlbd595762010-08-31 20:53:31 +00002467 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002468 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002469 Consumer, Visited);
2470 }
2471 }
2472 }
2473
2474 // Traverse using directives for qualified name lookup.
2475 if (QualifiedNameLookup) {
2476 ShadowContextRAII Shadow(Visited);
2477 DeclContext::udir_iterator I, E;
2478 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2479 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002480 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002481 }
2482 }
2483
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002484 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002485 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002486 if (!Record->hasDefinition())
2487 return;
2488
Douglas Gregor2d435302009-12-30 17:04:44 +00002489 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2490 BEnd = Record->bases_end();
2491 B != BEnd; ++B) {
2492 QualType BaseType = B->getType();
2493
2494 // Don't look into dependent bases, because name lookup can't look
2495 // there anyway.
2496 if (BaseType->isDependentType())
2497 continue;
2498
2499 const RecordType *Record = BaseType->getAs<RecordType>();
2500 if (!Record)
2501 continue;
2502
2503 // FIXME: It would be nice to be able to determine whether referencing
2504 // a particular member would be ambiguous. For example, given
2505 //
2506 // struct A { int member; };
2507 // struct B { int member; };
2508 // struct C : A, B { };
2509 //
2510 // void f(C *c) { c->### }
2511 //
2512 // accessing 'member' would result in an ambiguity. However, we
2513 // could be smart enough to qualify the member with the base
2514 // class, e.g.,
2515 //
2516 // c->B::member
2517 //
2518 // or
2519 //
2520 // c->A::member
2521
2522 // Find results in this base class (and its bases).
2523 ShadowContextRAII Shadow(Visited);
2524 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002525 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002526 }
2527 }
2528
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002529 // Traverse the contexts of Objective-C classes.
2530 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2531 // Traverse categories.
2532 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2533 Category; Category = Category->getNextClassCategory()) {
2534 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002535 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2536 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002537 }
2538
2539 // Traverse protocols.
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002540 for (ObjCInterfaceDecl::all_protocol_iterator
2541 I = IFace->all_referenced_protocol_begin(),
2542 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002543 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002544 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2545 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002546 }
2547
2548 // Traverse the superclass.
2549 if (IFace->getSuperClass()) {
2550 ShadowContextRAII Shadow(Visited);
2551 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002552 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002553 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002554
2555 // If there is an implementation, traverse it. We do this to find
2556 // synthesized ivars.
2557 if (IFace->getImplementation()) {
2558 ShadowContextRAII Shadow(Visited);
2559 LookupVisibleDecls(IFace->getImplementation(), Result,
2560 QualifiedNameLookup, true, Consumer, Visited);
2561 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002562 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2563 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2564 E = Protocol->protocol_end(); I != E; ++I) {
2565 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002566 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2567 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002568 }
2569 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2570 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2571 E = Category->protocol_end(); I != E; ++I) {
2572 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002573 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2574 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002575 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002576
2577 // If there is an implementation, traverse it.
2578 if (Category->getImplementation()) {
2579 ShadowContextRAII Shadow(Visited);
2580 LookupVisibleDecls(Category->getImplementation(), Result,
2581 QualifiedNameLookup, true, Consumer, Visited);
2582 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002583 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002584}
2585
2586static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2587 UnqualUsingDirectiveSet &UDirs,
2588 VisibleDeclConsumer &Consumer,
2589 VisibleDeclsRecord &Visited) {
2590 if (!S)
2591 return;
2592
Douglas Gregor39982192010-08-15 06:18:01 +00002593 if (!S->getEntity() ||
2594 (!S->getParent() &&
2595 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002596 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2597 // Walk through the declarations in this Scope.
2598 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2599 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002600 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002601 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002602 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002603 Visited.add(ND);
2604 }
2605 }
2606 }
2607
Douglas Gregor66230062010-03-15 14:33:29 +00002608 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002609 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002610 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002611 // Look into this scope's declaration context, along with any of its
2612 // parent lookup contexts (e.g., enclosing classes), up to the point
2613 // where we hit the context stored in the next outer scope.
2614 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002615 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor2d435302009-12-30 17:04:44 +00002616
Douglas Gregorea166062010-03-15 15:26:48 +00002617 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002618 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002619 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2620 if (Method->isInstanceMethod()) {
2621 // For instance methods, look for ivars in the method's interface.
2622 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2623 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002624 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2625 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2626 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002627 }
2628
2629 // We've already performed all of the name lookup that we need
2630 // to for Objective-C methods; the next context will be the
2631 // outer scope.
2632 break;
2633 }
2634
Douglas Gregor2d435302009-12-30 17:04:44 +00002635 if (Ctx->isFunctionOrMethod())
2636 continue;
2637
2638 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002639 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002640 }
2641 } else if (!S->getParent()) {
2642 // Look into the translation unit scope. We walk through the translation
2643 // unit's declaration context, because the Scope itself won't have all of
2644 // the declarations if we loaded a precompiled header.
2645 // FIXME: We would like the translation unit's Scope object to point to the
2646 // translation unit, so we don't need this special "if" branch. However,
2647 // doing so would force the normal C++ name-lookup code to look into the
2648 // translation unit decl when the IdentifierInfo chains would suffice.
2649 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002650 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002651 Entity = Result.getSema().Context.getTranslationUnitDecl();
2652 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002653 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002654 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002655
2656 if (Entity) {
2657 // Lookup visible declarations in any namespaces found by using
2658 // directives.
2659 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2660 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2661 for (; UI != UEnd; ++UI)
2662 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002663 Result, /*QualifiedNameLookup=*/false,
2664 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002665 }
2666
2667 // Lookup names in the parent scope.
2668 ShadowContextRAII Shadow(Visited);
2669 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2670}
2671
2672void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002673 VisibleDeclConsumer &Consumer,
2674 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002675 // Determine the set of using directives available during
2676 // unqualified name lookup.
2677 Scope *Initial = S;
2678 UnqualUsingDirectiveSet UDirs;
2679 if (getLangOptions().CPlusPlus) {
2680 // Find the first namespace or translation-unit scope.
2681 while (S && !isNamespaceOrTranslationUnitScope(S))
2682 S = S->getParent();
2683
2684 UDirs.visitScopeChain(Initial, S);
2685 }
2686 UDirs.done();
2687
2688 // Look for visible declarations.
2689 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2690 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002691 if (!IncludeGlobalScope)
2692 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002693 ShadowContextRAII Shadow(Visited);
2694 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2695}
2696
2697void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002698 VisibleDeclConsumer &Consumer,
2699 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002700 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2701 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002702 if (!IncludeGlobalScope)
2703 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002704 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002705 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2706 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002707}
2708
2709//----------------------------------------------------------------------------
2710// Typo correction
2711//----------------------------------------------------------------------------
2712
2713namespace {
2714class TypoCorrectionConsumer : public VisibleDeclConsumer {
2715 /// \brief The name written that is a typo in the source.
2716 llvm::StringRef Typo;
2717
2718 /// \brief The results found that have the smallest edit distance
2719 /// found (so far) with the typo name.
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002720 ///
2721 /// The boolean value indicates whether there is a keyword with this name.
2722 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
Douglas Gregor2d435302009-12-30 17:04:44 +00002723
2724 /// \brief The best edit distance found so far.
2725 unsigned BestEditDistance;
2726
2727public:
2728 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002729 : Typo(Typo->getName()),
2730 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
Douglas Gregor2d435302009-12-30 17:04:44 +00002731
Douglas Gregor09bbc652010-01-14 15:47:35 +00002732 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor57756ea2010-10-14 22:11:03 +00002733 void FoundName(llvm::StringRef Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002734 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002735
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002736 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2737 iterator begin() { return BestResults.begin(); }
2738 iterator end() { return BestResults.end(); }
2739 void erase(iterator I) { BestResults.erase(I); }
2740 unsigned size() const { return BestResults.size(); }
2741 bool empty() const { return BestResults.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002742
Douglas Gregoraf9eb592010-10-15 13:35:25 +00002743 bool &operator[](llvm::StringRef Name) {
2744 return BestResults[Name];
2745 }
2746
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002747 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002748};
2749
2750}
2751
Douglas Gregor09bbc652010-01-14 15:47:35 +00002752void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2753 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002754 // Don't consider hidden names for typo correction.
2755 if (Hiding)
2756 return;
2757
2758 // Only consider entities with identifiers for names, ignoring
2759 // special names (constructors, overloaded operators, selectors,
2760 // etc.).
2761 IdentifierInfo *Name = ND->getIdentifier();
2762 if (!Name)
2763 return;
2764
Douglas Gregor57756ea2010-10-14 22:11:03 +00002765 FoundName(Name->getName());
2766}
2767
2768void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002769 using namespace std;
2770
Douglas Gregor93910a52010-10-19 19:39:10 +00002771 // Use a simple length-based heuristic to determine the minimum possible
2772 // edit distance. If the minimum isn't good enough, bail out early.
2773 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
2774 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
2775 return;
2776
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002777 // Compute an upper bound on the allowable edit distance, so that the
2778 // edit-distance algorithm can short-circuit.
2779 unsigned UpperBound = min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
2780
Douglas Gregor2d435302009-12-30 17:04:44 +00002781 // Compute the edit distance between the typo and the name of this
2782 // entity. If this edit distance is not worse than the best edit
2783 // distance we've seen so far, add it to the list of results.
Douglas Gregorc1fb15e2010-10-19 22:14:33 +00002784 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
Douglas Gregor57756ea2010-10-14 22:11:03 +00002785 if (ED == 0)
2786 return;
2787
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002788 if (ED < BestEditDistance) {
2789 // This result is better than any we've seen before; clear out
2790 // the previous results.
2791 BestResults.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002792 BestEditDistance = ED;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002793 } else if (ED > BestEditDistance) {
2794 // This result is worse than the best results we've seen so far;
2795 // ignore it.
2796 return;
2797 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00002798
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002799 // Add this name to the list of results. By not assigning a value, we
2800 // keep the current value if we've seen this name before (either as a
2801 // keyword or as a declaration), or get the default value (not a keyword)
2802 // if we haven't seen it before.
Douglas Gregor57756ea2010-10-14 22:11:03 +00002803 (void)BestResults[Name];
Douglas Gregor2d435302009-12-30 17:04:44 +00002804}
2805
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002806void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2807 llvm::StringRef Keyword) {
2808 // Compute the edit distance between the typo and this keyword.
2809 // If this edit distance is not worse than the best edit
2810 // distance we've seen so far, add it to the list of results.
2811 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002812 if (ED < BestEditDistance) {
2813 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002814 BestEditDistance = ED;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002815 } else if (ED > BestEditDistance) {
2816 // This result is worse than the best results we've seen so far;
2817 // ignore it.
2818 return;
2819 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002820
Douglas Gregor0afa7f62010-10-14 20:34:08 +00002821 BestResults[Keyword] = true;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002822}
2823
Douglas Gregord507d772010-10-20 03:06:34 +00002824/// \brief Perform name lookup for a possible result for typo correction.
2825static void LookupPotentialTypoResult(Sema &SemaRef,
2826 LookupResult &Res,
2827 IdentifierInfo *Name,
2828 Scope *S, CXXScopeSpec *SS,
2829 DeclContext *MemberContext,
2830 bool EnteringContext,
2831 Sema::CorrectTypoContext CTC) {
2832 Res.suppressDiagnostics();
2833 Res.clear();
2834 Res.setLookupName(Name);
2835 if (MemberContext) {
2836 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
2837 if (CTC == Sema::CTC_ObjCIvarLookup) {
2838 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
2839 Res.addDecl(Ivar);
2840 Res.resolveKind();
2841 return;
2842 }
2843 }
2844
2845 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
2846 Res.addDecl(Prop);
2847 Res.resolveKind();
2848 return;
2849 }
2850 }
2851
2852 SemaRef.LookupQualifiedName(Res, MemberContext);
2853 return;
2854 }
2855
2856 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2857 EnteringContext);
2858
2859 // Fake ivar lookup; this should really be part of
2860 // LookupParsedName.
2861 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2862 if (Method->isInstanceMethod() && Method->getClassInterface() &&
2863 (Res.empty() ||
2864 (Res.isSingleResult() &&
2865 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
2866 if (ObjCIvarDecl *IV
2867 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
2868 Res.addDecl(IV);
2869 Res.resolveKind();
2870 }
2871 }
2872 }
2873}
2874
Douglas Gregor2d435302009-12-30 17:04:44 +00002875/// \brief Try to "correct" a typo in the source code by finding
2876/// visible declarations whose names are similar to the name that was
2877/// present in the source code.
2878///
2879/// \param Res the \c LookupResult structure that contains the name
2880/// that was present in the source code along with the name-lookup
2881/// criteria used to search for the name. On success, this structure
2882/// will contain the results of name lookup.
2883///
2884/// \param S the scope in which name lookup occurs.
2885///
2886/// \param SS the nested-name-specifier that precedes the name we're
2887/// looking for, if present.
2888///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002889/// \param MemberContext if non-NULL, the context in which to look for
2890/// a member access expression.
2891///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002892/// \param EnteringContext whether we're entering the context described by
2893/// the nested-name-specifier SS.
2894///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002895/// \param CTC The context in which typo correction occurs, which impacts the
2896/// set of keywords permitted.
2897///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002898/// \param OPT when non-NULL, the search for visible declarations will
2899/// also walk the protocols in the qualified interfaces of \p OPT.
2900///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002901/// \returns the corrected name if the typo was corrected, otherwise returns an
2902/// empty \c DeclarationName. When a typo was corrected, the result structure
2903/// may contain the results of name lookup for the correct name or it may be
2904/// empty.
2905DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002906 DeclContext *MemberContext,
2907 bool EnteringContext,
2908 CorrectTypoContext CTC,
2909 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00002910 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002911 return DeclarationName();
Ted Kremeneke51136e2010-01-06 00:23:04 +00002912
Douglas Gregor2d435302009-12-30 17:04:44 +00002913 // We only attempt to correct typos for identifiers.
2914 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2915 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002916 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002917
2918 // If the scope specifier itself was invalid, don't try to correct
2919 // typos.
2920 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002921 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002922
2923 // Never try to correct typos during template deduction or
2924 // instantiation.
2925 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002926 return DeclarationName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002927
Douglas Gregor2d435302009-12-30 17:04:44 +00002928 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002929
2930 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor87074f12010-10-20 01:32:02 +00002931 bool IsUnqualifiedLookup = false;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002932 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002933 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002934
2935 // Look in qualified interfaces.
2936 if (OPT) {
2937 for (ObjCObjectPointerType::qual_iterator
2938 I = OPT->qual_begin(), E = OPT->qual_end();
2939 I != E; ++I)
2940 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2941 }
2942 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002943 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2944 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002945 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002946
Douglas Gregor87074f12010-10-20 01:32:02 +00002947 // Provide a stop gap for files that are just seriously broken. Trying
2948 // to correct all typos can turn into a HUGE performance penalty, causing
2949 // some files to take minutes to get rejected by the parser.
2950 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
2951 return DeclarationName();
2952 ++TyposCorrected;
2953
Douglas Gregor2d435302009-12-30 17:04:44 +00002954 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2955 } else {
Douglas Gregor87074f12010-10-20 01:32:02 +00002956 IsUnqualifiedLookup = true;
2957 UnqualifiedTyposCorrectedMap::iterator Cached
2958 = UnqualifiedTyposCorrected.find(Typo);
2959 if (Cached == UnqualifiedTyposCorrected.end()) {
2960 // Provide a stop gap for files that are just seriously broken. Trying
2961 // to correct all typos can turn into a HUGE performance penalty, causing
2962 // some files to take minutes to get rejected by the parser.
2963 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
2964 return DeclarationName();
2965
2966 // For unqualified lookup, look through all of the names that we have
2967 // seen in this translation unit.
2968 for (IdentifierTable::iterator I = Context.Idents.begin(),
2969 IEnd = Context.Idents.end();
2970 I != IEnd; ++I)
2971 Consumer.FoundName(I->getKey());
2972
2973 // Walk through identifiers in external identifier sources.
2974 if (IdentifierInfoLookup *External
Douglas Gregor57756ea2010-10-14 22:11:03 +00002975 = Context.Idents.getExternalIdentifierLookup()) {
Douglas Gregor87074f12010-10-20 01:32:02 +00002976 IdentifierIterator *Iter = External->getIdentifiers();
2977 do {
2978 llvm::StringRef Name = Iter->Next();
2979 if (Name.empty())
2980 break;
Douglas Gregor57756ea2010-10-14 22:11:03 +00002981
Douglas Gregor87074f12010-10-20 01:32:02 +00002982 Consumer.FoundName(Name);
2983 } while (true);
2984 }
2985 } else {
2986 // Use the cached value, unless it's a keyword. In the keyword case, we'll
2987 // end up adding the keyword below.
2988 if (Cached->second.first.empty())
2989 return DeclarationName();
2990
2991 if (!Cached->second.second)
2992 Consumer.FoundName(Cached->second.first);
Douglas Gregor57756ea2010-10-14 22:11:03 +00002993 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002994 }
2995
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002996 // Add context-dependent keywords.
2997 bool WantTypeSpecifiers = false;
2998 bool WantExpressionKeywords = false;
2999 bool WantCXXNamedCasts = false;
3000 bool WantRemainingKeywords = false;
3001 switch (CTC) {
3002 case CTC_Unknown:
3003 WantTypeSpecifiers = true;
3004 WantExpressionKeywords = true;
3005 WantCXXNamedCasts = true;
3006 WantRemainingKeywords = true;
Douglas Gregor5fd04d42010-05-18 16:14:23 +00003007
3008 if (ObjCMethodDecl *Method = getCurMethodDecl())
3009 if (Method->getClassInterface() &&
3010 Method->getClassInterface()->getSuperClass())
3011 Consumer.addKeywordResult(Context, "super");
3012
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003013 break;
3014
3015 case CTC_NoKeywords:
3016 break;
3017
3018 case CTC_Type:
3019 WantTypeSpecifiers = true;
3020 break;
3021
3022 case CTC_ObjCMessageReceiver:
3023 Consumer.addKeywordResult(Context, "super");
3024 // Fall through to handle message receivers like expressions.
3025
3026 case CTC_Expression:
3027 if (getLangOptions().CPlusPlus)
3028 WantTypeSpecifiers = true;
3029 WantExpressionKeywords = true;
3030 // Fall through to get C++ named casts.
3031
3032 case CTC_CXXCasts:
3033 WantCXXNamedCasts = true;
3034 break;
3035
Douglas Gregord507d772010-10-20 03:06:34 +00003036 case CTC_ObjCPropertyLookup:
3037 // FIXME: Add "isa"?
3038 break;
3039
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003040 case CTC_MemberLookup:
3041 if (getLangOptions().CPlusPlus)
3042 Consumer.addKeywordResult(Context, "template");
3043 break;
Douglas Gregord507d772010-10-20 03:06:34 +00003044
3045 case CTC_ObjCIvarLookup:
3046 break;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003047 }
3048
3049 if (WantTypeSpecifiers) {
3050 // Add type-specifier keywords to the set of results.
3051 const char *CTypeSpecs[] = {
3052 "char", "const", "double", "enum", "float", "int", "long", "short",
3053 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3054 "_Complex", "_Imaginary",
3055 // storage-specifiers as well
3056 "extern", "inline", "static", "typedef"
3057 };
3058
3059 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3060 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3061 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
3062
3063 if (getLangOptions().C99)
3064 Consumer.addKeywordResult(Context, "restrict");
3065 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3066 Consumer.addKeywordResult(Context, "bool");
3067
3068 if (getLangOptions().CPlusPlus) {
3069 Consumer.addKeywordResult(Context, "class");
3070 Consumer.addKeywordResult(Context, "typename");
3071 Consumer.addKeywordResult(Context, "wchar_t");
3072
3073 if (getLangOptions().CPlusPlus0x) {
3074 Consumer.addKeywordResult(Context, "char16_t");
3075 Consumer.addKeywordResult(Context, "char32_t");
3076 Consumer.addKeywordResult(Context, "constexpr");
3077 Consumer.addKeywordResult(Context, "decltype");
3078 Consumer.addKeywordResult(Context, "thread_local");
3079 }
3080 }
3081
3082 if (getLangOptions().GNUMode)
3083 Consumer.addKeywordResult(Context, "typeof");
3084 }
3085
Douglas Gregor86ad0852010-05-18 16:30:22 +00003086 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003087 Consumer.addKeywordResult(Context, "const_cast");
3088 Consumer.addKeywordResult(Context, "dynamic_cast");
3089 Consumer.addKeywordResult(Context, "reinterpret_cast");
3090 Consumer.addKeywordResult(Context, "static_cast");
3091 }
3092
3093 if (WantExpressionKeywords) {
3094 Consumer.addKeywordResult(Context, "sizeof");
3095 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3096 Consumer.addKeywordResult(Context, "false");
3097 Consumer.addKeywordResult(Context, "true");
3098 }
3099
3100 if (getLangOptions().CPlusPlus) {
3101 const char *CXXExprs[] = {
3102 "delete", "new", "operator", "throw", "typeid"
3103 };
3104 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3105 for (unsigned I = 0; I != NumCXXExprs; ++I)
3106 Consumer.addKeywordResult(Context, CXXExprs[I]);
3107
3108 if (isa<CXXMethodDecl>(CurContext) &&
3109 cast<CXXMethodDecl>(CurContext)->isInstance())
3110 Consumer.addKeywordResult(Context, "this");
3111
3112 if (getLangOptions().CPlusPlus0x) {
3113 Consumer.addKeywordResult(Context, "alignof");
3114 Consumer.addKeywordResult(Context, "nullptr");
3115 }
3116 }
3117 }
3118
3119 if (WantRemainingKeywords) {
3120 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3121 // Statements.
3122 const char *CStmts[] = {
3123 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3124 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3125 for (unsigned I = 0; I != NumCStmts; ++I)
3126 Consumer.addKeywordResult(Context, CStmts[I]);
3127
3128 if (getLangOptions().CPlusPlus) {
3129 Consumer.addKeywordResult(Context, "catch");
3130 Consumer.addKeywordResult(Context, "try");
3131 }
3132
3133 if (S && S->getBreakParent())
3134 Consumer.addKeywordResult(Context, "break");
3135
3136 if (S && S->getContinueParent())
3137 Consumer.addKeywordResult(Context, "continue");
3138
John McCallaab3e412010-08-25 08:40:02 +00003139 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003140 Consumer.addKeywordResult(Context, "case");
3141 Consumer.addKeywordResult(Context, "default");
3142 }
3143 } else {
3144 if (getLangOptions().CPlusPlus) {
3145 Consumer.addKeywordResult(Context, "namespace");
3146 Consumer.addKeywordResult(Context, "template");
3147 }
3148
3149 if (S && S->isClassScope()) {
3150 Consumer.addKeywordResult(Context, "explicit");
3151 Consumer.addKeywordResult(Context, "friend");
3152 Consumer.addKeywordResult(Context, "mutable");
3153 Consumer.addKeywordResult(Context, "private");
3154 Consumer.addKeywordResult(Context, "protected");
3155 Consumer.addKeywordResult(Context, "public");
3156 Consumer.addKeywordResult(Context, "virtual");
3157 }
3158 }
3159
3160 if (getLangOptions().CPlusPlus) {
3161 Consumer.addKeywordResult(Context, "using");
3162
3163 if (getLangOptions().CPlusPlus0x)
3164 Consumer.addKeywordResult(Context, "static_assert");
3165 }
3166 }
3167
3168 // If we haven't found anything, we're done.
Douglas Gregor87074f12010-10-20 01:32:02 +00003169 if (Consumer.empty()) {
3170 // If this was an unqualified lookup, note that no correction was found.
3171 if (IsUnqualifiedLookup)
3172 (void)UnqualifiedTyposCorrected[Typo];
3173
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003174 return DeclarationName();
Douglas Gregor87074f12010-10-20 01:32:02 +00003175 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003176
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003177 // Make sure that the user typed at least 3 characters for each correction
3178 // made. Otherwise, we don't even both looking at the results.
3179 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor87074f12010-10-20 01:32:02 +00003180 if (ED > 0 && Typo->getName().size() / ED < 3) {
3181 // If this was an unqualified lookup, note that no correction was found.
3182 if (IsUnqualifiedLookup)
3183 (void)UnqualifiedTyposCorrected[Typo];
3184
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003185 return DeclarationName();
Douglas Gregor87074f12010-10-20 01:32:02 +00003186 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003187
3188 // Weed out any names that could not be found by name lookup.
Douglas Gregor26c55782010-10-15 16:49:56 +00003189 bool LastLookupWasAccepted = false;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003190 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3191 IEnd = Consumer.end();
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003192 I != IEnd; /* Increment in loop. */) {
3193 // Keywords are always found.
3194 if (I->second) {
3195 ++I;
3196 continue;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003197 }
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003198
3199 // Perform name lookup on this name.
3200 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
Douglas Gregord507d772010-10-20 03:06:34 +00003201 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3202 EnteringContext, CTC);
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003203
3204 switch (Res.getResultKind()) {
3205 case LookupResult::NotFound:
3206 case LookupResult::NotFoundInCurrentInstantiation:
3207 case LookupResult::Ambiguous:
3208 // We didn't find this name in our scope, or didn't like what we found;
3209 // ignore it.
3210 Res.suppressDiagnostics();
3211 {
3212 TypoCorrectionConsumer::iterator Next = I;
3213 ++Next;
3214 Consumer.erase(I);
3215 I = Next;
3216 }
Douglas Gregor26c55782010-10-15 16:49:56 +00003217 LastLookupWasAccepted = false;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003218 break;
3219
3220 case LookupResult::Found:
3221 case LookupResult::FoundOverloaded:
3222 case LookupResult::FoundUnresolvedValue:
3223 ++I;
Douglas Gregord507d772010-10-20 03:06:34 +00003224 LastLookupWasAccepted = true;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003225 break;
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003226 }
3227
3228 if (Res.isAmbiguous()) {
3229 // We don't deal with ambiguities.
3230 Res.suppressDiagnostics();
3231 Res.clear();
3232 return DeclarationName();
3233 }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003234 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003235
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003236 // If only a single name remains, return that result.
Douglas Gregor26c55782010-10-15 16:49:56 +00003237 if (Consumer.size() == 1) {
3238 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor1f32ebe2010-10-20 01:01:57 +00003239 if (Consumer.begin()->second) {
3240 Res.suppressDiagnostics();
3241 Res.clear();
3242 } else if (!LastLookupWasAccepted) {
Douglas Gregor26c55782010-10-15 16:49:56 +00003243 // Perform name lookup on this name.
Douglas Gregord507d772010-10-20 03:06:34 +00003244 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3245 EnteringContext, CTC);
Douglas Gregor26c55782010-10-15 16:49:56 +00003246 }
3247
Douglas Gregor87074f12010-10-20 01:32:02 +00003248 // Record the correction for unqualified lookup.
3249 if (IsUnqualifiedLookup)
3250 UnqualifiedTyposCorrected[Typo]
Douglas Gregord507d772010-10-20 03:06:34 +00003251 = std::make_pair(Name->getName(), Consumer.begin()->second);
Douglas Gregor87074f12010-10-20 01:32:02 +00003252
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003253 return &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor26c55782010-10-15 16:49:56 +00003254 }
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003255 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
3256 && Consumer["super"]) {
3257 // Prefix 'super' when we're completing in a message-receiver
3258 // context.
3259 Res.suppressDiagnostics();
3260 Res.clear();
Douglas Gregor87074f12010-10-20 01:32:02 +00003261
3262 // Record the correction for unqualified lookup.
3263 if (IsUnqualifiedLookup)
3264 UnqualifiedTyposCorrected[Typo]
Douglas Gregord507d772010-10-20 03:06:34 +00003265 = std::make_pair("super", Consumer.begin()->second);
Douglas Gregor87074f12010-10-20 01:32:02 +00003266
Douglas Gregoraf9eb592010-10-15 13:35:25 +00003267 return &Context.Idents.get("super");
3268 }
3269
Douglas Gregor0afa7f62010-10-14 20:34:08 +00003270 Res.suppressDiagnostics();
3271 Res.setLookupName(Typo);
Douglas Gregor2d435302009-12-30 17:04:44 +00003272 Res.clear();
Douglas Gregor87074f12010-10-20 01:32:02 +00003273 // Record the correction for unqualified lookup.
3274 if (IsUnqualifiedLookup)
3275 (void)UnqualifiedTyposCorrected[Typo];
3276
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003277 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003278}