blob: bb267e3733a467750801dea557c006f8ab3a8e0b [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"
John McCall6538c932009-10-10 05:48:19 +000034#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2d435302009-12-30 17:04:44 +000035#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000036#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000037#include <vector>
38#include <iterator>
39#include <utility>
40#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000041
42using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000043using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000044
John McCallf6c8a4e2009-11-10 07:01:13 +000045namespace {
46 class UnqualUsingEntry {
47 const DeclContext *Nominated;
48 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000049
John McCallf6c8a4e2009-11-10 07:01:13 +000050 public:
51 UnqualUsingEntry(const DeclContext *Nominated,
52 const DeclContext *CommonAncestor)
53 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
54 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000055
John McCallf6c8a4e2009-11-10 07:01:13 +000056 const DeclContext *getCommonAncestor() const {
57 return CommonAncestor;
58 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000059
John McCallf6c8a4e2009-11-10 07:01:13 +000060 const DeclContext *getNominatedNamespace() const {
61 return Nominated;
62 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000063
John McCallf6c8a4e2009-11-10 07:01:13 +000064 // Sort by the pointer value of the common ancestor.
65 struct Comparator {
66 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
67 return L.getCommonAncestor() < R.getCommonAncestor();
68 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000069
John McCallf6c8a4e2009-11-10 07:01:13 +000070 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
71 return E.getCommonAncestor() < DC;
72 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000073
John McCallf6c8a4e2009-11-10 07:01:13 +000074 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
75 return DC < E.getCommonAncestor();
76 }
77 };
78 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000079
John McCallf6c8a4e2009-11-10 07:01:13 +000080 /// A collection of using directives, as used by C++ unqualified
81 /// lookup.
82 class UnqualUsingDirectiveSet {
83 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000084
John McCallf6c8a4e2009-11-10 07:01:13 +000085 ListTy list;
86 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000087
John McCallf6c8a4e2009-11-10 07:01:13 +000088 public:
89 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000090
John McCallf6c8a4e2009-11-10 07:01:13 +000091 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
92 // C++ [namespace.udir]p1:
93 // During unqualified name lookup, the names appear as if they
94 // were declared in the nearest enclosing namespace which contains
95 // both the using-directive and the nominated namespace.
96 DeclContext *InnermostFileDC
97 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
98 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000099
John McCallf6c8a4e2009-11-10 07:01:13 +0000100 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000101 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
102 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
103 visit(Ctx, EffectiveDC);
104 } else {
105 Scope::udir_iterator I = S->using_directives_begin(),
106 End = S->using_directives_end();
107
108 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000109 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000110 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000111 }
112 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000113
114 // Visits a context and collect all of its using directives
115 // recursively. Treats all using directives as if they were
116 // declared in the context.
117 //
118 // A given context is only every visited once, so it is important
119 // that contexts be visited from the inside out in order to get
120 // the effective DCs right.
121 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
122 if (!visited.insert(DC))
123 return;
124
125 addUsingDirectives(DC, EffectiveDC);
126 }
127
128 // Visits a using directive and collects all of its using
129 // directives recursively. Treats all using directives as if they
130 // were declared in the effective DC.
131 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
132 DeclContext *NS = UD->getNominatedNamespace();
133 if (!visited.insert(NS))
134 return;
135
136 addUsingDirective(UD, EffectiveDC);
137 addUsingDirectives(NS, EffectiveDC);
138 }
139
140 // Adds all the using directives in a context (and those nominated
141 // by its using directives, transitively) as if they appeared in
142 // the given effective context.
143 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
144 llvm::SmallVector<DeclContext*,4> queue;
145 while (true) {
146 DeclContext::udir_iterator I, End;
147 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
148 UsingDirectiveDecl *UD = *I;
149 DeclContext *NS = UD->getNominatedNamespace();
150 if (visited.insert(NS)) {
151 addUsingDirective(UD, EffectiveDC);
152 queue.push_back(NS);
153 }
154 }
155
156 if (queue.empty())
157 return;
158
159 DC = queue.back();
160 queue.pop_back();
161 }
162 }
163
164 // Add a using directive as if it had been declared in the given
165 // context. This helps implement C++ [namespace.udir]p3:
166 // The using-directive is transitive: if a scope contains a
167 // using-directive that nominates a second namespace that itself
168 // contains using-directives, the effect is as if the
169 // using-directives from the second namespace also appeared in
170 // the first.
171 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
172 // Find the common ancestor between the effective context and
173 // the nominated namespace.
174 DeclContext *Common = UD->getNominatedNamespace();
175 while (!Common->Encloses(EffectiveDC))
176 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000177 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000178
179 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
180 }
181
182 void done() {
183 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
184 }
185
186 typedef ListTy::iterator iterator;
187 typedef ListTy::const_iterator const_iterator;
188
189 iterator begin() { return list.begin(); }
190 iterator end() { return list.end(); }
191 const_iterator begin() const { return list.begin(); }
192 const_iterator end() const { return list.end(); }
193
194 std::pair<const_iterator,const_iterator>
195 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000196 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000197 UnqualUsingEntry::Comparator());
198 }
199 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000200}
201
Douglas Gregor889ceb72009-02-03 19:21:40 +0000202// Retrieve the set of identifier namespaces that correspond to a
203// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000204static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
205 bool CPlusPlus,
206 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000207 unsigned IDNS = 0;
208 switch (NameKind) {
209 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000210 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000211 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000212 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000213 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCallea305ed2009-12-18 10:40:03 +0000214 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
215 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000216 break;
217
John McCallb9467b62010-04-24 01:30:58 +0000218 case Sema::LookupOperatorName:
219 // Operator lookup is its own crazy thing; it is not the same
220 // as (e.g.) looking up an operator name for redeclaration.
221 assert(!Redeclaration && "cannot do redeclaration operator lookup");
222 IDNS = Decl::IDNS_NonMemberOperator;
223 break;
224
Douglas Gregor889ceb72009-02-03 19:21:40 +0000225 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000226 if (CPlusPlus) {
227 IDNS = Decl::IDNS_Type;
228
229 // When looking for a redeclaration of a tag name, we add:
230 // 1) TagFriend to find undeclared friend decls
231 // 2) Namespace because they can't "overload" with tag decls.
232 // 3) Tag because it includes class templates, which can't
233 // "overload" with tag decls.
234 if (Redeclaration)
235 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
236 } else {
237 IDNS = Decl::IDNS_Tag;
238 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000239 break;
240
241 case Sema::LookupMemberName:
242 IDNS = Decl::IDNS_Member;
243 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000244 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000245 break;
246
247 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000248 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
249 break;
250
Douglas Gregor889ceb72009-02-03 19:21:40 +0000251 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000252 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000253 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000254
John McCall84d87672009-12-10 09:41:52 +0000255 case Sema::LookupUsingDeclName:
256 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
257 | Decl::IDNS_Member | Decl::IDNS_Using;
258 break;
259
Douglas Gregor79947a22009-04-24 00:11:27 +0000260 case Sema::LookupObjCProtocolName:
261 IDNS = Decl::IDNS_ObjCProtocol;
262 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000263
264 case Sema::LookupAnyName:
265 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
266 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
267 | Decl::IDNS_Type;
268 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000269 }
270 return IDNS;
271}
272
John McCallea305ed2009-12-18 10:40:03 +0000273void LookupResult::configure() {
274 IDNS = getIDNS(LookupKind,
275 SemaRef.getLangOptions().CPlusPlus,
276 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000277
278 // If we're looking for one of the allocation or deallocation
279 // operators, make sure that the implicitly-declared new and delete
280 // operators can be found.
281 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000282 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000283 case OO_New:
284 case OO_Delete:
285 case OO_Array_New:
286 case OO_Array_Delete:
287 SemaRef.DeclareGlobalNewDelete();
288 break;
289
290 default:
291 break;
292 }
293 }
John McCallea305ed2009-12-18 10:40:03 +0000294}
295
John McCall19c1bfd2010-08-25 05:32:35 +0000296#ifndef NDEBUG
297void LookupResult::sanity() const {
298 assert(ResultKind != NotFound || Decls.size() == 0);
299 assert(ResultKind != Found || Decls.size() == 1);
300 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
301 (Decls.size() == 1 &&
302 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
303 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
304 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
305 (Decls.size() == 1 && Ambiguity == AmbiguousBaseSubobjects));
306 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 Gregord0d2ee02010-01-15 01:44:47 +00001241/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001242///
1243/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1244/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001245/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001246///
1247/// Different lookup criteria can find different names. For example, a
1248/// particular scope can have both a struct and a function of the same
1249/// name, and each can be found by certain lookup criteria. For more
1250/// information about lookup criteria, see the documentation for the
1251/// class LookupCriteria.
1252///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001253/// \param R captures both the lookup criteria and any lookup results found.
1254///
1255/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001256/// search. If the lookup criteria permits, name lookup may also search
1257/// in the parent contexts or (for C++ classes) base classes.
1258///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001259/// \param InUnqualifiedLookup true if this is qualified name lookup that
1260/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001261///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001262/// \returns true if lookup succeeded, false if it failed.
1263bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1264 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001265 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001266
John McCall27b18f82009-11-17 02:14:36 +00001267 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001268 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001269
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001270 // Make sure that the declaration context is complete.
1271 assert((!isa<TagDecl>(LookupCtx) ||
1272 LookupCtx->isDependentContext() ||
1273 cast<TagDecl>(LookupCtx)->isDefinition() ||
1274 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1275 ->isBeingDefined()) &&
1276 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001277
Douglas Gregor34074322009-01-14 22:20:51 +00001278 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001279 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001280 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001281 if (isa<CXXRecordDecl>(LookupCtx))
1282 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001283 return true;
1284 }
Douglas Gregor34074322009-01-14 22:20:51 +00001285
John McCall6538c932009-10-10 05:48:19 +00001286 // Don't descend into implied contexts for redeclarations.
1287 // C++98 [namespace.qual]p6:
1288 // In a declaration for a namespace member in which the
1289 // declarator-id is a qualified-id, given that the qualified-id
1290 // for the namespace member has the form
1291 // nested-name-specifier unqualified-id
1292 // the unqualified-id shall name a member of the namespace
1293 // designated by the nested-name-specifier.
1294 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001295 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001296 return false;
1297
John McCall27b18f82009-11-17 02:14:36 +00001298 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001299 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001300 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001301
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001302 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001303 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001304 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001305 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001306 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001307
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001308 // If we're performing qualified name lookup into a dependent class,
1309 // then we are actually looking into a current instantiation. If we have any
1310 // dependent base classes, then we either have to delay lookup until
1311 // template instantiation time (at which point all bases will be available)
1312 // or we have to fail.
1313 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1314 LookupRec->hasAnyDependentBases()) {
1315 R.setNotFoundInCurrentInstantiation();
1316 return false;
1317 }
1318
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001319 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001320 CXXBasePaths Paths;
1321 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001322
1323 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001324 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001325 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001326 case LookupOrdinaryName:
1327 case LookupMemberName:
1328 case LookupRedeclarationWithLinkage:
1329 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1330 break;
1331
1332 case LookupTagName:
1333 BaseCallback = &CXXRecordDecl::FindTagMember;
1334 break;
John McCall84d87672009-12-10 09:41:52 +00001335
Douglas Gregor39982192010-08-15 06:18:01 +00001336 case LookupAnyName:
1337 BaseCallback = &LookupAnyMember;
1338 break;
1339
John McCall84d87672009-12-10 09:41:52 +00001340 case LookupUsingDeclName:
1341 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001342
1343 case LookupOperatorName:
1344 case LookupNamespaceName:
1345 case LookupObjCProtocolName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001346 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001347 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001348
1349 case LookupNestedNameSpecifierName:
1350 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1351 break;
1352 }
1353
John McCall27b18f82009-11-17 02:14:36 +00001354 if (!LookupRec->lookupInBases(BaseCallback,
1355 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001356 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001357
John McCall553c0792010-01-23 00:46:32 +00001358 R.setNamingClass(LookupRec);
1359
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001360 // C++ [class.member.lookup]p2:
1361 // [...] If the resulting set of declarations are not all from
1362 // sub-objects of the same type, or the set has a nonstatic member
1363 // and includes members from distinct sub-objects, there is an
1364 // ambiguity and the program is ill-formed. Otherwise that set is
1365 // the result of the lookup.
1366 // FIXME: support using declarations!
1367 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001368 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001369 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001370 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001371 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001372 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001373
John McCall401982f2010-01-20 21:53:11 +00001374 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1375 // across all paths.
1376 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1377
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001378 // Determine whether we're looking at a distinct sub-object or not.
1379 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001380 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001381 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1382 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001383 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001384 != Context.getCanonicalType(PathElement.Base->getType())) {
1385 // We found members of the given name in two subobjects of
1386 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001387 R.setAmbiguousBaseSubobjectTypes(Paths);
1388 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001389 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1390 // We have a different subobject of the same type.
1391
1392 // C++ [class.member.lookup]p5:
1393 // A static member, a nested type or an enumerator defined in
1394 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001395 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001396 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001397 if (isa<VarDecl>(FirstDecl) ||
1398 isa<TypeDecl>(FirstDecl) ||
1399 isa<EnumConstantDecl>(FirstDecl))
1400 continue;
1401
1402 if (isa<CXXMethodDecl>(FirstDecl)) {
1403 // Determine whether all of the methods are static.
1404 bool AllMethodsAreStatic = true;
1405 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1406 Func != Path->Decls.second; ++Func) {
1407 if (!isa<CXXMethodDecl>(*Func)) {
1408 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1409 break;
1410 }
1411
1412 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1413 AllMethodsAreStatic = false;
1414 break;
1415 }
1416 }
1417
1418 if (AllMethodsAreStatic)
1419 continue;
1420 }
1421
1422 // We have found a nonstatic member name in multiple, distinct
1423 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001424 R.setAmbiguousBaseSubobjects(Paths);
1425 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001426 }
1427 }
1428
1429 // Lookup in a base class succeeded; return these results.
1430
John McCall9f3059a2009-10-09 21:13:30 +00001431 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001432 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1433 NamedDecl *D = *I;
1434 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1435 D->getAccess());
1436 R.addDecl(D, AS);
1437 }
John McCall9f3059a2009-10-09 21:13:30 +00001438 R.resolveKind();
1439 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001440}
1441
1442/// @brief Performs name lookup for a name that was parsed in the
1443/// source code, and may contain a C++ scope specifier.
1444///
1445/// This routine is a convenience routine meant to be called from
1446/// contexts that receive a name and an optional C++ scope specifier
1447/// (e.g., "N::M::x"). It will then perform either qualified or
1448/// unqualified name lookup (with LookupQualifiedName or LookupName,
1449/// respectively) on the given name and return those results.
1450///
1451/// @param S The scope from which unqualified name lookup will
1452/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001453///
Douglas Gregore861bac2009-08-25 22:51:20 +00001454/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001455///
1456/// @param Name The name of the entity that name lookup will
1457/// search for.
1458///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001459/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001460/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001461/// C library functions (like "malloc") are implicitly declared.
1462///
Douglas Gregore861bac2009-08-25 22:51:20 +00001463/// @param EnteringContext Indicates whether we are going to enter the
1464/// context of the scope-specifier SS (if present).
1465///
John McCall9f3059a2009-10-09 21:13:30 +00001466/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001467bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001468 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001469 if (SS && SS->isInvalid()) {
1470 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001471 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001472 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001473 }
Mike Stump11289f42009-09-09 15:08:12 +00001474
Douglas Gregore861bac2009-08-25 22:51:20 +00001475 if (SS && SS->isSet()) {
1476 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001477 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001478 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001479 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001480 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001481
John McCall27b18f82009-11-17 02:14:36 +00001482 R.setContextRange(SS->getRange());
1483
1484 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001485 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001486
Douglas Gregore861bac2009-08-25 22:51:20 +00001487 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001488 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001489 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001490 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001491 }
1492
Mike Stump11289f42009-09-09 15:08:12 +00001493 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001494 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001495}
1496
Douglas Gregor889ceb72009-02-03 19:21:40 +00001497
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001498/// @brief Produce a diagnostic describing the ambiguity that resulted
1499/// from name lookup.
1500///
1501/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001502///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001503/// @param Name The name of the entity that name lookup was
1504/// searching for.
1505///
1506/// @param NameLoc The location of the name within the source code.
1507///
1508/// @param LookupRange A source range that provides more
1509/// source-location information concerning the lookup itself. For
1510/// example, this range might highlight a nested-name-specifier that
1511/// precedes the name.
1512///
1513/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001514bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001515 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1516
John McCall27b18f82009-11-17 02:14:36 +00001517 DeclarationName Name = Result.getLookupName();
1518 SourceLocation NameLoc = Result.getNameLoc();
1519 SourceRange LookupRange = Result.getContextRange();
1520
John McCall6538c932009-10-10 05:48:19 +00001521 switch (Result.getAmbiguityKind()) {
1522 case LookupResult::AmbiguousBaseSubobjects: {
1523 CXXBasePaths *Paths = Result.getBasePaths();
1524 QualType SubobjectType = Paths->front().back().Base->getType();
1525 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1526 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1527 << LookupRange;
1528
1529 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1530 while (isa<CXXMethodDecl>(*Found) &&
1531 cast<CXXMethodDecl>(*Found)->isStatic())
1532 ++Found;
1533
1534 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1535
1536 return true;
1537 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001538
John McCall6538c932009-10-10 05:48:19 +00001539 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001540 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1541 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001542
1543 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001544 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001545 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1546 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001547 Path != PathEnd; ++Path) {
1548 Decl *D = *Path->Decls.first;
1549 if (DeclsPrinted.insert(D).second)
1550 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1551 }
1552
Douglas Gregor1c846b02009-01-16 00:38:09 +00001553 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001554 }
1555
John McCall6538c932009-10-10 05:48:19 +00001556 case LookupResult::AmbiguousTagHiding: {
1557 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001558
John McCall6538c932009-10-10 05:48:19 +00001559 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1560
1561 LookupResult::iterator DI, DE = Result.end();
1562 for (DI = Result.begin(); DI != DE; ++DI)
1563 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1564 TagDecls.insert(TD);
1565 Diag(TD->getLocation(), diag::note_hidden_tag);
1566 }
1567
1568 for (DI = Result.begin(); DI != DE; ++DI)
1569 if (!isa<TagDecl>(*DI))
1570 Diag((*DI)->getLocation(), diag::note_hiding_object);
1571
1572 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001573 LookupResult::Filter F = Result.makeFilter();
1574 while (F.hasNext()) {
1575 if (TagDecls.count(F.next()))
1576 F.erase();
1577 }
1578 F.done();
John McCall6538c932009-10-10 05:48:19 +00001579
1580 return true;
1581 }
1582
1583 case LookupResult::AmbiguousReference: {
1584 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001585
John McCall6538c932009-10-10 05:48:19 +00001586 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1587 for (; DI != DE; ++DI)
1588 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001589
John McCall6538c932009-10-10 05:48:19 +00001590 return true;
1591 }
1592 }
1593
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001594 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001595 return true;
1596}
Douglas Gregore254f902009-02-04 00:32:51 +00001597
John McCallf24d7bb2010-05-28 18:45:08 +00001598namespace {
1599 struct AssociatedLookup {
1600 AssociatedLookup(Sema &S,
1601 Sema::AssociatedNamespaceSet &Namespaces,
1602 Sema::AssociatedClassSet &Classes)
1603 : S(S), Namespaces(Namespaces), Classes(Classes) {
1604 }
1605
1606 Sema &S;
1607 Sema::AssociatedNamespaceSet &Namespaces;
1608 Sema::AssociatedClassSet &Classes;
1609 };
1610}
1611
Mike Stump11289f42009-09-09 15:08:12 +00001612static void
John McCallf24d7bb2010-05-28 18:45:08 +00001613addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001614
Douglas Gregor8b895222010-04-30 07:08:38 +00001615static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1616 DeclContext *Ctx) {
1617 // Add the associated namespace for this class.
1618
1619 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1620 // be a locally scoped record.
1621
1622 while (Ctx->isRecord() || Ctx->isTransparentContext())
1623 Ctx = Ctx->getParent();
1624
John McCallc7e8e792009-08-07 22:18:02 +00001625 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001626 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001627}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001628
Mike Stump11289f42009-09-09 15:08:12 +00001629// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001630// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001631static void
John McCallf24d7bb2010-05-28 18:45:08 +00001632addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1633 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001634 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001635 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001636 switch (Arg.getKind()) {
1637 case TemplateArgument::Null:
1638 break;
Mike Stump11289f42009-09-09 15:08:12 +00001639
Douglas Gregor197e5f72009-07-08 07:51:57 +00001640 case TemplateArgument::Type:
1641 // [...] the namespaces and classes associated with the types of the
1642 // template arguments provided for template type parameters (excluding
1643 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001644 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001645 break;
Mike Stump11289f42009-09-09 15:08:12 +00001646
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001647 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001648 // [...] the namespaces in which any template template arguments are
1649 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001650 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001651 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001652 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001653 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001654 DeclContext *Ctx = ClassTemplate->getDeclContext();
1655 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001656 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001657 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001658 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001659 }
1660 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001661 }
1662
1663 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001664 case TemplateArgument::Integral:
1665 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001666 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001667 // associated namespaces. ]
1668 break;
Mike Stump11289f42009-09-09 15:08:12 +00001669
Douglas Gregor197e5f72009-07-08 07:51:57 +00001670 case TemplateArgument::Pack:
1671 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1672 PEnd = Arg.pack_end();
1673 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001674 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001675 break;
1676 }
1677}
1678
Douglas Gregore254f902009-02-04 00:32:51 +00001679// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001680// argument-dependent lookup with an argument of class type
1681// (C++ [basic.lookup.koenig]p2).
1682static void
John McCallf24d7bb2010-05-28 18:45:08 +00001683addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1684 CXXRecordDecl *Class) {
1685
1686 // Just silently ignore anything whose name is __va_list_tag.
1687 if (Class->getDeclName() == Result.S.VAListTagName)
1688 return;
1689
Douglas Gregore254f902009-02-04 00:32:51 +00001690 // C++ [basic.lookup.koenig]p2:
1691 // [...]
1692 // -- If T is a class type (including unions), its associated
1693 // classes are: the class itself; the class of which it is a
1694 // member, if any; and its direct and indirect base
1695 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001696 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001697
1698 // Add the class of which it is a member, if any.
1699 DeclContext *Ctx = Class->getDeclContext();
1700 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001701 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001702 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001703 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001704
Douglas Gregore254f902009-02-04 00:32:51 +00001705 // Add the class itself. If we've already seen this class, we don't
1706 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001707 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001708 return;
1709
Mike Stump11289f42009-09-09 15:08:12 +00001710 // -- If T is a template-id, its associated namespaces and classes are
1711 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001712 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001713 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001714 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001715 // namespaces in which any template template arguments are defined; and
1716 // the classes in which any member templates used as template template
1717 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001718 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001719 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001720 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1721 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1722 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001723 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001724 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001725 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001726
Douglas Gregor197e5f72009-07-08 07:51:57 +00001727 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1728 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001729 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001730 }
Mike Stump11289f42009-09-09 15:08:12 +00001731
John McCall67da35c2010-02-04 22:26:26 +00001732 // Only recurse into base classes for complete types.
1733 if (!Class->hasDefinition()) {
1734 // FIXME: we might need to instantiate templates here
1735 return;
1736 }
1737
Douglas Gregore254f902009-02-04 00:32:51 +00001738 // Add direct and indirect base classes along with their associated
1739 // namespaces.
1740 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1741 Bases.push_back(Class);
1742 while (!Bases.empty()) {
1743 // Pop this class off the stack.
1744 Class = Bases.back();
1745 Bases.pop_back();
1746
1747 // Visit the base classes.
1748 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1749 BaseEnd = Class->bases_end();
1750 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001751 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001752 // In dependent contexts, we do ADL twice, and the first time around,
1753 // the base type might be a dependent TemplateSpecializationType, or a
1754 // TemplateTypeParmType. If that happens, simply ignore it.
1755 // FIXME: If we want to support export, we probably need to add the
1756 // namespace of the template in a TemplateSpecializationType, or even
1757 // the classes and namespaces of known non-dependent arguments.
1758 if (!BaseType)
1759 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001760 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001761 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001762 // Find the associated namespace for this base class.
1763 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001764 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001765
1766 // Make sure we visit the bases of this base class.
1767 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1768 Bases.push_back(BaseDecl);
1769 }
1770 }
1771 }
1772}
1773
1774// \brief Add the associated classes and namespaces for
1775// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001776// (C++ [basic.lookup.koenig]p2).
1777static void
John McCallf24d7bb2010-05-28 18:45:08 +00001778addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001779 // C++ [basic.lookup.koenig]p2:
1780 //
1781 // For each argument type T in the function call, there is a set
1782 // of zero or more associated namespaces and a set of zero or more
1783 // associated classes to be considered. The sets of namespaces and
1784 // classes is determined entirely by the types of the function
1785 // arguments (and the namespace of any template template
1786 // argument). Typedef names and using-declarations used to specify
1787 // the types do not contribute to this set. The sets of namespaces
1788 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001789
John McCall0af3d3b2010-05-28 06:08:54 +00001790 llvm::SmallVector<const Type *, 16> Queue;
1791 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1792
Douglas Gregore254f902009-02-04 00:32:51 +00001793 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001794 switch (T->getTypeClass()) {
1795
1796#define TYPE(Class, Base)
1797#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1798#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1799#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1800#define ABSTRACT_TYPE(Class, Base)
1801#include "clang/AST/TypeNodes.def"
1802 // T is canonical. We can also ignore dependent types because
1803 // we don't need to do ADL at the definition point, but if we
1804 // wanted to implement template export (or if we find some other
1805 // use for associated classes and namespaces...) this would be
1806 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001807 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001808
John McCall0af3d3b2010-05-28 06:08:54 +00001809 // -- If T is a pointer to U or an array of U, its associated
1810 // namespaces and classes are those associated with U.
1811 case Type::Pointer:
1812 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1813 continue;
1814 case Type::ConstantArray:
1815 case Type::IncompleteArray:
1816 case Type::VariableArray:
1817 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1818 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001819
John McCall0af3d3b2010-05-28 06:08:54 +00001820 // -- If T is a fundamental type, its associated sets of
1821 // namespaces and classes are both empty.
1822 case Type::Builtin:
1823 break;
1824
1825 // -- If T is a class type (including unions), its associated
1826 // classes are: the class itself; the class of which it is a
1827 // member, if any; and its direct and indirect base
1828 // classes. Its associated namespaces are the namespaces in
1829 // which its associated classes are defined.
1830 case Type::Record: {
1831 CXXRecordDecl *Class
1832 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001833 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001834 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001835 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001836
John McCall0af3d3b2010-05-28 06:08:54 +00001837 // -- If T is an enumeration type, its associated namespace is
1838 // the namespace in which it is defined. If it is class
1839 // member, its associated class is the member’s class; else
1840 // it has no associated class.
1841 case Type::Enum: {
1842 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001843
John McCall0af3d3b2010-05-28 06:08:54 +00001844 DeclContext *Ctx = Enum->getDeclContext();
1845 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001846 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001847
John McCall0af3d3b2010-05-28 06:08:54 +00001848 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001849 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001850
John McCall0af3d3b2010-05-28 06:08:54 +00001851 break;
1852 }
1853
1854 // -- If T is a function type, its associated namespaces and
1855 // classes are those associated with the function parameter
1856 // types and those associated with the return type.
1857 case Type::FunctionProto: {
1858 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1859 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1860 ArgEnd = Proto->arg_type_end();
1861 Arg != ArgEnd; ++Arg)
1862 Queue.push_back(Arg->getTypePtr());
1863 // fallthrough
1864 }
1865 case Type::FunctionNoProto: {
1866 const FunctionType *FnType = cast<FunctionType>(T);
1867 T = FnType->getResultType().getTypePtr();
1868 continue;
1869 }
1870
1871 // -- If T is a pointer to a member function of a class X, its
1872 // associated namespaces and classes are those associated
1873 // with the function parameter types and return type,
1874 // together with those associated with X.
1875 //
1876 // -- If T is a pointer to a data member of class X, its
1877 // associated namespaces and classes are those associated
1878 // with the member type together with those associated with
1879 // X.
1880 case Type::MemberPointer: {
1881 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1882
1883 // Queue up the class type into which this points.
1884 Queue.push_back(MemberPtr->getClass());
1885
1886 // And directly continue with the pointee type.
1887 T = MemberPtr->getPointeeType().getTypePtr();
1888 continue;
1889 }
1890
1891 // As an extension, treat this like a normal pointer.
1892 case Type::BlockPointer:
1893 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1894 continue;
1895
1896 // References aren't covered by the standard, but that's such an
1897 // obvious defect that we cover them anyway.
1898 case Type::LValueReference:
1899 case Type::RValueReference:
1900 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1901 continue;
1902
1903 // These are fundamental types.
1904 case Type::Vector:
1905 case Type::ExtVector:
1906 case Type::Complex:
1907 break;
1908
1909 // These are ignored by ADL.
1910 case Type::ObjCObject:
1911 case Type::ObjCInterface:
1912 case Type::ObjCObjectPointer:
1913 break;
1914 }
1915
1916 if (Queue.empty()) break;
1917 T = Queue.back();
1918 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001919 }
Douglas Gregore254f902009-02-04 00:32:51 +00001920}
1921
1922/// \brief Find the associated classes and namespaces for
1923/// argument-dependent lookup for a call with the given set of
1924/// arguments.
1925///
1926/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001927/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001928/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001929void
Douglas Gregore254f902009-02-04 00:32:51 +00001930Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1931 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001932 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001933 AssociatedNamespaces.clear();
1934 AssociatedClasses.clear();
1935
John McCallf24d7bb2010-05-28 18:45:08 +00001936 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1937
Douglas Gregore254f902009-02-04 00:32:51 +00001938 // C++ [basic.lookup.koenig]p2:
1939 // For each argument type T in the function call, there is a set
1940 // of zero or more associated namespaces and a set of zero or more
1941 // associated classes to be considered. The sets of namespaces and
1942 // classes is determined entirely by the types of the function
1943 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001944 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001945 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1946 Expr *Arg = Args[ArgIdx];
1947
1948 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00001949 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001950 continue;
1951 }
1952
1953 // [...] In addition, if the argument is the name or address of a
1954 // set of overloaded functions and/or function templates, its
1955 // associated classes and namespaces are the union of those
1956 // associated with each of the members of the set: the namespace
1957 // in which the function or function template is defined and the
1958 // classes and namespaces associated with its (non-dependent)
1959 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001960 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001961 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00001962 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00001963 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001964
John McCallf24d7bb2010-05-28 18:45:08 +00001965 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1966 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00001967
John McCallf24d7bb2010-05-28 18:45:08 +00001968 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1969 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001970 // Look through any using declarations to find the underlying function.
1971 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001972
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001973 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1974 if (!FDecl)
1975 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001976
1977 // Add the classes and namespaces associated with the parameter
1978 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00001979 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001980 }
1981 }
1982}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001983
1984/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1985/// an acceptable non-member overloaded operator for a call whose
1986/// arguments have types T1 (and, if non-empty, T2). This routine
1987/// implements the check in C++ [over.match.oper]p3b2 concerning
1988/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001989static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001990IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1991 QualType T1, QualType T2,
1992 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001993 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1994 return true;
1995
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001996 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1997 return true;
1998
John McCall9dd450b2009-09-21 23:43:11 +00001999 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002000 if (Proto->getNumArgs() < 1)
2001 return false;
2002
2003 if (T1->isEnumeralType()) {
2004 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002005 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002006 return true;
2007 }
2008
2009 if (Proto->getNumArgs() < 2)
2010 return false;
2011
2012 if (!T2.isNull() && T2->isEnumeralType()) {
2013 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002014 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002015 return true;
2016 }
2017
2018 return false;
2019}
2020
John McCall5cebab12009-11-18 07:57:50 +00002021NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002022 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002023 LookupNameKind NameKind,
2024 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002025 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002026 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002027 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002028}
2029
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002030/// \brief Find the protocol with the given name, if any.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002031ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2032 SourceLocation IdLoc) {
2033 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2034 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002035 return cast_or_null<ObjCProtocolDecl>(D);
2036}
2037
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002038void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002039 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002040 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002041 // C++ [over.match.oper]p3:
2042 // -- The set of non-member candidates is the result of the
2043 // unqualified lookup of operator@ in the context of the
2044 // expression according to the usual rules for name lookup in
2045 // unqualified function calls (3.4.2) except that all member
2046 // functions are ignored. However, if no operand has a class
2047 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002048 // that have a first parameter of type T1 or "reference to
2049 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002050 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002051 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002052 // when T2 is an enumeration type, are candidate functions.
2053 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002054 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2055 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002056
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002057 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2058
John McCall9f3059a2009-10-09 21:13:30 +00002059 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002060 return;
2061
2062 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2063 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002064 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2065 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002066 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002067 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002068 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002069 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002070 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002071 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002072 // later?
2073 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002074 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002075 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002076 }
2077}
2078
Douglas Gregor52b72822010-07-02 23:12:18 +00002079/// \brief Look up the constructors for the given class.
2080DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +00002081 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002082 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2083 if (!Class->hasDeclaredDefaultConstructor())
2084 DeclareImplicitDefaultConstructor(Class);
2085 if (!Class->hasDeclaredCopyConstructor())
2086 DeclareImplicitCopyConstructor(Class);
2087 }
Douglas Gregora6d69502010-07-02 23:41:54 +00002088
Douglas Gregor52b72822010-07-02 23:12:18 +00002089 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2090 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2091 return Class->lookup(Name);
2092}
2093
Douglas Gregore71edda2010-07-01 22:47:18 +00002094/// \brief Look for the destructor of the given class.
2095///
2096/// During semantic analysis, this routine should be used in lieu of
2097/// CXXRecordDecl::getDestructor().
2098///
2099/// \returns The destructor for this class.
2100CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +00002101 // If the destructor has not yet been declared, do so now.
2102 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2103 !Class->hasDeclaredDestructor())
2104 DeclareImplicitDestructor(Class);
2105
Douglas Gregore71edda2010-07-01 22:47:18 +00002106 return Class->getDestructor();
2107}
2108
John McCall8fe68082010-01-26 07:16:45 +00002109void ADLResult::insert(NamedDecl *New) {
2110 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2111
2112 // If we haven't yet seen a decl for this key, or the last decl
2113 // was exactly this one, we're done.
2114 if (Old == 0 || Old == New) {
2115 Old = New;
2116 return;
2117 }
2118
2119 // Otherwise, decide which is a more recent redeclaration.
2120 FunctionDecl *OldFD, *NewFD;
2121 if (isa<FunctionTemplateDecl>(New)) {
2122 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2123 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2124 } else {
2125 OldFD = cast<FunctionDecl>(Old);
2126 NewFD = cast<FunctionDecl>(New);
2127 }
2128
2129 FunctionDecl *Cursor = NewFD;
2130 while (true) {
2131 Cursor = Cursor->getPreviousDeclaration();
2132
2133 // If we got to the end without finding OldFD, OldFD is the newer
2134 // declaration; leave things as they are.
2135 if (!Cursor) return;
2136
2137 // If we do find OldFD, then NewFD is newer.
2138 if (Cursor == OldFD) break;
2139
2140 // Otherwise, keep looking.
2141 }
2142
2143 Old = New;
2144}
2145
Sebastian Redlc057f422009-10-23 19:23:15 +00002146void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002147 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00002148 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002149 // Find all of the associated namespaces and classes based on the
2150 // arguments we have.
2151 AssociatedNamespaceSet AssociatedNamespaces;
2152 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002153 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002154 AssociatedNamespaces,
2155 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002156
Sebastian Redlc057f422009-10-23 19:23:15 +00002157 QualType T1, T2;
2158 if (Operator) {
2159 T1 = Args[0]->getType();
2160 if (NumArgs >= 2)
2161 T2 = Args[1]->getType();
2162 }
2163
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002164 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002165 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2166 // and let Y be the lookup set produced by argument dependent
2167 // lookup (defined as follows). If X contains [...] then Y is
2168 // empty. Otherwise Y is the set of declarations found in the
2169 // namespaces associated with the argument types as described
2170 // below. The set of declarations found by the lookup of the name
2171 // is the union of X and Y.
2172 //
2173 // Here, we compute Y and add its members to the overloaded
2174 // candidate set.
2175 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002176 NSEnd = AssociatedNamespaces.end();
2177 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002178 // When considering an associated namespace, the lookup is the
2179 // same as the lookup performed when the associated namespace is
2180 // used as a qualifier (3.4.3.2) except that:
2181 //
2182 // -- Any using-directives in the associated namespace are
2183 // ignored.
2184 //
John McCallc7e8e792009-08-07 22:18:02 +00002185 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002186 // associated classes are visible within their respective
2187 // namespaces even if they are not visible during an ordinary
2188 // lookup (11.4).
2189 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002190 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002191 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002192 // If the only declaration here is an ordinary friend, consider
2193 // it only if it was declared in an associated classes.
2194 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002195 DeclContext *LexDC = D->getLexicalDeclContext();
2196 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2197 continue;
2198 }
Mike Stump11289f42009-09-09 15:08:12 +00002199
John McCall91f61fc2010-01-26 06:04:06 +00002200 if (isa<UsingShadowDecl>(D))
2201 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002202
John McCall91f61fc2010-01-26 06:04:06 +00002203 if (isa<FunctionDecl>(D)) {
2204 if (Operator &&
2205 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2206 T1, T2, Context))
2207 continue;
John McCall8fe68082010-01-26 07:16:45 +00002208 } else if (!isa<FunctionTemplateDecl>(D))
2209 continue;
2210
2211 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002212 }
2213 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002214}
Douglas Gregor2d435302009-12-30 17:04:44 +00002215
2216//----------------------------------------------------------------------------
2217// Search for all visible declarations.
2218//----------------------------------------------------------------------------
2219VisibleDeclConsumer::~VisibleDeclConsumer() { }
2220
2221namespace {
2222
2223class ShadowContextRAII;
2224
2225class VisibleDeclsRecord {
2226public:
2227 /// \brief An entry in the shadow map, which is optimized to store a
2228 /// single declaration (the common case) but can also store a list
2229 /// of declarations.
2230 class ShadowMapEntry {
2231 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2232
2233 /// \brief Contains either the solitary NamedDecl * or a vector
2234 /// of declarations.
2235 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2236
2237 public:
2238 ShadowMapEntry() : DeclOrVector() { }
2239
2240 void Add(NamedDecl *ND);
2241 void Destroy();
2242
2243 // Iteration.
2244 typedef NamedDecl **iterator;
2245 iterator begin();
2246 iterator end();
2247 };
2248
2249private:
2250 /// \brief A mapping from declaration names to the declarations that have
2251 /// this name within a particular scope.
2252 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2253
2254 /// \brief A list of shadow maps, which is used to model name hiding.
2255 std::list<ShadowMap> ShadowMaps;
2256
2257 /// \brief The declaration contexts we have already visited.
2258 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2259
2260 friend class ShadowContextRAII;
2261
2262public:
2263 /// \brief Determine whether we have already visited this context
2264 /// (and, if not, note that we are going to visit that context now).
2265 bool visitedContext(DeclContext *Ctx) {
2266 return !VisitedContexts.insert(Ctx);
2267 }
2268
Douglas Gregor39982192010-08-15 06:18:01 +00002269 bool alreadyVisitedContext(DeclContext *Ctx) {
2270 return VisitedContexts.count(Ctx);
2271 }
2272
Douglas Gregor2d435302009-12-30 17:04:44 +00002273 /// \brief Determine whether the given declaration is hidden in the
2274 /// current scope.
2275 ///
2276 /// \returns the declaration that hides the given declaration, or
2277 /// NULL if no such declaration exists.
2278 NamedDecl *checkHidden(NamedDecl *ND);
2279
2280 /// \brief Add a declaration to the current shadow map.
2281 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2282};
2283
2284/// \brief RAII object that records when we've entered a shadow context.
2285class ShadowContextRAII {
2286 VisibleDeclsRecord &Visible;
2287
2288 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2289
2290public:
2291 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2292 Visible.ShadowMaps.push_back(ShadowMap());
2293 }
2294
2295 ~ShadowContextRAII() {
2296 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2297 EEnd = Visible.ShadowMaps.back().end();
2298 E != EEnd;
2299 ++E)
2300 E->second.Destroy();
2301
2302 Visible.ShadowMaps.pop_back();
2303 }
2304};
2305
2306} // end anonymous namespace
2307
2308void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2309 if (DeclOrVector.isNull()) {
2310 // 0 - > 1 elements: just set the single element information.
2311 DeclOrVector = ND;
2312 return;
2313 }
2314
2315 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2316 // 1 -> 2 elements: create the vector of results and push in the
2317 // existing declaration.
2318 DeclVector *Vec = new DeclVector;
2319 Vec->push_back(PrevND);
2320 DeclOrVector = Vec;
2321 }
2322
2323 // Add the new element to the end of the vector.
2324 DeclOrVector.get<DeclVector*>()->push_back(ND);
2325}
2326
2327void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2328 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2329 delete Vec;
2330 DeclOrVector = ((NamedDecl *)0);
2331 }
2332}
2333
2334VisibleDeclsRecord::ShadowMapEntry::iterator
2335VisibleDeclsRecord::ShadowMapEntry::begin() {
2336 if (DeclOrVector.isNull())
2337 return 0;
2338
2339 if (DeclOrVector.dyn_cast<NamedDecl *>())
2340 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2341
2342 return DeclOrVector.get<DeclVector *>()->begin();
2343}
2344
2345VisibleDeclsRecord::ShadowMapEntry::iterator
2346VisibleDeclsRecord::ShadowMapEntry::end() {
2347 if (DeclOrVector.isNull())
2348 return 0;
2349
2350 if (DeclOrVector.dyn_cast<NamedDecl *>())
2351 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2352
2353 return DeclOrVector.get<DeclVector *>()->end();
2354}
2355
2356NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002357 // Look through using declarations.
2358 ND = ND->getUnderlyingDecl();
2359
Douglas Gregor2d435302009-12-30 17:04:44 +00002360 unsigned IDNS = ND->getIdentifierNamespace();
2361 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2362 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2363 SM != SMEnd; ++SM) {
2364 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2365 if (Pos == SM->end())
2366 continue;
2367
2368 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2369 IEnd = Pos->second.end();
2370 I != IEnd; ++I) {
2371 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002372 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor2d435302009-12-30 17:04:44 +00002373 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2374 Decl::IDNS_ObjCProtocol)))
2375 continue;
2376
2377 // Protocols are in distinct namespaces from everything else.
2378 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2379 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2380 (*I)->getIdentifierNamespace() != IDNS)
2381 continue;
2382
Douglas Gregor09bbc652010-01-14 15:47:35 +00002383 // Functions and function templates in the same scope overload
2384 // rather than hide. FIXME: Look for hiding based on function
2385 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002386 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002387 ND->isFunctionOrFunctionTemplate() &&
2388 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002389 continue;
2390
Douglas Gregor2d435302009-12-30 17:04:44 +00002391 // We've found a declaration that hides this one.
2392 return *I;
2393 }
2394 }
2395
2396 return 0;
2397}
2398
2399static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2400 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002401 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002402 VisibleDeclConsumer &Consumer,
2403 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002404 if (!Ctx)
2405 return;
2406
Douglas Gregor2d435302009-12-30 17:04:44 +00002407 // Make sure we don't visit the same context twice.
2408 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2409 return;
2410
Douglas Gregor7454c562010-07-02 20:37:36 +00002411 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2412 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2413
Douglas Gregor2d435302009-12-30 17:04:44 +00002414 // Enumerate all of the results in this context.
2415 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2416 CurCtx = CurCtx->getNextContext()) {
2417 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2418 DEnd = CurCtx->decls_end();
2419 D != DEnd; ++D) {
2420 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2421 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002422 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002423 Visited.add(ND);
2424 }
2425
2426 // Visit transparent contexts inside this context.
2427 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2428 if (InnerCtx->isTransparentContext())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002429 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002430 Consumer, Visited);
2431 }
2432 }
2433 }
2434
2435 // Traverse using directives for qualified name lookup.
2436 if (QualifiedNameLookup) {
2437 ShadowContextRAII Shadow(Visited);
2438 DeclContext::udir_iterator I, E;
2439 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2440 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002441 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002442 }
2443 }
2444
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002445 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002446 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002447 if (!Record->hasDefinition())
2448 return;
2449
Douglas Gregor2d435302009-12-30 17:04:44 +00002450 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2451 BEnd = Record->bases_end();
2452 B != BEnd; ++B) {
2453 QualType BaseType = B->getType();
2454
2455 // Don't look into dependent bases, because name lookup can't look
2456 // there anyway.
2457 if (BaseType->isDependentType())
2458 continue;
2459
2460 const RecordType *Record = BaseType->getAs<RecordType>();
2461 if (!Record)
2462 continue;
2463
2464 // FIXME: It would be nice to be able to determine whether referencing
2465 // a particular member would be ambiguous. For example, given
2466 //
2467 // struct A { int member; };
2468 // struct B { int member; };
2469 // struct C : A, B { };
2470 //
2471 // void f(C *c) { c->### }
2472 //
2473 // accessing 'member' would result in an ambiguity. However, we
2474 // could be smart enough to qualify the member with the base
2475 // class, e.g.,
2476 //
2477 // c->B::member
2478 //
2479 // or
2480 //
2481 // c->A::member
2482
2483 // Find results in this base class (and its bases).
2484 ShadowContextRAII Shadow(Visited);
2485 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002486 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002487 }
2488 }
2489
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002490 // Traverse the contexts of Objective-C classes.
2491 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2492 // Traverse categories.
2493 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2494 Category; Category = Category->getNextClassCategory()) {
2495 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002496 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2497 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002498 }
2499
2500 // Traverse protocols.
2501 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2502 E = IFace->protocol_end(); I != E; ++I) {
2503 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002504 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2505 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002506 }
2507
2508 // Traverse the superclass.
2509 if (IFace->getSuperClass()) {
2510 ShadowContextRAII Shadow(Visited);
2511 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002512 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002513 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002514
2515 // If there is an implementation, traverse it. We do this to find
2516 // synthesized ivars.
2517 if (IFace->getImplementation()) {
2518 ShadowContextRAII Shadow(Visited);
2519 LookupVisibleDecls(IFace->getImplementation(), Result,
2520 QualifiedNameLookup, true, Consumer, Visited);
2521 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002522 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2523 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2524 E = Protocol->protocol_end(); I != E; ++I) {
2525 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002526 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2527 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002528 }
2529 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2530 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2531 E = Category->protocol_end(); I != E; ++I) {
2532 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002533 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2534 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002535 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002536
2537 // If there is an implementation, traverse it.
2538 if (Category->getImplementation()) {
2539 ShadowContextRAII Shadow(Visited);
2540 LookupVisibleDecls(Category->getImplementation(), Result,
2541 QualifiedNameLookup, true, Consumer, Visited);
2542 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002543 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002544}
2545
2546static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2547 UnqualUsingDirectiveSet &UDirs,
2548 VisibleDeclConsumer &Consumer,
2549 VisibleDeclsRecord &Visited) {
2550 if (!S)
2551 return;
2552
Douglas Gregor39982192010-08-15 06:18:01 +00002553 if (!S->getEntity() ||
2554 (!S->getParent() &&
2555 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002556 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2557 // Walk through the declarations in this Scope.
2558 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2559 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002560 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002561 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002562 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002563 Visited.add(ND);
2564 }
2565 }
2566 }
2567
Douglas Gregor66230062010-03-15 14:33:29 +00002568 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002569 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002570 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002571 // Look into this scope's declaration context, along with any of its
2572 // parent lookup contexts (e.g., enclosing classes), up to the point
2573 // where we hit the context stored in the next outer scope.
2574 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002575 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor2d435302009-12-30 17:04:44 +00002576
Douglas Gregorea166062010-03-15 15:26:48 +00002577 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002578 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002579 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2580 if (Method->isInstanceMethod()) {
2581 // For instance methods, look for ivars in the method's interface.
2582 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2583 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002584 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2585 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2586 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002587 }
2588
2589 // We've already performed all of the name lookup that we need
2590 // to for Objective-C methods; the next context will be the
2591 // outer scope.
2592 break;
2593 }
2594
Douglas Gregor2d435302009-12-30 17:04:44 +00002595 if (Ctx->isFunctionOrMethod())
2596 continue;
2597
2598 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002599 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002600 }
2601 } else if (!S->getParent()) {
2602 // Look into the translation unit scope. We walk through the translation
2603 // unit's declaration context, because the Scope itself won't have all of
2604 // the declarations if we loaded a precompiled header.
2605 // FIXME: We would like the translation unit's Scope object to point to the
2606 // translation unit, so we don't need this special "if" branch. However,
2607 // doing so would force the normal C++ name-lookup code to look into the
2608 // translation unit decl when the IdentifierInfo chains would suffice.
2609 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002610 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002611 Entity = Result.getSema().Context.getTranslationUnitDecl();
2612 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002613 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002614 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002615
2616 if (Entity) {
2617 // Lookup visible declarations in any namespaces found by using
2618 // directives.
2619 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2620 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2621 for (; UI != UEnd; ++UI)
2622 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002623 Result, /*QualifiedNameLookup=*/false,
2624 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002625 }
2626
2627 // Lookup names in the parent scope.
2628 ShadowContextRAII Shadow(Visited);
2629 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2630}
2631
2632void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002633 VisibleDeclConsumer &Consumer,
2634 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002635 // Determine the set of using directives available during
2636 // unqualified name lookup.
2637 Scope *Initial = S;
2638 UnqualUsingDirectiveSet UDirs;
2639 if (getLangOptions().CPlusPlus) {
2640 // Find the first namespace or translation-unit scope.
2641 while (S && !isNamespaceOrTranslationUnitScope(S))
2642 S = S->getParent();
2643
2644 UDirs.visitScopeChain(Initial, S);
2645 }
2646 UDirs.done();
2647
2648 // Look for visible declarations.
2649 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2650 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002651 if (!IncludeGlobalScope)
2652 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002653 ShadowContextRAII Shadow(Visited);
2654 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2655}
2656
2657void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002658 VisibleDeclConsumer &Consumer,
2659 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002660 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2661 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002662 if (!IncludeGlobalScope)
2663 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002664 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002665 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2666 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002667}
2668
2669//----------------------------------------------------------------------------
2670// Typo correction
2671//----------------------------------------------------------------------------
2672
2673namespace {
2674class TypoCorrectionConsumer : public VisibleDeclConsumer {
2675 /// \brief The name written that is a typo in the source.
2676 llvm::StringRef Typo;
2677
2678 /// \brief The results found that have the smallest edit distance
2679 /// found (so far) with the typo name.
2680 llvm::SmallVector<NamedDecl *, 4> BestResults;
2681
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002682 /// \brief The keywords that have the smallest edit distance.
2683 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2684
Douglas Gregor2d435302009-12-30 17:04:44 +00002685 /// \brief The best edit distance found so far.
2686 unsigned BestEditDistance;
2687
2688public:
2689 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2690 : Typo(Typo->getName()) { }
2691
Douglas Gregor09bbc652010-01-14 15:47:35 +00002692 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002693 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002694
2695 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2696 iterator begin() const { return BestResults.begin(); }
2697 iterator end() const { return BestResults.end(); }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002698 void clear_decls() { BestResults.clear(); }
2699
2700 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002701
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002702 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2703 keyword_iterator;
2704 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2705 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2706 bool keyword_empty() const { return BestKeywords.empty(); }
2707 unsigned keyword_size() const { return BestKeywords.size(); }
2708
2709 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002710};
2711
2712}
2713
Douglas Gregor09bbc652010-01-14 15:47:35 +00002714void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2715 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002716 // Don't consider hidden names for typo correction.
2717 if (Hiding)
2718 return;
2719
2720 // Only consider entities with identifiers for names, ignoring
2721 // special names (constructors, overloaded operators, selectors,
2722 // etc.).
2723 IdentifierInfo *Name = ND->getIdentifier();
2724 if (!Name)
2725 return;
2726
2727 // Compute the edit distance between the typo and the name of this
2728 // entity. If this edit distance is not worse than the best edit
2729 // distance we've seen so far, add it to the list of results.
2730 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002731 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002732 if (ED < BestEditDistance) {
2733 // This result is better than any we've seen before; clear out
2734 // the previous results.
2735 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002736 BestKeywords.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002737 BestEditDistance = ED;
2738 } else if (ED > BestEditDistance) {
2739 // This result is worse than the best results we've seen so far;
2740 // ignore it.
2741 return;
2742 }
2743 } else
2744 BestEditDistance = ED;
2745
2746 BestResults.push_back(ND);
2747}
2748
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002749void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2750 llvm::StringRef Keyword) {
2751 // Compute the edit distance between the typo and this keyword.
2752 // If this edit distance is not worse than the best edit
2753 // distance we've seen so far, add it to the list of results.
2754 unsigned ED = Typo.edit_distance(Keyword);
2755 if (!BestResults.empty() || !BestKeywords.empty()) {
2756 if (ED < BestEditDistance) {
2757 BestResults.clear();
2758 BestKeywords.clear();
2759 BestEditDistance = ED;
2760 } else if (ED > BestEditDistance) {
2761 // This result is worse than the best results we've seen so far;
2762 // ignore it.
2763 return;
2764 }
2765 } else
2766 BestEditDistance = ED;
2767
2768 BestKeywords.push_back(&Context.Idents.get(Keyword));
2769}
2770
Douglas Gregor2d435302009-12-30 17:04:44 +00002771/// \brief Try to "correct" a typo in the source code by finding
2772/// visible declarations whose names are similar to the name that was
2773/// present in the source code.
2774///
2775/// \param Res the \c LookupResult structure that contains the name
2776/// that was present in the source code along with the name-lookup
2777/// criteria used to search for the name. On success, this structure
2778/// will contain the results of name lookup.
2779///
2780/// \param S the scope in which name lookup occurs.
2781///
2782/// \param SS the nested-name-specifier that precedes the name we're
2783/// looking for, if present.
2784///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002785/// \param MemberContext if non-NULL, the context in which to look for
2786/// a member access expression.
2787///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002788/// \param EnteringContext whether we're entering the context described by
2789/// the nested-name-specifier SS.
2790///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002791/// \param CTC The context in which typo correction occurs, which impacts the
2792/// set of keywords permitted.
2793///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002794/// \param OPT when non-NULL, the search for visible declarations will
2795/// also walk the protocols in the qualified interfaces of \p OPT.
2796///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002797/// \returns the corrected name if the typo was corrected, otherwise returns an
2798/// empty \c DeclarationName. When a typo was corrected, the result structure
2799/// may contain the results of name lookup for the correct name or it may be
2800/// empty.
2801DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002802 DeclContext *MemberContext,
2803 bool EnteringContext,
2804 CorrectTypoContext CTC,
2805 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00002806 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002807 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002808
2809 // Provide a stop gap for files that are just seriously broken. Trying
2810 // to correct all typos can turn into a HUGE performance penalty, causing
2811 // some files to take minutes to get rejected by the parser.
2812 // FIXME: Is this the right solution?
2813 if (TyposCorrected == 20)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002814 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002815 ++TyposCorrected;
Ted Kremeneke51136e2010-01-06 00:23:04 +00002816
Douglas Gregor2d435302009-12-30 17:04:44 +00002817 // We only attempt to correct typos for identifiers.
2818 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2819 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002820 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002821
2822 // If the scope specifier itself was invalid, don't try to correct
2823 // typos.
2824 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002825 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002826
2827 // Never try to correct typos during template deduction or
2828 // instantiation.
2829 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002830 return DeclarationName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002831
Douglas Gregor2d435302009-12-30 17:04:44 +00002832 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002833
2834 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002835 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002836 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002837
2838 // Look in qualified interfaces.
2839 if (OPT) {
2840 for (ObjCObjectPointerType::qual_iterator
2841 I = OPT->qual_begin(), E = OPT->qual_end();
2842 I != E; ++I)
2843 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2844 }
2845 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002846 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2847 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002848 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002849
2850 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2851 } else {
2852 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2853 }
2854
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002855 // Add context-dependent keywords.
2856 bool WantTypeSpecifiers = false;
2857 bool WantExpressionKeywords = false;
2858 bool WantCXXNamedCasts = false;
2859 bool WantRemainingKeywords = false;
2860 switch (CTC) {
2861 case CTC_Unknown:
2862 WantTypeSpecifiers = true;
2863 WantExpressionKeywords = true;
2864 WantCXXNamedCasts = true;
2865 WantRemainingKeywords = true;
Douglas Gregor5fd04d42010-05-18 16:14:23 +00002866
2867 if (ObjCMethodDecl *Method = getCurMethodDecl())
2868 if (Method->getClassInterface() &&
2869 Method->getClassInterface()->getSuperClass())
2870 Consumer.addKeywordResult(Context, "super");
2871
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002872 break;
2873
2874 case CTC_NoKeywords:
2875 break;
2876
2877 case CTC_Type:
2878 WantTypeSpecifiers = true;
2879 break;
2880
2881 case CTC_ObjCMessageReceiver:
2882 Consumer.addKeywordResult(Context, "super");
2883 // Fall through to handle message receivers like expressions.
2884
2885 case CTC_Expression:
2886 if (getLangOptions().CPlusPlus)
2887 WantTypeSpecifiers = true;
2888 WantExpressionKeywords = true;
2889 // Fall through to get C++ named casts.
2890
2891 case CTC_CXXCasts:
2892 WantCXXNamedCasts = true;
2893 break;
2894
2895 case CTC_MemberLookup:
2896 if (getLangOptions().CPlusPlus)
2897 Consumer.addKeywordResult(Context, "template");
2898 break;
2899 }
2900
2901 if (WantTypeSpecifiers) {
2902 // Add type-specifier keywords to the set of results.
2903 const char *CTypeSpecs[] = {
2904 "char", "const", "double", "enum", "float", "int", "long", "short",
2905 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2906 "_Complex", "_Imaginary",
2907 // storage-specifiers as well
2908 "extern", "inline", "static", "typedef"
2909 };
2910
2911 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2912 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2913 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2914
2915 if (getLangOptions().C99)
2916 Consumer.addKeywordResult(Context, "restrict");
2917 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2918 Consumer.addKeywordResult(Context, "bool");
2919
2920 if (getLangOptions().CPlusPlus) {
2921 Consumer.addKeywordResult(Context, "class");
2922 Consumer.addKeywordResult(Context, "typename");
2923 Consumer.addKeywordResult(Context, "wchar_t");
2924
2925 if (getLangOptions().CPlusPlus0x) {
2926 Consumer.addKeywordResult(Context, "char16_t");
2927 Consumer.addKeywordResult(Context, "char32_t");
2928 Consumer.addKeywordResult(Context, "constexpr");
2929 Consumer.addKeywordResult(Context, "decltype");
2930 Consumer.addKeywordResult(Context, "thread_local");
2931 }
2932 }
2933
2934 if (getLangOptions().GNUMode)
2935 Consumer.addKeywordResult(Context, "typeof");
2936 }
2937
Douglas Gregor86ad0852010-05-18 16:30:22 +00002938 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002939 Consumer.addKeywordResult(Context, "const_cast");
2940 Consumer.addKeywordResult(Context, "dynamic_cast");
2941 Consumer.addKeywordResult(Context, "reinterpret_cast");
2942 Consumer.addKeywordResult(Context, "static_cast");
2943 }
2944
2945 if (WantExpressionKeywords) {
2946 Consumer.addKeywordResult(Context, "sizeof");
2947 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2948 Consumer.addKeywordResult(Context, "false");
2949 Consumer.addKeywordResult(Context, "true");
2950 }
2951
2952 if (getLangOptions().CPlusPlus) {
2953 const char *CXXExprs[] = {
2954 "delete", "new", "operator", "throw", "typeid"
2955 };
2956 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2957 for (unsigned I = 0; I != NumCXXExprs; ++I)
2958 Consumer.addKeywordResult(Context, CXXExprs[I]);
2959
2960 if (isa<CXXMethodDecl>(CurContext) &&
2961 cast<CXXMethodDecl>(CurContext)->isInstance())
2962 Consumer.addKeywordResult(Context, "this");
2963
2964 if (getLangOptions().CPlusPlus0x) {
2965 Consumer.addKeywordResult(Context, "alignof");
2966 Consumer.addKeywordResult(Context, "nullptr");
2967 }
2968 }
2969 }
2970
2971 if (WantRemainingKeywords) {
2972 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2973 // Statements.
2974 const char *CStmts[] = {
2975 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2976 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2977 for (unsigned I = 0; I != NumCStmts; ++I)
2978 Consumer.addKeywordResult(Context, CStmts[I]);
2979
2980 if (getLangOptions().CPlusPlus) {
2981 Consumer.addKeywordResult(Context, "catch");
2982 Consumer.addKeywordResult(Context, "try");
2983 }
2984
2985 if (S && S->getBreakParent())
2986 Consumer.addKeywordResult(Context, "break");
2987
2988 if (S && S->getContinueParent())
2989 Consumer.addKeywordResult(Context, "continue");
2990
John McCallaab3e412010-08-25 08:40:02 +00002991 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002992 Consumer.addKeywordResult(Context, "case");
2993 Consumer.addKeywordResult(Context, "default");
2994 }
2995 } else {
2996 if (getLangOptions().CPlusPlus) {
2997 Consumer.addKeywordResult(Context, "namespace");
2998 Consumer.addKeywordResult(Context, "template");
2999 }
3000
3001 if (S && S->isClassScope()) {
3002 Consumer.addKeywordResult(Context, "explicit");
3003 Consumer.addKeywordResult(Context, "friend");
3004 Consumer.addKeywordResult(Context, "mutable");
3005 Consumer.addKeywordResult(Context, "private");
3006 Consumer.addKeywordResult(Context, "protected");
3007 Consumer.addKeywordResult(Context, "public");
3008 Consumer.addKeywordResult(Context, "virtual");
3009 }
3010 }
3011
3012 if (getLangOptions().CPlusPlus) {
3013 Consumer.addKeywordResult(Context, "using");
3014
3015 if (getLangOptions().CPlusPlus0x)
3016 Consumer.addKeywordResult(Context, "static_assert");
3017 }
3018 }
3019
3020 // If we haven't found anything, we're done.
Douglas Gregor2d435302009-12-30 17:04:44 +00003021 if (Consumer.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003022 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003023
3024 // Only allow a single, closest name in the result set (it's okay to
3025 // have overloads of that name, though).
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003026 DeclarationName BestName;
3027 NamedDecl *BestIvarOrPropertyDecl = 0;
3028 bool FoundIvarOrPropertyDecl = false;
3029
3030 // Check all of the declaration results to find the best name so far.
3031 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3032 IEnd = Consumer.end();
3033 I != IEnd; ++I) {
3034 if (!BestName)
3035 BestName = (*I)->getDeclName();
3036 else if (BestName != (*I)->getDeclName())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003037 return DeclarationName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003038
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003039 // \brief Keep track of either an Objective-C ivar or a property, but not
3040 // both.
3041 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
3042 if (FoundIvarOrPropertyDecl)
3043 BestIvarOrPropertyDecl = 0;
3044 else {
3045 BestIvarOrPropertyDecl = *I;
3046 FoundIvarOrPropertyDecl = true;
3047 }
3048 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003049 }
3050
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003051 // Now check all of the keyword results to find the best name.
3052 switch (Consumer.keyword_size()) {
3053 case 0:
3054 // No keywords matched.
3055 break;
3056
3057 case 1:
3058 // If we already have a name
3059 if (!BestName) {
3060 // We did not have anything previously,
3061 BestName = *Consumer.keyword_begin();
3062 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
3063 // We have a declaration with the same name as a context-sensitive
3064 // keyword. The keyword takes precedence.
3065 BestIvarOrPropertyDecl = 0;
3066 FoundIvarOrPropertyDecl = false;
3067 Consumer.clear_decls();
Douglas Gregor86ad0852010-05-18 16:30:22 +00003068 } else if (CTC == CTC_ObjCMessageReceiver &&
3069 (*Consumer.keyword_begin())->isStr("super")) {
3070 // In an Objective-C message send, give the "super" keyword a slight
3071 // edge over entities not in function or method scope.
3072 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3073 IEnd = Consumer.end();
3074 I != IEnd; ++I) {
3075 if ((*I)->getDeclName() == BestName) {
3076 if ((*I)->getDeclContext()->isFunctionOrMethod())
3077 return DeclarationName();
3078 }
3079 }
3080
3081 // Everything found was outside a function or method; the 'super'
3082 // keyword takes precedence.
3083 BestIvarOrPropertyDecl = 0;
3084 FoundIvarOrPropertyDecl = false;
3085 Consumer.clear_decls();
3086 BestName = *Consumer.keyword_begin();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003087 } else {
3088 // Name collision; we will not correct typos.
3089 return DeclarationName();
3090 }
3091 break;
3092
3093 default:
3094 // Name collision; we will not correct typos.
3095 return DeclarationName();
3096 }
3097
Douglas Gregor2d435302009-12-30 17:04:44 +00003098 // BestName is the closest viable name to what the user
3099 // typed. However, to make sure that we don't pick something that's
3100 // way off, make sure that the user typed at least 3 characters for
3101 // each correction.
3102 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003103 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
3104 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003105 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003106
3107 // Perform name lookup again with the name we chose, and declare
3108 // success if we found something that was not ambiguous.
3109 Res.clear();
3110 Res.setLookupName(BestName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003111
3112 // If we found an ivar or property, add that result; no further
3113 // lookup is required.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003114 if (BestIvarOrPropertyDecl)
3115 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003116 // If we're looking into the context of a member, perform qualified
3117 // name lookup on the best name.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003118 else if (!Consumer.keyword_empty()) {
3119 // The best match was a keyword. Return it.
3120 return BestName;
3121 } else if (MemberContext)
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003122 LookupQualifiedName(Res, MemberContext);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003123 // Perform lookup as if we had just parsed the best name.
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003124 else
3125 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3126 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00003127
3128 if (Res.isAmbiguous()) {
3129 Res.suppressDiagnostics();
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003130 return DeclarationName();
Douglas Gregor598b08f2009-12-31 05:20:13 +00003131 }
3132
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003133 if (Res.getResultKind() != LookupResult::NotFound)
3134 return BestName;
3135
3136 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003137}