blob: eedfa92c3b463d7315ecbb13da678d34d267e818 [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"
15#include "clang/Sema/Lookup.h"
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/DeclSpec.h"
John McCallcc14d1f2010-08-24 08:50:51 +000017#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000018#include "clang/Sema/ScopeInfo.h"
John McCall19c1bfd2010-08-25 05:32:35 +000019#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor960b5bc2009-01-15 00:26:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000021#include "clang/AST/CXXInheritance.h"
Douglas Gregor34074322009-01-14 22:20:51 +000022#include "clang/AST/Decl.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000026#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000027#include "clang/AST/ExprCXX.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000028#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000029#include "clang/Basic/LangOptions.h"
John McCalla1e130b2010-08-25 07:03:20 +000030#include "llvm/ADT/DenseSet.h"
Douglas Gregor34074322009-01-14 22:20:51 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000032#include "llvm/ADT/SmallPtrSet.h"
John McCall6538c932009-10-10 05:48:19 +000033#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2d435302009-12-30 17:04:44 +000034#include <list>
Douglas Gregor1c846b02009-01-16 00:38:09 +000035#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000036#include <vector>
37#include <iterator>
38#include <utility>
39#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000040
41using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000042using namespace sema;
Douglas Gregor34074322009-01-14 22:20:51 +000043
John McCallf6c8a4e2009-11-10 07:01:13 +000044namespace {
45 class UnqualUsingEntry {
46 const DeclContext *Nominated;
47 const DeclContext *CommonAncestor;
Douglas Gregor889ceb72009-02-03 19:21:40 +000048
John McCallf6c8a4e2009-11-10 07:01:13 +000049 public:
50 UnqualUsingEntry(const DeclContext *Nominated,
51 const DeclContext *CommonAncestor)
52 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
53 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000054
John McCallf6c8a4e2009-11-10 07:01:13 +000055 const DeclContext *getCommonAncestor() const {
56 return CommonAncestor;
57 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000058
John McCallf6c8a4e2009-11-10 07:01:13 +000059 const DeclContext *getNominatedNamespace() const {
60 return Nominated;
61 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000062
John McCallf6c8a4e2009-11-10 07:01:13 +000063 // Sort by the pointer value of the common ancestor.
64 struct Comparator {
65 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
66 return L.getCommonAncestor() < R.getCommonAncestor();
67 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000068
John McCallf6c8a4e2009-11-10 07:01:13 +000069 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
70 return E.getCommonAncestor() < DC;
71 }
Douglas Gregor889ceb72009-02-03 19:21:40 +000072
John McCallf6c8a4e2009-11-10 07:01:13 +000073 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
74 return DC < E.getCommonAncestor();
75 }
76 };
77 };
Douglas Gregor889ceb72009-02-03 19:21:40 +000078
John McCallf6c8a4e2009-11-10 07:01:13 +000079 /// A collection of using directives, as used by C++ unqualified
80 /// lookup.
81 class UnqualUsingDirectiveSet {
82 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +000083
John McCallf6c8a4e2009-11-10 07:01:13 +000084 ListTy list;
85 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor889ceb72009-02-03 19:21:40 +000086
John McCallf6c8a4e2009-11-10 07:01:13 +000087 public:
88 UnqualUsingDirectiveSet() {}
Douglas Gregor889ceb72009-02-03 19:21:40 +000089
John McCallf6c8a4e2009-11-10 07:01:13 +000090 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
91 // C++ [namespace.udir]p1:
92 // During unqualified name lookup, the names appear as if they
93 // were declared in the nearest enclosing namespace which contains
94 // both the using-directive and the nominated namespace.
95 DeclContext *InnermostFileDC
96 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
97 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor889ceb72009-02-03 19:21:40 +000098
John McCallf6c8a4e2009-11-10 07:01:13 +000099 for (; S; S = S->getParent()) {
John McCallf6c8a4e2009-11-10 07:01:13 +0000100 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
101 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
102 visit(Ctx, EffectiveDC);
103 } else {
104 Scope::udir_iterator I = S->using_directives_begin(),
105 End = S->using_directives_end();
106
107 for (; I != End; ++I)
John McCall48871652010-08-21 09:40:31 +0000108 visit(*I, InnermostFileDC);
John McCallf6c8a4e2009-11-10 07:01:13 +0000109 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000110 }
111 }
John McCallf6c8a4e2009-11-10 07:01:13 +0000112
113 // Visits a context and collect all of its using directives
114 // recursively. Treats all using directives as if they were
115 // declared in the context.
116 //
117 // A given context is only every visited once, so it is important
118 // that contexts be visited from the inside out in order to get
119 // the effective DCs right.
120 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
121 if (!visited.insert(DC))
122 return;
123
124 addUsingDirectives(DC, EffectiveDC);
125 }
126
127 // Visits a using directive and collects all of its using
128 // directives recursively. Treats all using directives as if they
129 // were declared in the effective DC.
130 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
131 DeclContext *NS = UD->getNominatedNamespace();
132 if (!visited.insert(NS))
133 return;
134
135 addUsingDirective(UD, EffectiveDC);
136 addUsingDirectives(NS, EffectiveDC);
137 }
138
139 // Adds all the using directives in a context (and those nominated
140 // by its using directives, transitively) as if they appeared in
141 // the given effective context.
142 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
143 llvm::SmallVector<DeclContext*,4> queue;
144 while (true) {
145 DeclContext::udir_iterator I, End;
146 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
147 UsingDirectiveDecl *UD = *I;
148 DeclContext *NS = UD->getNominatedNamespace();
149 if (visited.insert(NS)) {
150 addUsingDirective(UD, EffectiveDC);
151 queue.push_back(NS);
152 }
153 }
154
155 if (queue.empty())
156 return;
157
158 DC = queue.back();
159 queue.pop_back();
160 }
161 }
162
163 // Add a using directive as if it had been declared in the given
164 // context. This helps implement C++ [namespace.udir]p3:
165 // The using-directive is transitive: if a scope contains a
166 // using-directive that nominates a second namespace that itself
167 // contains using-directives, the effect is as if the
168 // using-directives from the second namespace also appeared in
169 // the first.
170 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
171 // Find the common ancestor between the effective context and
172 // the nominated namespace.
173 DeclContext *Common = UD->getNominatedNamespace();
174 while (!Common->Encloses(EffectiveDC))
175 Common = Common->getParent();
John McCall9757d032009-11-10 09:20:04 +0000176 Common = Common->getPrimaryContext();
John McCallf6c8a4e2009-11-10 07:01:13 +0000177
178 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
179 }
180
181 void done() {
182 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
183 }
184
185 typedef ListTy::iterator iterator;
186 typedef ListTy::const_iterator const_iterator;
187
188 iterator begin() { return list.begin(); }
189 iterator end() { return list.end(); }
190 const_iterator begin() const { return list.begin(); }
191 const_iterator end() const { return list.end(); }
192
193 std::pair<const_iterator,const_iterator>
194 getNamespacesFor(DeclContext *DC) const {
John McCall9757d032009-11-10 09:20:04 +0000195 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCallf6c8a4e2009-11-10 07:01:13 +0000196 UnqualUsingEntry::Comparator());
197 }
198 };
Douglas Gregor889ceb72009-02-03 19:21:40 +0000199}
200
Douglas Gregor889ceb72009-02-03 19:21:40 +0000201// Retrieve the set of identifier namespaces that correspond to a
202// specific kind of name lookup.
John McCallea305ed2009-12-18 10:40:03 +0000203static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
204 bool CPlusPlus,
205 bool Redeclaration) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000206 unsigned IDNS = 0;
207 switch (NameKind) {
208 case Sema::LookupOrdinaryName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000209 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000210 IDNS = Decl::IDNS_Ordinary;
John McCallea305ed2009-12-18 10:40:03 +0000211 if (CPlusPlus) {
John McCalle87beb22010-04-23 18:46:30 +0000212 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCallea305ed2009-12-18 10:40:03 +0000213 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
214 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000215 break;
216
John McCallb9467b62010-04-24 01:30:58 +0000217 case Sema::LookupOperatorName:
218 // Operator lookup is its own crazy thing; it is not the same
219 // as (e.g.) looking up an operator name for redeclaration.
220 assert(!Redeclaration && "cannot do redeclaration operator lookup");
221 IDNS = Decl::IDNS_NonMemberOperator;
222 break;
223
Douglas Gregor889ceb72009-02-03 19:21:40 +0000224 case Sema::LookupTagName:
John McCalle87beb22010-04-23 18:46:30 +0000225 if (CPlusPlus) {
226 IDNS = Decl::IDNS_Type;
227
228 // When looking for a redeclaration of a tag name, we add:
229 // 1) TagFriend to find undeclared friend decls
230 // 2) Namespace because they can't "overload" with tag decls.
231 // 3) Tag because it includes class templates, which can't
232 // "overload" with tag decls.
233 if (Redeclaration)
234 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
235 } else {
236 IDNS = Decl::IDNS_Tag;
237 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000238 break;
239
240 case Sema::LookupMemberName:
241 IDNS = Decl::IDNS_Member;
242 if (CPlusPlus)
Mike Stump11289f42009-09-09 15:08:12 +0000243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000244 break;
245
246 case Sema::LookupNestedNameSpecifierName:
John McCalle87beb22010-04-23 18:46:30 +0000247 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
248 break;
249
Douglas Gregor889ceb72009-02-03 19:21:40 +0000250 case Sema::LookupNamespaceName:
John McCalle87beb22010-04-23 18:46:30 +0000251 IDNS = Decl::IDNS_Namespace;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000252 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000253
John McCall84d87672009-12-10 09:41:52 +0000254 case Sema::LookupUsingDeclName:
255 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
256 | Decl::IDNS_Member | Decl::IDNS_Using;
257 break;
258
Douglas Gregor79947a22009-04-24 00:11:27 +0000259 case Sema::LookupObjCProtocolName:
260 IDNS = Decl::IDNS_ObjCProtocol;
261 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000262
263 case Sema::LookupAnyName:
264 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
265 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
266 | Decl::IDNS_Type;
267 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000268 }
269 return IDNS;
270}
271
John McCallea305ed2009-12-18 10:40:03 +0000272void LookupResult::configure() {
273 IDNS = getIDNS(LookupKind,
274 SemaRef.getLangOptions().CPlusPlus,
275 isForRedeclaration());
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000276
277 // If we're looking for one of the allocation or deallocation
278 // operators, make sure that the implicitly-declared new and delete
279 // operators can be found.
280 if (!isForRedeclaration()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000281 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorbcf0a472010-03-24 05:07:21 +0000282 case OO_New:
283 case OO_Delete:
284 case OO_Array_New:
285 case OO_Array_Delete:
286 SemaRef.DeclareGlobalNewDelete();
287 break;
288
289 default:
290 break;
291 }
292 }
John McCallea305ed2009-12-18 10:40:03 +0000293}
294
John McCall19c1bfd2010-08-25 05:32:35 +0000295#ifndef NDEBUG
296void LookupResult::sanity() const {
297 assert(ResultKind != NotFound || Decls.size() == 0);
298 assert(ResultKind != Found || Decls.size() == 1);
299 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
300 (Decls.size() == 1 &&
301 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
302 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
303 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
304 (Decls.size() == 1 && Ambiguity == AmbiguousBaseSubobjects));
305 assert((Paths != NULL) == (ResultKind == Ambiguous &&
306 (Ambiguity == AmbiguousBaseSubobjectTypes ||
307 Ambiguity == AmbiguousBaseSubobjects)));
308}
309#endif
310
John McCall9f3059a2009-10-09 21:13:30 +0000311// Necessary because CXXBasePaths is not complete in Sema.h
John McCall5cebab12009-11-18 07:57:50 +0000312void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCall9f3059a2009-10-09 21:13:30 +0000313 delete Paths;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000314}
315
John McCall283b9012009-11-22 00:44:51 +0000316/// Resolves the result kind of this lookup.
John McCall5cebab12009-11-18 07:57:50 +0000317void LookupResult::resolveKind() {
John McCall9f3059a2009-10-09 21:13:30 +0000318 unsigned N = Decls.size();
John McCall84d87672009-12-10 09:41:52 +0000319
John McCall9f3059a2009-10-09 21:13:30 +0000320 // Fast case: no possible ambiguity.
John McCall1f82f242009-11-18 22:49:29 +0000321 if (N == 0) {
John McCall7fe6e9c2010-01-15 21:27:01 +0000322 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall1f82f242009-11-18 22:49:29 +0000323 return;
324 }
325
John McCall283b9012009-11-22 00:44:51 +0000326 // If there's a single decl, we need to examine it to decide what
327 // kind of lookup this is.
John McCalle61f2ba2009-11-18 02:36:19 +0000328 if (N == 1) {
Douglas Gregor516d6722010-04-25 21:15:30 +0000329 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
330 if (isa<FunctionTemplateDecl>(D))
John McCall283b9012009-11-22 00:44:51 +0000331 ResultKind = FoundOverloaded;
Douglas Gregor516d6722010-04-25 21:15:30 +0000332 else if (isa<UnresolvedUsingValueDecl>(D))
John McCalle61f2ba2009-11-18 02:36:19 +0000333 ResultKind = FoundUnresolvedValue;
334 return;
335 }
John McCall9f3059a2009-10-09 21:13:30 +0000336
John McCall6538c932009-10-10 05:48:19 +0000337 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCall27b18f82009-11-17 02:14:36 +0000338 if (ResultKind == Ambiguous) return;
John McCall6538c932009-10-10 05:48:19 +0000339
John McCall9f3059a2009-10-09 21:13:30 +0000340 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor13e65872010-08-11 14:45:53 +0000341 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
342
John McCall9f3059a2009-10-09 21:13:30 +0000343 bool Ambiguous = false;
344 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall283b9012009-11-22 00:44:51 +0000345 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCall9f3059a2009-10-09 21:13:30 +0000346
347 unsigned UniqueTagIndex = 0;
348
349 unsigned I = 0;
350 while (I < N) {
John McCallf0f1cf02009-11-17 07:50:12 +0000351 NamedDecl *D = Decls[I]->getUnderlyingDecl();
352 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCall9f3059a2009-10-09 21:13:30 +0000353
Douglas Gregor13e65872010-08-11 14:45:53 +0000354 // Redeclarations of types via typedef can occur both within a scope
355 // and, through using declarations and directives, across scopes. There is
356 // no ambiguity if they all refer to the same type, so unique based on the
357 // canonical type.
358 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
359 if (!TD->getDeclContext()->isRecord()) {
360 QualType T = SemaRef.Context.getTypeDeclType(TD);
361 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
362 // The type is not unique; pull something off the back and continue
363 // at this index.
364 Decls[I] = Decls[--N];
365 continue;
366 }
367 }
368 }
369
John McCallf0f1cf02009-11-17 07:50:12 +0000370 if (!Unique.insert(D)) {
John McCall9f3059a2009-10-09 21:13:30 +0000371 // If it's not unique, pull something off the back (and
372 // continue at this index).
373 Decls[I] = Decls[--N];
Douglas Gregor13e65872010-08-11 14:45:53 +0000374 continue;
375 }
376
377 // Otherwise, do some decl type analysis and then continue.
John McCalle61f2ba2009-11-18 02:36:19 +0000378
Douglas Gregor13e65872010-08-11 14:45:53 +0000379 if (isa<UnresolvedUsingValueDecl>(D)) {
380 HasUnresolved = true;
381 } else if (isa<TagDecl>(D)) {
382 if (HasTag)
383 Ambiguous = true;
384 UniqueTagIndex = I;
385 HasTag = true;
386 } else if (isa<FunctionTemplateDecl>(D)) {
387 HasFunction = true;
388 HasFunctionTemplate = true;
389 } else if (isa<FunctionDecl>(D)) {
390 HasFunction = true;
391 } else {
392 if (HasNonFunction)
393 Ambiguous = true;
394 HasNonFunction = true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000395 }
Douglas Gregor13e65872010-08-11 14:45:53 +0000396 I++;
Mike Stump11289f42009-09-09 15:08:12 +0000397 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000398
John McCall9f3059a2009-10-09 21:13:30 +0000399 // C++ [basic.scope.hiding]p2:
400 // A class name or enumeration name can be hidden by the name of
401 // an object, function, or enumerator declared in the same
402 // scope. If a class or enumeration name and an object, function,
403 // or enumerator are declared in the same scope (in any order)
404 // with the same name, the class or enumeration name is hidden
405 // wherever the object, function, or enumerator name is visible.
406 // But it's still an error if there are distinct tag types found,
407 // even if they're not visible. (ref?)
John McCall80053822009-12-03 00:58:24 +0000408 if (HideTags && HasTag && !Ambiguous &&
409 (HasFunction || HasNonFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000410 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000411
John McCall9f3059a2009-10-09 21:13:30 +0000412 Decls.set_size(N);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000413
John McCall80053822009-12-03 00:58:24 +0000414 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCall9f3059a2009-10-09 21:13:30 +0000415 Ambiguous = true;
Douglas Gregorf23311d2009-01-17 01:13:24 +0000416
John McCall9f3059a2009-10-09 21:13:30 +0000417 if (Ambiguous)
John McCall6538c932009-10-10 05:48:19 +0000418 setAmbiguous(LookupResult::AmbiguousReference);
John McCalle61f2ba2009-11-18 02:36:19 +0000419 else if (HasUnresolved)
420 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall283b9012009-11-22 00:44:51 +0000421 else if (N > 1 || HasFunctionTemplate)
John McCall27b18f82009-11-17 02:14:36 +0000422 ResultKind = LookupResult::FoundOverloaded;
John McCall9f3059a2009-10-09 21:13:30 +0000423 else
John McCall27b18f82009-11-17 02:14:36 +0000424 ResultKind = LookupResult::Found;
Douglas Gregor34074322009-01-14 22:20:51 +0000425}
426
John McCall5cebab12009-11-18 07:57:50 +0000427void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall5b0829a2010-02-10 09:31:12 +0000428 CXXBasePaths::const_paths_iterator I, E;
John McCall9f3059a2009-10-09 21:13:30 +0000429 DeclContext::lookup_iterator DI, DE;
430 for (I = P.begin(), E = P.end(); I != E; ++I)
431 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
432 addDecl(*DI);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000433}
434
John McCall5cebab12009-11-18 07:57:50 +0000435void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000436 Paths = new CXXBasePaths;
437 Paths->swap(P);
438 addDeclsFromBasePaths(*Paths);
439 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000440 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000441}
442
John McCall5cebab12009-11-18 07:57:50 +0000443void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCall9f3059a2009-10-09 21:13:30 +0000444 Paths = new CXXBasePaths;
445 Paths->swap(P);
446 addDeclsFromBasePaths(*Paths);
447 resolveKind();
John McCall6538c932009-10-10 05:48:19 +0000448 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCall9f3059a2009-10-09 21:13:30 +0000449}
450
John McCall5cebab12009-11-18 07:57:50 +0000451void LookupResult::print(llvm::raw_ostream &Out) {
John McCall9f3059a2009-10-09 21:13:30 +0000452 Out << Decls.size() << " result(s)";
453 if (isAmbiguous()) Out << ", ambiguous";
454 if (Paths) Out << ", base paths present";
455
456 for (iterator I = begin(), E = end(); I != E; ++I) {
457 Out << "\n";
458 (*I)->print(Out, 2);
459 }
460}
461
Douglas Gregord3a59182010-02-12 05:48:04 +0000462/// \brief Lookup a builtin function, when name lookup would otherwise
463/// fail.
464static bool LookupBuiltin(Sema &S, LookupResult &R) {
465 Sema::LookupNameKind NameKind = R.getLookupKind();
466
467 // If we didn't find a use of this identifier, and if the identifier
468 // corresponds to a compiler builtin, create the decl object for the builtin
469 // now, injecting it into translation unit scope, and return it.
470 if (NameKind == Sema::LookupOrdinaryName ||
471 NameKind == Sema::LookupRedeclarationWithLinkage) {
472 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
473 if (II) {
474 // If this is a builtin on this (or all) targets, create the decl.
475 if (unsigned BuiltinID = II->getBuiltinID()) {
476 // In C++, we don't have any predefined library functions like
477 // 'malloc'. Instead, we'll just error.
478 if (S.getLangOptions().CPlusPlus &&
479 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
480 return false;
481
482 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
483 S.TUScope, R.isForRedeclaration(),
484 R.getNameLoc());
485 if (D)
486 R.addDecl(D);
487 return (D != NULL);
488 }
489 }
490 }
491
492 return false;
493}
494
Douglas Gregor7454c562010-07-02 20:37:36 +0000495/// \brief Determine whether we can declare a special member function within
496/// the class at this point.
497static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
498 const CXXRecordDecl *Class) {
John McCall2ded5d22010-08-11 23:52:36 +0000499 // Don't do it if the class is invalid.
500 if (Class->isInvalidDecl())
501 return false;
502
Douglas Gregor7454c562010-07-02 20:37:36 +0000503 // We need to have a definition for the class.
504 if (!Class->getDefinition() || Class->isDependentContext())
505 return false;
506
507 // We can't be in the middle of defining the class.
508 if (const RecordType *RecordTy
509 = Context.getTypeDeclType(Class)->getAs<RecordType>())
510 return !RecordTy->isBeingDefined();
511
512 return false;
513}
514
515void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000516 if (!CanDeclareSpecialMemberFunction(Context, Class))
517 return;
Douglas Gregor9672f922010-07-03 00:47:00 +0000518
519 // If the default constructor has not yet been declared, do so now.
520 if (!Class->hasDeclaredDefaultConstructor())
521 DeclareImplicitDefaultConstructor(Class);
Douglas Gregora6d69502010-07-02 23:41:54 +0000522
523 // If the copy constructor has not yet been declared, do so now.
524 if (!Class->hasDeclaredCopyConstructor())
525 DeclareImplicitCopyConstructor(Class);
526
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000527 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000528 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000529 DeclareImplicitCopyAssignment(Class);
530
Douglas Gregor7454c562010-07-02 20:37:36 +0000531 // If the destructor has not yet been declared, do so now.
Douglas Gregora6d69502010-07-02 23:41:54 +0000532 if (!Class->hasDeclaredDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +0000533 DeclareImplicitDestructor(Class);
534}
535
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000536/// \brief Determine whether this is the name of an implicitly-declared
537/// special member function.
538static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
539 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000540 case DeclarationName::CXXConstructorName:
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000541 case DeclarationName::CXXDestructorName:
542 return true;
543
544 case DeclarationName::CXXOperatorName:
545 return Name.getCXXOverloadedOperator() == OO_Equal;
546
547 default:
548 break;
549 }
550
551 return false;
552}
553
554/// \brief If there are any implicit member functions with the given name
555/// that need to be declared in the given declaration context, do so.
556static void DeclareImplicitMemberFunctionsWithName(Sema &S,
557 DeclarationName Name,
558 const DeclContext *DC) {
559 if (!DC)
560 return;
561
562 switch (Name.getNameKind()) {
Douglas Gregora6d69502010-07-02 23:41:54 +0000563 case DeclarationName::CXXConstructorName:
564 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor9672f922010-07-03 00:47:00 +0000565 if (Record->getDefinition() &&
566 CanDeclareSpecialMemberFunction(S.Context, Record)) {
567 if (!Record->hasDeclaredDefaultConstructor())
568 S.DeclareImplicitDefaultConstructor(
569 const_cast<CXXRecordDecl *>(Record));
570 if (!Record->hasDeclaredCopyConstructor())
571 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
572 }
Douglas Gregora6d69502010-07-02 23:41:54 +0000573 break;
574
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000575 case DeclarationName::CXXDestructorName:
576 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
577 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
578 CanDeclareSpecialMemberFunction(S.Context, Record))
579 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000580 break;
581
582 case DeclarationName::CXXOperatorName:
583 if (Name.getCXXOverloadedOperator() != OO_Equal)
584 break;
585
586 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
587 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
588 CanDeclareSpecialMemberFunction(S.Context, Record))
589 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
590 break;
591
592 default:
593 break;
594 }
595}
Douglas Gregor7454c562010-07-02 20:37:36 +0000596
John McCall9f3059a2009-10-09 21:13:30 +0000597// Adds all qualifying matches for a name within a decl context to the
598// given lookup result. Returns true if any matches were found.
Douglas Gregord3a59182010-02-12 05:48:04 +0000599static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCall9f3059a2009-10-09 21:13:30 +0000600 bool Found = false;
601
Douglas Gregor7454c562010-07-02 20:37:36 +0000602 // Lazily declare C++ special member functions.
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000603 if (S.getLangOptions().CPlusPlus)
604 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor7454c562010-07-02 20:37:36 +0000605
606 // Perform lookup into this declaration context.
John McCallf6c8a4e2009-11-10 07:01:13 +0000607 DeclContext::lookup_const_iterator I, E;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000608 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall401982f2010-01-20 21:53:11 +0000609 NamedDecl *D = *I;
610 if (R.isAcceptableDecl(D)) {
611 R.addDecl(D);
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000612 Found = true;
613 }
614 }
John McCall9f3059a2009-10-09 21:13:30 +0000615
Douglas Gregord3a59182010-02-12 05:48:04 +0000616 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
617 return true;
618
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000619 if (R.getLookupName().getNameKind()
Chandler Carruth3a693b72010-01-31 11:44:02 +0000620 != DeclarationName::CXXConversionFunctionName ||
621 R.getLookupName().getCXXNameType()->isDependentType() ||
622 !isa<CXXRecordDecl>(DC))
623 return Found;
624
625 // C++ [temp.mem]p6:
626 // A specialization of a conversion function template is not found by
627 // name lookup. Instead, any conversion function templates visible in the
628 // context of the use are considered. [...]
629 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
630 if (!Record->isDefinition())
631 return Found;
632
633 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
634 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
635 UEnd = Unresolved->end(); U != UEnd; ++U) {
636 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
637 if (!ConvTemplate)
638 continue;
639
640 // When we're performing lookup for the purposes of redeclaration, just
641 // add the conversion function template. When we deduce template
642 // arguments for specializations, we'll end up unifying the return
643 // type of the new declaration with the type of the function template.
644 if (R.isForRedeclaration()) {
645 R.addDecl(ConvTemplate);
646 Found = true;
647 continue;
648 }
649
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000650 // C++ [temp.mem]p6:
Chandler Carruth3a693b72010-01-31 11:44:02 +0000651 // [...] For each such operator, if argument deduction succeeds
652 // (14.9.2.3), the resulting specialization is used as if found by
653 // name lookup.
654 //
655 // When referencing a conversion function for any purpose other than
656 // a redeclaration (such that we'll be building an expression with the
657 // result), perform template argument deduction and place the
658 // specialization into the result set. We do this to avoid forcing all
659 // callers to perform special deduction for conversion functions.
John McCall19c1bfd2010-08-25 05:32:35 +0000660 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruth3a693b72010-01-31 11:44:02 +0000661 FunctionDecl *Specialization = 0;
662
663 const FunctionProtoType *ConvProto
664 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
665 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3c96a462010-01-12 01:17:50 +0000666
Chandler Carruth3a693b72010-01-31 11:44:02 +0000667 // Compute the type of the function that we would expect the conversion
668 // function to have, if it were to match the name given.
669 // FIXME: Calling convention!
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000670 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruth3a693b72010-01-31 11:44:02 +0000671 QualType ExpectedType
672 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
673 0, 0, ConvProto->isVariadic(),
674 ConvProto->getTypeQuals(),
675 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000676 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruth3a693b72010-01-31 11:44:02 +0000677
678 // Perform template argument deduction against the type that we would
679 // expect the function to have.
680 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
681 Specialization, Info)
682 == Sema::TDK_Success) {
683 R.addDecl(Specialization);
684 Found = true;
Douglas Gregorea0a0a92010-01-11 18:40:55 +0000685 }
686 }
Chandler Carruth3a693b72010-01-31 11:44:02 +0000687
John McCall9f3059a2009-10-09 21:13:30 +0000688 return Found;
689}
690
John McCallf6c8a4e2009-11-10 07:01:13 +0000691// Performs C++ unqualified lookup into the given file context.
John McCall9f3059a2009-10-09 21:13:30 +0000692static bool
Douglas Gregord3a59182010-02-12 05:48:04 +0000693CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
694 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000695
696 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
697
John McCallf6c8a4e2009-11-10 07:01:13 +0000698 // Perform direct name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +0000699 bool Found = LookupDirect(S, R, NS);
Douglas Gregor700792c2009-02-05 19:25:20 +0000700
John McCallf6c8a4e2009-11-10 07:01:13 +0000701 // Perform direct name lookup into the namespaces nominated by the
702 // using directives whose common ancestor is this namespace.
703 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
704 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump11289f42009-09-09 15:08:12 +0000705
John McCallf6c8a4e2009-11-10 07:01:13 +0000706 for (; UI != UEnd; ++UI)
Douglas Gregord3a59182010-02-12 05:48:04 +0000707 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCallf6c8a4e2009-11-10 07:01:13 +0000708 Found = true;
John McCall9f3059a2009-10-09 21:13:30 +0000709
710 R.resolveKind();
711
712 return Found;
Douglas Gregor700792c2009-02-05 19:25:20 +0000713}
714
715static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000716 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000717 return Ctx->isFileContext();
718 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000719}
Douglas Gregored8f2882009-01-30 01:04:22 +0000720
Douglas Gregor66230062010-03-15 14:33:29 +0000721// Find the next outer declaration context from this scope. This
722// routine actually returns the semantic outer context, which may
723// differ from the lexical context (encoded directly in the Scope
724// stack) when we are parsing a member of a class template. In this
725// case, the second element of the pair will be true, to indicate that
726// name lookup should continue searching in this semantic context when
727// it leaves the current template parameter scope.
728static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
729 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
730 DeclContext *Lexical = 0;
731 for (Scope *OuterS = S->getParent(); OuterS;
732 OuterS = OuterS->getParent()) {
733 if (OuterS->getEntity()) {
Douglas Gregorea166062010-03-15 15:26:48 +0000734 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor66230062010-03-15 14:33:29 +0000735 break;
736 }
737 }
738
739 // C++ [temp.local]p8:
740 // In the definition of a member of a class template that appears
741 // outside of the namespace containing the class template
742 // definition, the name of a template-parameter hides the name of
743 // a member of this namespace.
744 //
745 // Example:
746 //
747 // namespace N {
748 // class C { };
749 //
750 // template<class T> class B {
751 // void f(T);
752 // };
753 // }
754 //
755 // template<class C> void N::B<C>::f(C) {
756 // C b; // C is the template parameter, not N::C
757 // }
758 //
759 // In this example, the lexical context we return is the
760 // TranslationUnit, while the semantic context is the namespace N.
761 if (!Lexical || !DC || !S->getParent() ||
762 !S->getParent()->isTemplateParamScope())
763 return std::make_pair(Lexical, false);
764
765 // Find the outermost template parameter scope.
766 // For the example, this is the scope for the template parameters of
767 // template<class C>.
768 Scope *OutermostTemplateScope = S->getParent();
769 while (OutermostTemplateScope->getParent() &&
770 OutermostTemplateScope->getParent()->isTemplateParamScope())
771 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregor7f737c02009-09-10 16:57:35 +0000772
Douglas Gregor66230062010-03-15 14:33:29 +0000773 // Find the namespace context in which the original scope occurs. In
774 // the example, this is namespace N.
775 DeclContext *Semantic = DC;
776 while (!Semantic->isFileContext())
777 Semantic = Semantic->getParent();
778
779 // Find the declaration context just outside of the template
780 // parameter scope. This is the context in which the template is
781 // being lexically declaration (a namespace context). In the
782 // example, this is the global scope.
783 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
784 Lexical->Encloses(Semantic))
785 return std::make_pair(Semantic, true);
786
787 return std::make_pair(Lexical, false);
Douglas Gregor7f737c02009-09-10 16:57:35 +0000788}
789
John McCall27b18f82009-11-17 02:14:36 +0000790bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCallea305ed2009-12-18 10:40:03 +0000791 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCall27b18f82009-11-17 02:14:36 +0000792
793 DeclarationName Name = R.getLookupName();
794
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000795 // If this is the name of an implicitly-declared special member function,
796 // go through the scope stack to implicitly declare
797 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
798 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
799 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
800 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
801 }
802
803 // Implicitly declare member functions with the name we're looking for, if in
804 // fact we are in a scope where it matters.
805
Douglas Gregor889ceb72009-02-03 19:21:40 +0000806 Scope *Initial = S;
Mike Stump11289f42009-09-09 15:08:12 +0000807 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000808 I = IdResolver.begin(Name),
809 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000810
Douglas Gregor889ceb72009-02-03 19:21:40 +0000811 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000812 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000813 // ...During unqualified name lookup (3.4.1), the names appear as if
814 // they were declared in the nearest enclosing namespace which contains
815 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000816 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000817 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000818 //
819 // For example:
820 // namespace A { int i; }
821 // void foo() {
822 // int i;
823 // {
824 // using namespace A;
825 // ++i; // finds local 'i', A::i appears at global scope
826 // }
827 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000828 //
Douglas Gregor66230062010-03-15 14:33:29 +0000829 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor700792c2009-02-05 19:25:20 +0000830 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor3e51e172010-05-20 20:58:56 +0000831 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
832
Douglas Gregor889ceb72009-02-03 19:21:40 +0000833 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000834 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000835 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000836 if (R.isAcceptableDecl(*I)) {
John McCall9f3059a2009-10-09 21:13:30 +0000837 Found = true;
838 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000839 }
840 }
John McCall9f3059a2009-10-09 21:13:30 +0000841 if (Found) {
842 R.resolveKind();
Douglas Gregor3e51e172010-05-20 20:58:56 +0000843 if (S->isClassScope())
844 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
845 R.setNamingClass(Record);
John McCall9f3059a2009-10-09 21:13:30 +0000846 return true;
847 }
848
Douglas Gregor66230062010-03-15 14:33:29 +0000849 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
850 S->getParent() && !S->getParent()->isTemplateParamScope()) {
851 // We've just searched the last template parameter scope and
852 // found nothing, so look into the the contexts between the
853 // lexical and semantic declaration contexts returned by
854 // findOuterContext(). This implements the name lookup behavior
855 // of C++ [temp.local]p8.
856 Ctx = OutsideOfTemplateParamDC;
857 OutsideOfTemplateParamDC = 0;
858 }
859
860 if (Ctx) {
861 DeclContext *OuterCtx;
862 bool SearchAfterTemplateScope;
863 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
864 if (SearchAfterTemplateScope)
865 OutsideOfTemplateParamDC = OuterCtx;
866
Douglas Gregorea166062010-03-15 15:26:48 +0000867 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor337caf92010-02-19 16:08:35 +0000868 // We do not directly look into transparent contexts, since
869 // those entities will be found in the nearest enclosing
870 // non-transparent context.
871 if (Ctx->isTransparentContext())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000872 continue;
Douglas Gregor337caf92010-02-19 16:08:35 +0000873
874 // We do not look directly into function or method contexts,
875 // since all of the local variables and parameters of the
876 // function/method are present within the Scope.
877 if (Ctx->isFunctionOrMethod()) {
878 // If we have an Objective-C instance method, look for ivars
879 // in the corresponding interface.
880 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
881 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
882 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
883 ObjCInterfaceDecl *ClassDeclared;
884 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
885 Name.getAsIdentifierInfo(),
886 ClassDeclared)) {
887 if (R.isAcceptableDecl(Ivar)) {
888 R.addDecl(Ivar);
889 R.resolveKind();
890 return true;
891 }
892 }
893 }
894 }
895
896 continue;
897 }
898
Douglas Gregor7f737c02009-09-10 16:57:35 +0000899 // Perform qualified name lookup into this context.
900 // FIXME: In some cases, we know that every name that could be found by
901 // this qualified name lookup will also be on the identifier chain. For
902 // example, inside a class without any base classes, we never need to
903 // perform qualified lookup because all of the members are on top of the
904 // identifier chain.
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000905 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCall9f3059a2009-10-09 21:13:30 +0000906 return true;
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000907 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000908 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000909 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000910
John McCallf6c8a4e2009-11-10 07:01:13 +0000911 // Stop if we ran out of scopes.
912 // FIXME: This really, really shouldn't be happening.
913 if (!S) return false;
914
Douglas Gregor700792c2009-02-05 19:25:20 +0000915 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000916 // nominated namespaces by those using-directives.
John McCallf6c8a4e2009-11-10 07:01:13 +0000917 //
Mike Stump87c57ac2009-05-16 07:39:55 +0000918 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
919 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000920
John McCallf6c8a4e2009-11-10 07:01:13 +0000921 UnqualUsingDirectiveSet UDirs;
922 UDirs.visitScopeChain(Initial, S);
923 UDirs.done();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000924
Douglas Gregor700792c2009-02-05 19:25:20 +0000925 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000926 // Unqualified name lookup in C++ requires looking into scopes
927 // that aren't strictly lexical, and therefore we walk through the
928 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000929
Douglas Gregor889ceb72009-02-03 19:21:40 +0000930 for (; S; S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000931 // Check whether the IdResolver has anything in this scope.
John McCall9f3059a2009-10-09 21:13:30 +0000932 bool Found = false;
John McCall48871652010-08-21 09:40:31 +0000933 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCallea305ed2009-12-18 10:40:03 +0000934 if (R.isAcceptableDecl(*I)) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000935 // We found something. Look for anything else in our scope
936 // with this same name and in an acceptable identifier
937 // namespace, so that we can construct an overload set if we
938 // need to.
John McCall9f3059a2009-10-09 21:13:30 +0000939 Found = true;
940 R.addDecl(*I);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000941 }
942 }
943
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000944 if (Found && S->isTemplateParamScope()) {
John McCall9f3059a2009-10-09 21:13:30 +0000945 R.resolveKind();
946 return true;
947 }
948
Douglas Gregorf3d3ae62010-05-14 04:53:42 +0000949 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
950 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
951 S->getParent() && !S->getParent()->isTemplateParamScope()) {
952 // We've just searched the last template parameter scope and
953 // found nothing, so look into the the contexts between the
954 // lexical and semantic declaration contexts returned by
955 // findOuterContext(). This implements the name lookup behavior
956 // of C++ [temp.local]p8.
957 Ctx = OutsideOfTemplateParamDC;
958 OutsideOfTemplateParamDC = 0;
959 }
960
961 if (Ctx) {
962 DeclContext *OuterCtx;
963 bool SearchAfterTemplateScope;
964 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
965 if (SearchAfterTemplateScope)
966 OutsideOfTemplateParamDC = OuterCtx;
967
968 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
969 // We do not directly look into transparent contexts, since
970 // those entities will be found in the nearest enclosing
971 // non-transparent context.
972 if (Ctx->isTransparentContext())
973 continue;
974
975 // If we have a context, and it's not a context stashed in the
976 // template parameter scope for an out-of-line definition, also
977 // look into that context.
978 if (!(Found && S && S->isTemplateParamScope())) {
979 assert(Ctx->isFileContext() &&
980 "We should have been looking only at file context here already.");
981
982 // Look into context considering using-directives.
983 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
984 Found = true;
985 }
986
987 if (Found) {
988 R.resolveKind();
989 return true;
990 }
991
992 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
993 return false;
994 }
995 }
996
Douglas Gregor3ce74932010-02-05 07:07:10 +0000997 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCall9f3059a2009-10-09 21:13:30 +0000998 return false;
Douglas Gregor700792c2009-02-05 19:25:20 +0000999 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001000
John McCall9f3059a2009-10-09 21:13:30 +00001001 return !R.empty();
Douglas Gregored8f2882009-01-30 01:04:22 +00001002}
1003
Douglas Gregor34074322009-01-14 22:20:51 +00001004/// @brief Perform unqualified name lookup starting from a given
1005/// scope.
1006///
1007/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1008/// used to find names within the current scope. For example, 'x' in
1009/// @code
1010/// int x;
1011/// int f() {
1012/// return x; // unqualified name look finds 'x' in the global scope
1013/// }
1014/// @endcode
1015///
1016/// Different lookup criteria can find different names. For example, a
1017/// particular scope can have both a struct and a function of the same
1018/// name, and each can be found by certain lookup criteria. For more
1019/// information about lookup criteria, see the documentation for the
1020/// class LookupCriteria.
1021///
1022/// @param S The scope from which unqualified name lookup will
1023/// begin. If the lookup criteria permits, name lookup may also search
1024/// in the parent scopes.
1025///
1026/// @param Name The name of the entity that we are searching for.
1027///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001028/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001029/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001030/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +00001031///
1032/// @returns The result of name lookup, which includes zero or more
1033/// declarations and possibly additional information used to diagnose
1034/// ambiguities.
John McCall27b18f82009-11-17 02:14:36 +00001035bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1036 DeclarationName Name = R.getLookupName();
John McCall9f3059a2009-10-09 21:13:30 +00001037 if (!Name) return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001038
John McCall27b18f82009-11-17 02:14:36 +00001039 LookupNameKind NameKind = R.getLookupKind();
1040
Douglas Gregor34074322009-01-14 22:20:51 +00001041 if (!getLangOptions().CPlusPlus) {
1042 // Unqualified name lookup in C/Objective-C is purely lexical, so
1043 // search in the declarations attached to the name.
1044
John McCallea305ed2009-12-18 10:40:03 +00001045 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001046 // Find the nearest non-transparent declaration scope.
1047 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +00001048 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +00001049 static_cast<DeclContext *>(S->getEntity())
1050 ->isTransparentContext()))
1051 S = S->getParent();
Douglas Gregored8f2882009-01-30 01:04:22 +00001052 }
1053
John McCallea305ed2009-12-18 10:40:03 +00001054 unsigned IDNS = R.getIdentifierNamespace();
1055
Douglas Gregor34074322009-01-14 22:20:51 +00001056 // Scan up the scope chain looking for a decl that matches this
1057 // identifier that is in the appropriate namespace. This search
1058 // should not take long, as shadowing of names is uncommon, and
1059 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +00001060 bool LeftStartingScope = false;
1061
Douglas Gregored8f2882009-01-30 01:04:22 +00001062 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +00001063 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +00001064 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001065 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +00001066 if (NameKind == LookupRedeclarationWithLinkage) {
1067 // Determine whether this (or a previous) declaration is
1068 // out-of-scope.
John McCall48871652010-08-21 09:40:31 +00001069 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregoreddf4332009-02-24 20:03:32 +00001070 LeftStartingScope = true;
1071
1072 // If we found something outside of our starting scope that
1073 // does not have linkage, skip it.
1074 if (LeftStartingScope && !((*I)->hasLinkage()))
1075 continue;
1076 }
1077
John McCall9f3059a2009-10-09 21:13:30 +00001078 R.addDecl(*I);
1079
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001080 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001081 // If this declaration has the "overloadable" attribute, we
1082 // might have a set of overloaded functions.
1083
1084 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +00001085 while (!(S->getFlags() & Scope::DeclScope) ||
John McCall48871652010-08-21 09:40:31 +00001086 !S->isDeclScope(*I))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001087 S = S->getParent();
1088
1089 // Find the last declaration in this scope (with the same
1090 // name, naturally).
1091 IdentifierResolver::iterator LastI = I;
1092 for (++LastI; LastI != IEnd; ++LastI) {
John McCall48871652010-08-21 09:40:31 +00001093 if (!S->isDeclScope(*LastI))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001094 break;
John McCall9f3059a2009-10-09 21:13:30 +00001095 R.addDecl(*LastI);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001096 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001097 }
1098
John McCall9f3059a2009-10-09 21:13:30 +00001099 R.resolveKind();
1100
1101 return true;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001102 }
Douglas Gregor34074322009-01-14 22:20:51 +00001103 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001104 // Perform C++ unqualified name lookup.
John McCall27b18f82009-11-17 02:14:36 +00001105 if (CppLookupName(R, S))
John McCall9f3059a2009-10-09 21:13:30 +00001106 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001107 }
1108
1109 // If we didn't find a use of this identifier, and if the identifier
1110 // corresponds to a compiler builtin, create the decl object for the builtin
1111 // now, injecting it into translation unit scope, and return it.
Douglas Gregord3a59182010-02-12 05:48:04 +00001112 if (AllowBuiltinCreation)
1113 return LookupBuiltin(*this, R);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001114
John McCall9f3059a2009-10-09 21:13:30 +00001115 return false;
Douglas Gregor34074322009-01-14 22:20:51 +00001116}
1117
John McCall6538c932009-10-10 05:48:19 +00001118/// @brief Perform qualified name lookup in the namespaces nominated by
1119/// using directives by the given context.
1120///
1121/// C++98 [namespace.qual]p2:
1122/// Given X::m (where X is a user-declared namespace), or given ::m
1123/// (where X is the global namespace), let S be the set of all
1124/// declarations of m in X and in the transitive closure of all
1125/// namespaces nominated by using-directives in X and its used
1126/// namespaces, except that using-directives are ignored in any
1127/// namespace, including X, directly containing one or more
1128/// declarations of m. No namespace is searched more than once in
1129/// the lookup of a name. If S is the empty set, the program is
1130/// ill-formed. Otherwise, if S has exactly one member, or if the
1131/// context of the reference is a using-declaration
1132/// (namespace.udecl), S is the required set of declarations of
1133/// m. Otherwise if the use of m is not one that allows a unique
1134/// declaration to be chosen from S, the program is ill-formed.
1135/// C++98 [namespace.qual]p5:
1136/// During the lookup of a qualified namespace member name, if the
1137/// lookup finds more than one declaration of the member, and if one
1138/// declaration introduces a class name or enumeration name and the
1139/// other declarations either introduce the same object, the same
1140/// enumerator or a set of functions, the non-type name hides the
1141/// class or enumeration name if and only if the declarations are
1142/// from the same namespace; otherwise (the declarations are from
1143/// different namespaces), the program is ill-formed.
Douglas Gregord3a59182010-02-12 05:48:04 +00001144static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCall27b18f82009-11-17 02:14:36 +00001145 DeclContext *StartDC) {
John McCall6538c932009-10-10 05:48:19 +00001146 assert(StartDC->isFileContext() && "start context is not a file context");
1147
1148 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1149 DeclContext::udir_iterator E = StartDC->using_directives_end();
1150
1151 if (I == E) return false;
1152
1153 // We have at least added all these contexts to the queue.
1154 llvm::DenseSet<DeclContext*> Visited;
1155 Visited.insert(StartDC);
1156
1157 // We have not yet looked into these namespaces, much less added
1158 // their "using-children" to the queue.
1159 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1160
1161 // We have already looked into the initial namespace; seed the queue
1162 // with its using-children.
1163 for (; I != E; ++I) {
John McCallb8be78b2009-11-10 09:25:37 +00001164 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6538c932009-10-10 05:48:19 +00001165 if (Visited.insert(ND).second)
1166 Queue.push_back(ND);
1167 }
1168
1169 // The easiest way to implement the restriction in [namespace.qual]p5
1170 // is to check whether any of the individual results found a tag
1171 // and, if so, to declare an ambiguity if the final result is not
1172 // a tag.
1173 bool FoundTag = false;
1174 bool FoundNonTag = false;
1175
John McCall5cebab12009-11-18 07:57:50 +00001176 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6538c932009-10-10 05:48:19 +00001177
1178 bool Found = false;
1179 while (!Queue.empty()) {
1180 NamespaceDecl *ND = Queue.back();
1181 Queue.pop_back();
1182
1183 // We go through some convolutions here to avoid copying results
1184 // between LookupResults.
1185 bool UseLocal = !R.empty();
John McCall5cebab12009-11-18 07:57:50 +00001186 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregord3a59182010-02-12 05:48:04 +00001187 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6538c932009-10-10 05:48:19 +00001188
1189 if (FoundDirect) {
1190 // First do any local hiding.
1191 DirectR.resolveKind();
1192
1193 // If the local result is a tag, remember that.
1194 if (DirectR.isSingleTagDecl())
1195 FoundTag = true;
1196 else
1197 FoundNonTag = true;
1198
1199 // Append the local results to the total results if necessary.
1200 if (UseLocal) {
1201 R.addAllDecls(LocalR);
1202 LocalR.clear();
1203 }
1204 }
1205
1206 // If we find names in this namespace, ignore its using directives.
1207 if (FoundDirect) {
1208 Found = true;
1209 continue;
1210 }
1211
1212 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1213 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1214 if (Visited.insert(Nom).second)
1215 Queue.push_back(Nom);
1216 }
1217 }
1218
1219 if (Found) {
1220 if (FoundTag && FoundNonTag)
1221 R.setAmbiguousQualifiedTagHiding();
1222 else
1223 R.resolveKind();
1224 }
1225
1226 return Found;
1227}
1228
Douglas Gregor39982192010-08-15 06:18:01 +00001229/// \brief Callback that looks for any member of a class with the given name.
1230static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1231 CXXBasePath &Path,
1232 void *Name) {
1233 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1234
1235 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1236 Path.Decls = BaseRecord->lookup(N);
1237 return Path.Decls.first != Path.Decls.second;
1238}
1239
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001240/// \brief Perform qualified name lookup into a given context.
Douglas Gregor34074322009-01-14 22:20:51 +00001241///
1242/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1243/// names when the context of those names is explicit specified, e.g.,
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001244/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001245///
1246/// Different lookup criteria can find different names. For example, a
1247/// particular scope can have both a struct and a function of the same
1248/// name, and each can be found by certain lookup criteria. For more
1249/// information about lookup criteria, see the documentation for the
1250/// class LookupCriteria.
1251///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001252/// \param R captures both the lookup criteria and any lookup results found.
1253///
1254/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregor34074322009-01-14 22:20:51 +00001255/// search. If the lookup criteria permits, name lookup may also search
1256/// in the parent contexts or (for C++ classes) base classes.
1257///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001258/// \param InUnqualifiedLookup true if this is qualified name lookup that
1259/// occurs as part of unqualified name lookup.
Douglas Gregor34074322009-01-14 22:20:51 +00001260///
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001261/// \returns true if lookup succeeded, false if it failed.
1262bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1263 bool InUnqualifiedLookup) {
Douglas Gregor34074322009-01-14 22:20:51 +00001264 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001265
John McCall27b18f82009-11-17 02:14:36 +00001266 if (!R.getLookupName())
John McCall9f3059a2009-10-09 21:13:30 +00001267 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001268
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001269 // Make sure that the declaration context is complete.
1270 assert((!isa<TagDecl>(LookupCtx) ||
1271 LookupCtx->isDependentContext() ||
1272 cast<TagDecl>(LookupCtx)->isDefinition() ||
1273 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1274 ->isBeingDefined()) &&
1275 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001276
Douglas Gregor34074322009-01-14 22:20:51 +00001277 // Perform qualified name lookup into the LookupCtx.
Douglas Gregord3a59182010-02-12 05:48:04 +00001278 if (LookupDirect(*this, R, LookupCtx)) {
John McCall9f3059a2009-10-09 21:13:30 +00001279 R.resolveKind();
John McCall553c0792010-01-23 00:46:32 +00001280 if (isa<CXXRecordDecl>(LookupCtx))
1281 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCall9f3059a2009-10-09 21:13:30 +00001282 return true;
1283 }
Douglas Gregor34074322009-01-14 22:20:51 +00001284
John McCall6538c932009-10-10 05:48:19 +00001285 // Don't descend into implied contexts for redeclarations.
1286 // C++98 [namespace.qual]p6:
1287 // In a declaration for a namespace member in which the
1288 // declarator-id is a qualified-id, given that the qualified-id
1289 // for the namespace member has the form
1290 // nested-name-specifier unqualified-id
1291 // the unqualified-id shall name a member of the namespace
1292 // designated by the nested-name-specifier.
1293 // See also [class.mfct]p5 and [class.static.data]p2.
John McCall27b18f82009-11-17 02:14:36 +00001294 if (R.isForRedeclaration())
John McCall6538c932009-10-10 05:48:19 +00001295 return false;
1296
John McCall27b18f82009-11-17 02:14:36 +00001297 // If this is a namespace, look it up in the implied namespaces.
John McCall6538c932009-10-10 05:48:19 +00001298 if (LookupCtx->isFileContext())
Douglas Gregord3a59182010-02-12 05:48:04 +00001299 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6538c932009-10-10 05:48:19 +00001300
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001301 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregorcc2427c2009-09-11 22:57:37 +00001302 // classes, we're done.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001303 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor5a5fcd82010-07-01 00:21:21 +00001304 if (!LookupRec || !LookupRec->getDefinition())
John McCall9f3059a2009-10-09 21:13:30 +00001305 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001306
Douglas Gregord0d2ee02010-01-15 01:44:47 +00001307 // If we're performing qualified name lookup into a dependent class,
1308 // then we are actually looking into a current instantiation. If we have any
1309 // dependent base classes, then we either have to delay lookup until
1310 // template instantiation time (at which point all bases will be available)
1311 // or we have to fail.
1312 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1313 LookupRec->hasAnyDependentBases()) {
1314 R.setNotFoundInCurrentInstantiation();
1315 return false;
1316 }
1317
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001318 // Perform lookup into our base classes.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001319 CXXBasePaths Paths;
1320 Paths.setOrigin(LookupRec);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001321
1322 // Look for this member in our base classes
Douglas Gregor36d1b142009-10-06 17:59:45 +00001323 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCall27b18f82009-11-17 02:14:36 +00001324 switch (R.getLookupKind()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001325 case LookupOrdinaryName:
1326 case LookupMemberName:
1327 case LookupRedeclarationWithLinkage:
1328 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1329 break;
1330
1331 case LookupTagName:
1332 BaseCallback = &CXXRecordDecl::FindTagMember;
1333 break;
John McCall84d87672009-12-10 09:41:52 +00001334
Douglas Gregor39982192010-08-15 06:18:01 +00001335 case LookupAnyName:
1336 BaseCallback = &LookupAnyMember;
1337 break;
1338
John McCall84d87672009-12-10 09:41:52 +00001339 case LookupUsingDeclName:
1340 // This lookup is for redeclarations only.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001341
1342 case LookupOperatorName:
1343 case LookupNamespaceName:
1344 case LookupObjCProtocolName:
Douglas Gregor36d1b142009-10-06 17:59:45 +00001345 // These lookups will never find a member in a C++ class (or base class).
John McCall9f3059a2009-10-09 21:13:30 +00001346 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001347
1348 case LookupNestedNameSpecifierName:
1349 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1350 break;
1351 }
1352
John McCall27b18f82009-11-17 02:14:36 +00001353 if (!LookupRec->lookupInBases(BaseCallback,
1354 R.getLookupName().getAsOpaquePtr(), Paths))
John McCall9f3059a2009-10-09 21:13:30 +00001355 return false;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001356
John McCall553c0792010-01-23 00:46:32 +00001357 R.setNamingClass(LookupRec);
1358
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001359 // C++ [class.member.lookup]p2:
1360 // [...] If the resulting set of declarations are not all from
1361 // sub-objects of the same type, or the set has a nonstatic member
1362 // and includes members from distinct sub-objects, there is an
1363 // ambiguity and the program is ill-formed. Otherwise that set is
1364 // the result of the lookup.
1365 // FIXME: support using declarations!
1366 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001367 int SubobjectNumber = 0;
John McCalla332b952010-03-18 23:49:19 +00001368 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001369 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001370 Path != PathEnd; ++Path) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001371 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001372
John McCall401982f2010-01-20 21:53:11 +00001373 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1374 // across all paths.
1375 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1376
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001377 // Determine whether we're looking at a distinct sub-object or not.
1378 if (SubobjectType.isNull()) {
John McCall9f3059a2009-10-09 21:13:30 +00001379 // This is the first subobject we've looked at. Record its type.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001380 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1381 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001382 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001383 != Context.getCanonicalType(PathElement.Base->getType())) {
1384 // We found members of the given name in two subobjects of
1385 // different types. This lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001386 R.setAmbiguousBaseSubobjectTypes(Paths);
1387 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001388 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1389 // We have a different subobject of the same type.
1390
1391 // C++ [class.member.lookup]p5:
1392 // A static member, a nested type or an enumerator defined in
1393 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001394 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001395 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001396 if (isa<VarDecl>(FirstDecl) ||
1397 isa<TypeDecl>(FirstDecl) ||
1398 isa<EnumConstantDecl>(FirstDecl))
1399 continue;
1400
1401 if (isa<CXXMethodDecl>(FirstDecl)) {
1402 // Determine whether all of the methods are static.
1403 bool AllMethodsAreStatic = true;
1404 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1405 Func != Path->Decls.second; ++Func) {
1406 if (!isa<CXXMethodDecl>(*Func)) {
1407 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1408 break;
1409 }
1410
1411 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1412 AllMethodsAreStatic = false;
1413 break;
1414 }
1415 }
1416
1417 if (AllMethodsAreStatic)
1418 continue;
1419 }
1420
1421 // We have found a nonstatic member name in multiple, distinct
1422 // subobjects. Name lookup is ambiguous.
John McCall9f3059a2009-10-09 21:13:30 +00001423 R.setAmbiguousBaseSubobjects(Paths);
1424 return true;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001425 }
1426 }
1427
1428 // Lookup in a base class succeeded; return these results.
1429
John McCall9f3059a2009-10-09 21:13:30 +00001430 DeclContext::lookup_iterator I, E;
John McCall553c0792010-01-23 00:46:32 +00001431 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1432 NamedDecl *D = *I;
1433 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1434 D->getAccess());
1435 R.addDecl(D, AS);
1436 }
John McCall9f3059a2009-10-09 21:13:30 +00001437 R.resolveKind();
1438 return true;
Douglas Gregor34074322009-01-14 22:20:51 +00001439}
1440
1441/// @brief Performs name lookup for a name that was parsed in the
1442/// source code, and may contain a C++ scope specifier.
1443///
1444/// This routine is a convenience routine meant to be called from
1445/// contexts that receive a name and an optional C++ scope specifier
1446/// (e.g., "N::M::x"). It will then perform either qualified or
1447/// unqualified name lookup (with LookupQualifiedName or LookupName,
1448/// respectively) on the given name and return those results.
1449///
1450/// @param S The scope from which unqualified name lookup will
1451/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001452///
Douglas Gregore861bac2009-08-25 22:51:20 +00001453/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001454///
1455/// @param Name The name of the entity that name lookup will
1456/// search for.
1457///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001458/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001459/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001460/// C library functions (like "malloc") are implicitly declared.
1461///
Douglas Gregore861bac2009-08-25 22:51:20 +00001462/// @param EnteringContext Indicates whether we are going to enter the
1463/// context of the scope-specifier SS (if present).
1464///
John McCall9f3059a2009-10-09 21:13:30 +00001465/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001466bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCall27b18f82009-11-17 02:14:36 +00001467 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregore861bac2009-08-25 22:51:20 +00001468 if (SS && SS->isInvalid()) {
1469 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001470 // anything.
John McCall9f3059a2009-10-09 21:13:30 +00001471 return false;
Douglas Gregore861bac2009-08-25 22:51:20 +00001472 }
Mike Stump11289f42009-09-09 15:08:12 +00001473
Douglas Gregore861bac2009-08-25 22:51:20 +00001474 if (SS && SS->isSet()) {
1475 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001476 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001477 // contex, and will perform name lookup in that context.
John McCall0b66eb32010-05-01 00:40:08 +00001478 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCall9f3059a2009-10-09 21:13:30 +00001479 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001480
John McCall27b18f82009-11-17 02:14:36 +00001481 R.setContextRange(SS->getRange());
1482
1483 return LookupQualifiedName(R, DC);
Douglas Gregor52537682009-03-19 00:18:19 +00001484 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001485
Douglas Gregore861bac2009-08-25 22:51:20 +00001486 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001487 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001488 // Name lookup can't find anything in this case.
John McCall9f3059a2009-10-09 21:13:30 +00001489 return false;
Douglas Gregored8f2882009-01-30 01:04:22 +00001490 }
1491
Mike Stump11289f42009-09-09 15:08:12 +00001492 // Perform unqualified name lookup starting in the given scope.
John McCall27b18f82009-11-17 02:14:36 +00001493 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregor34074322009-01-14 22:20:51 +00001494}
1495
Douglas Gregor889ceb72009-02-03 19:21:40 +00001496
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001497/// @brief Produce a diagnostic describing the ambiguity that resulted
1498/// from name lookup.
1499///
1500/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001501///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001502/// @param Name The name of the entity that name lookup was
1503/// searching for.
1504///
1505/// @param NameLoc The location of the name within the source code.
1506///
1507/// @param LookupRange A source range that provides more
1508/// source-location information concerning the lookup itself. For
1509/// example, this range might highlight a nested-name-specifier that
1510/// precedes the name.
1511///
1512/// @returns true
John McCall27b18f82009-11-17 02:14:36 +00001513bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001514 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1515
John McCall27b18f82009-11-17 02:14:36 +00001516 DeclarationName Name = Result.getLookupName();
1517 SourceLocation NameLoc = Result.getNameLoc();
1518 SourceRange LookupRange = Result.getContextRange();
1519
John McCall6538c932009-10-10 05:48:19 +00001520 switch (Result.getAmbiguityKind()) {
1521 case LookupResult::AmbiguousBaseSubobjects: {
1522 CXXBasePaths *Paths = Result.getBasePaths();
1523 QualType SubobjectType = Paths->front().back().Base->getType();
1524 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1525 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1526 << LookupRange;
1527
1528 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1529 while (isa<CXXMethodDecl>(*Found) &&
1530 cast<CXXMethodDecl>(*Found)->isStatic())
1531 ++Found;
1532
1533 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1534
1535 return true;
1536 }
Douglas Gregor1c846b02009-01-16 00:38:09 +00001537
John McCall6538c932009-10-10 05:48:19 +00001538 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001539 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1540 << Name << LookupRange;
John McCall6538c932009-10-10 05:48:19 +00001541
1542 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001543 std::set<Decl *> DeclsPrinted;
John McCall6538c932009-10-10 05:48:19 +00001544 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1545 PathEnd = Paths->end();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001546 Path != PathEnd; ++Path) {
1547 Decl *D = *Path->Decls.first;
1548 if (DeclsPrinted.insert(D).second)
1549 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1550 }
1551
Douglas Gregor1c846b02009-01-16 00:38:09 +00001552 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001553 }
1554
John McCall6538c932009-10-10 05:48:19 +00001555 case LookupResult::AmbiguousTagHiding: {
1556 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregorf23311d2009-01-17 01:13:24 +00001557
John McCall6538c932009-10-10 05:48:19 +00001558 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1559
1560 LookupResult::iterator DI, DE = Result.end();
1561 for (DI = Result.begin(); DI != DE; ++DI)
1562 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1563 TagDecls.insert(TD);
1564 Diag(TD->getLocation(), diag::note_hidden_tag);
1565 }
1566
1567 for (DI = Result.begin(); DI != DE; ++DI)
1568 if (!isa<TagDecl>(*DI))
1569 Diag((*DI)->getLocation(), diag::note_hiding_object);
1570
1571 // For recovery purposes, go ahead and implement the hiding.
John McCallad371252010-01-20 00:46:10 +00001572 LookupResult::Filter F = Result.makeFilter();
1573 while (F.hasNext()) {
1574 if (TagDecls.count(F.next()))
1575 F.erase();
1576 }
1577 F.done();
John McCall6538c932009-10-10 05:48:19 +00001578
1579 return true;
1580 }
1581
1582 case LookupResult::AmbiguousReference: {
1583 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCall9f3059a2009-10-09 21:13:30 +00001584
John McCall6538c932009-10-10 05:48:19 +00001585 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1586 for (; DI != DE; ++DI)
1587 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCall9f3059a2009-10-09 21:13:30 +00001588
John McCall6538c932009-10-10 05:48:19 +00001589 return true;
1590 }
1591 }
1592
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001593 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001594 return true;
1595}
Douglas Gregore254f902009-02-04 00:32:51 +00001596
John McCallf24d7bb2010-05-28 18:45:08 +00001597namespace {
1598 struct AssociatedLookup {
1599 AssociatedLookup(Sema &S,
1600 Sema::AssociatedNamespaceSet &Namespaces,
1601 Sema::AssociatedClassSet &Classes)
1602 : S(S), Namespaces(Namespaces), Classes(Classes) {
1603 }
1604
1605 Sema &S;
1606 Sema::AssociatedNamespaceSet &Namespaces;
1607 Sema::AssociatedClassSet &Classes;
1608 };
1609}
1610
Mike Stump11289f42009-09-09 15:08:12 +00001611static void
John McCallf24d7bb2010-05-28 18:45:08 +00001612addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCallc7e8e792009-08-07 22:18:02 +00001613
Douglas Gregor8b895222010-04-30 07:08:38 +00001614static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1615 DeclContext *Ctx) {
1616 // Add the associated namespace for this class.
1617
1618 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1619 // be a locally scoped record.
1620
1621 while (Ctx->isRecord() || Ctx->isTransparentContext())
1622 Ctx = Ctx->getParent();
1623
John McCallc7e8e792009-08-07 22:18:02 +00001624 if (Ctx->isFileContext())
Douglas Gregor8b895222010-04-30 07:08:38 +00001625 Namespaces.insert(Ctx->getPrimaryContext());
John McCallc7e8e792009-08-07 22:18:02 +00001626}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001627
Mike Stump11289f42009-09-09 15:08:12 +00001628// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001629// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001630static void
John McCallf24d7bb2010-05-28 18:45:08 +00001631addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1632 const TemplateArgument &Arg) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001633 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001634 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001635 switch (Arg.getKind()) {
1636 case TemplateArgument::Null:
1637 break;
Mike Stump11289f42009-09-09 15:08:12 +00001638
Douglas Gregor197e5f72009-07-08 07:51:57 +00001639 case TemplateArgument::Type:
1640 // [...] the namespaces and classes associated with the types of the
1641 // template arguments provided for template type parameters (excluding
1642 // template template parameters)
John McCallf24d7bb2010-05-28 18:45:08 +00001643 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor197e5f72009-07-08 07:51:57 +00001644 break;
Mike Stump11289f42009-09-09 15:08:12 +00001645
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001646 case TemplateArgument::Template: {
Mike Stump11289f42009-09-09 15:08:12 +00001647 // [...] the namespaces in which any template template arguments are
1648 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001649 // template template arguments are defined.
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001650 TemplateName Template = Arg.getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00001651 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001652 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001653 DeclContext *Ctx = ClassTemplate->getDeclContext();
1654 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001655 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001656 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001657 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001658 }
1659 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001660 }
1661
1662 case TemplateArgument::Declaration:
Douglas Gregor197e5f72009-07-08 07:51:57 +00001663 case TemplateArgument::Integral:
1664 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001665 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001666 // associated namespaces. ]
1667 break;
Mike Stump11289f42009-09-09 15:08:12 +00001668
Douglas Gregor197e5f72009-07-08 07:51:57 +00001669 case TemplateArgument::Pack:
1670 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1671 PEnd = Arg.pack_end();
1672 P != PEnd; ++P)
John McCallf24d7bb2010-05-28 18:45:08 +00001673 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001674 break;
1675 }
1676}
1677
Douglas Gregore254f902009-02-04 00:32:51 +00001678// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001679// argument-dependent lookup with an argument of class type
1680// (C++ [basic.lookup.koenig]p2).
1681static void
John McCallf24d7bb2010-05-28 18:45:08 +00001682addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1683 CXXRecordDecl *Class) {
1684
1685 // Just silently ignore anything whose name is __va_list_tag.
1686 if (Class->getDeclName() == Result.S.VAListTagName)
1687 return;
1688
Douglas Gregore254f902009-02-04 00:32:51 +00001689 // C++ [basic.lookup.koenig]p2:
1690 // [...]
1691 // -- If T is a class type (including unions), its associated
1692 // classes are: the class itself; the class of which it is a
1693 // member, if any; and its direct and indirect base
1694 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001695 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001696
1697 // Add the class of which it is a member, if any.
1698 DeclContext *Ctx = Class->getDeclContext();
1699 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001700 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001701 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001702 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001703
Douglas Gregore254f902009-02-04 00:32:51 +00001704 // Add the class itself. If we've already seen this class, we don't
1705 // need to visit base classes.
John McCallf24d7bb2010-05-28 18:45:08 +00001706 if (!Result.Classes.insert(Class))
Douglas Gregore254f902009-02-04 00:32:51 +00001707 return;
1708
Mike Stump11289f42009-09-09 15:08:12 +00001709 // -- If T is a template-id, its associated namespaces and classes are
1710 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001711 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001712 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001713 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001714 // namespaces in which any template template arguments are defined; and
1715 // the classes in which any member templates used as template template
1716 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001717 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001718 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001719 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1720 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1721 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001722 Result.Classes.insert(EnclosingClass);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001723 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001724 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001725
Douglas Gregor197e5f72009-07-08 07:51:57 +00001726 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1727 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallf24d7bb2010-05-28 18:45:08 +00001728 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001729 }
Mike Stump11289f42009-09-09 15:08:12 +00001730
John McCall67da35c2010-02-04 22:26:26 +00001731 // Only recurse into base classes for complete types.
1732 if (!Class->hasDefinition()) {
1733 // FIXME: we might need to instantiate templates here
1734 return;
1735 }
1736
Douglas Gregore254f902009-02-04 00:32:51 +00001737 // Add direct and indirect base classes along with their associated
1738 // namespaces.
1739 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1740 Bases.push_back(Class);
1741 while (!Bases.empty()) {
1742 // Pop this class off the stack.
1743 Class = Bases.back();
1744 Bases.pop_back();
1745
1746 // Visit the base classes.
1747 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1748 BaseEnd = Class->bases_end();
1749 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001750 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlc45c03c2009-10-25 09:35:33 +00001751 // In dependent contexts, we do ADL twice, and the first time around,
1752 // the base type might be a dependent TemplateSpecializationType, or a
1753 // TemplateTypeParmType. If that happens, simply ignore it.
1754 // FIXME: If we want to support export, we probably need to add the
1755 // namespace of the template in a TemplateSpecializationType, or even
1756 // the classes and namespaces of known non-dependent arguments.
1757 if (!BaseType)
1758 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001759 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001760 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregore254f902009-02-04 00:32:51 +00001761 // Find the associated namespace for this base class.
1762 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallf24d7bb2010-05-28 18:45:08 +00001763 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001764
1765 // Make sure we visit the bases of this base class.
1766 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1767 Bases.push_back(BaseDecl);
1768 }
1769 }
1770 }
1771}
1772
1773// \brief Add the associated classes and namespaces for
1774// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001775// (C++ [basic.lookup.koenig]p2).
1776static void
John McCallf24d7bb2010-05-28 18:45:08 +00001777addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregore254f902009-02-04 00:32:51 +00001778 // C++ [basic.lookup.koenig]p2:
1779 //
1780 // For each argument type T in the function call, there is a set
1781 // of zero or more associated namespaces and a set of zero or more
1782 // associated classes to be considered. The sets of namespaces and
1783 // classes is determined entirely by the types of the function
1784 // arguments (and the namespace of any template template
1785 // argument). Typedef names and using-declarations used to specify
1786 // the types do not contribute to this set. The sets of namespaces
1787 // and classes are determined in the following way:
Douglas Gregore254f902009-02-04 00:32:51 +00001788
John McCall0af3d3b2010-05-28 06:08:54 +00001789 llvm::SmallVector<const Type *, 16> Queue;
1790 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1791
Douglas Gregore254f902009-02-04 00:32:51 +00001792 while (true) {
John McCall0af3d3b2010-05-28 06:08:54 +00001793 switch (T->getTypeClass()) {
1794
1795#define TYPE(Class, Base)
1796#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1797#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1798#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1799#define ABSTRACT_TYPE(Class, Base)
1800#include "clang/AST/TypeNodes.def"
1801 // T is canonical. We can also ignore dependent types because
1802 // we don't need to do ADL at the definition point, but if we
1803 // wanted to implement template export (or if we find some other
1804 // use for associated classes and namespaces...) this would be
1805 // wrong.
Douglas Gregore254f902009-02-04 00:32:51 +00001806 break;
Douglas Gregore254f902009-02-04 00:32:51 +00001807
John McCall0af3d3b2010-05-28 06:08:54 +00001808 // -- If T is a pointer to U or an array of U, its associated
1809 // namespaces and classes are those associated with U.
1810 case Type::Pointer:
1811 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1812 continue;
1813 case Type::ConstantArray:
1814 case Type::IncompleteArray:
1815 case Type::VariableArray:
1816 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1817 continue;
Douglas Gregore254f902009-02-04 00:32:51 +00001818
John McCall0af3d3b2010-05-28 06:08:54 +00001819 // -- If T is a fundamental type, its associated sets of
1820 // namespaces and classes are both empty.
1821 case Type::Builtin:
1822 break;
1823
1824 // -- If T is a class type (including unions), its associated
1825 // classes are: the class itself; the class of which it is a
1826 // member, if any; and its direct and indirect base
1827 // classes. Its associated namespaces are the namespaces in
1828 // which its associated classes are defined.
1829 case Type::Record: {
1830 CXXRecordDecl *Class
1831 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallf24d7bb2010-05-28 18:45:08 +00001832 addAssociatedClassesAndNamespaces(Result, Class);
John McCall0af3d3b2010-05-28 06:08:54 +00001833 break;
Douglas Gregor89ee6822009-02-28 01:32:25 +00001834 }
Douglas Gregorfe60c142010-05-20 02:26:51 +00001835
John McCall0af3d3b2010-05-28 06:08:54 +00001836 // -- If T is an enumeration type, its associated namespace is
1837 // the namespace in which it is defined. If it is class
1838 // member, its associated class is the member’s class; else
1839 // it has no associated class.
1840 case Type::Enum: {
1841 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001842
John McCall0af3d3b2010-05-28 06:08:54 +00001843 DeclContext *Ctx = Enum->getDeclContext();
1844 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallf24d7bb2010-05-28 18:45:08 +00001845 Result.Classes.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001846
John McCall0af3d3b2010-05-28 06:08:54 +00001847 // Add the associated namespace for this class.
John McCallf24d7bb2010-05-28 18:45:08 +00001848 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001849
John McCall0af3d3b2010-05-28 06:08:54 +00001850 break;
1851 }
1852
1853 // -- If T is a function type, its associated namespaces and
1854 // classes are those associated with the function parameter
1855 // types and those associated with the return type.
1856 case Type::FunctionProto: {
1857 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1858 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1859 ArgEnd = Proto->arg_type_end();
1860 Arg != ArgEnd; ++Arg)
1861 Queue.push_back(Arg->getTypePtr());
1862 // fallthrough
1863 }
1864 case Type::FunctionNoProto: {
1865 const FunctionType *FnType = cast<FunctionType>(T);
1866 T = FnType->getResultType().getTypePtr();
1867 continue;
1868 }
1869
1870 // -- If T is a pointer to a member function of a class X, its
1871 // associated namespaces and classes are those associated
1872 // with the function parameter types and return type,
1873 // together with those associated with X.
1874 //
1875 // -- If T is a pointer to a data member of class X, its
1876 // associated namespaces and classes are those associated
1877 // with the member type together with those associated with
1878 // X.
1879 case Type::MemberPointer: {
1880 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1881
1882 // Queue up the class type into which this points.
1883 Queue.push_back(MemberPtr->getClass());
1884
1885 // And directly continue with the pointee type.
1886 T = MemberPtr->getPointeeType().getTypePtr();
1887 continue;
1888 }
1889
1890 // As an extension, treat this like a normal pointer.
1891 case Type::BlockPointer:
1892 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1893 continue;
1894
1895 // References aren't covered by the standard, but that's such an
1896 // obvious defect that we cover them anyway.
1897 case Type::LValueReference:
1898 case Type::RValueReference:
1899 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1900 continue;
1901
1902 // These are fundamental types.
1903 case Type::Vector:
1904 case Type::ExtVector:
1905 case Type::Complex:
1906 break;
1907
1908 // These are ignored by ADL.
1909 case Type::ObjCObject:
1910 case Type::ObjCInterface:
1911 case Type::ObjCObjectPointer:
1912 break;
1913 }
1914
1915 if (Queue.empty()) break;
1916 T = Queue.back();
1917 Queue.pop_back();
Douglas Gregore254f902009-02-04 00:32:51 +00001918 }
Douglas Gregore254f902009-02-04 00:32:51 +00001919}
1920
1921/// \brief Find the associated classes and namespaces for
1922/// argument-dependent lookup for a call with the given set of
1923/// arguments.
1924///
1925/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001926/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001927/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001928void
Douglas Gregore254f902009-02-04 00:32:51 +00001929Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1930 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001931 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001932 AssociatedNamespaces.clear();
1933 AssociatedClasses.clear();
1934
John McCallf24d7bb2010-05-28 18:45:08 +00001935 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1936
Douglas Gregore254f902009-02-04 00:32:51 +00001937 // C++ [basic.lookup.koenig]p2:
1938 // For each argument type T in the function call, there is a set
1939 // of zero or more associated namespaces and a set of zero or more
1940 // associated classes to be considered. The sets of namespaces and
1941 // classes is determined entirely by the types of the function
1942 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001943 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001944 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1945 Expr *Arg = Args[ArgIdx];
1946
1947 if (Arg->getType() != Context.OverloadTy) {
John McCallf24d7bb2010-05-28 18:45:08 +00001948 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001949 continue;
1950 }
1951
1952 // [...] In addition, if the argument is the name or address of a
1953 // set of overloaded functions and/or function templates, its
1954 // associated classes and namespaces are the union of those
1955 // associated with each of the members of the set: the namespace
1956 // in which the function or function template is defined and the
1957 // classes and namespaces associated with its (non-dependent)
1958 // parameter types and return type.
Douglas Gregorbe759252009-07-08 10:57:20 +00001959 Arg = Arg->IgnoreParens();
John McCalld14a8642009-11-21 08:51:07 +00001960 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCalle3027922010-08-25 11:45:40 +00001961 if (unaryOp->getOpcode() == UO_AddrOf)
John McCalld14a8642009-11-21 08:51:07 +00001962 Arg = unaryOp->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001963
John McCallf24d7bb2010-05-28 18:45:08 +00001964 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1965 if (!ULE) continue;
John McCalld14a8642009-11-21 08:51:07 +00001966
John McCallf24d7bb2010-05-28 18:45:08 +00001967 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1968 I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001969 // Look through any using declarations to find the underlying function.
1970 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001971
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00001972 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1973 if (!FDecl)
1974 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001975
1976 // Add the classes and namespaces associated with the parameter
1977 // types and return type of this function.
John McCallf24d7bb2010-05-28 18:45:08 +00001978 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregore254f902009-02-04 00:32:51 +00001979 }
1980 }
1981}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001982
1983/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1984/// an acceptable non-member overloaded operator for a call whose
1985/// arguments have types T1 (and, if non-empty, T2). This routine
1986/// implements the check in C++ [over.match.oper]p3b2 concerning
1987/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001988static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001989IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1990 QualType T1, QualType T2,
1991 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001992 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1993 return true;
1994
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001995 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1996 return true;
1997
John McCall9dd450b2009-09-21 23:43:11 +00001998 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001999 if (Proto->getNumArgs() < 1)
2000 return false;
2001
2002 if (T1->isEnumeralType()) {
2003 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002004 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002005 return true;
2006 }
2007
2008 if (Proto->getNumArgs() < 2)
2009 return false;
2010
2011 if (!T2.isNull() && T2->isEnumeralType()) {
2012 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002013 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002014 return true;
2015 }
2016
2017 return false;
2018}
2019
John McCall5cebab12009-11-18 07:57:50 +00002020NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002021 SourceLocation Loc,
John McCall5cebab12009-11-18 07:57:50 +00002022 LookupNameKind NameKind,
2023 RedeclarationKind Redecl) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002024 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall5cebab12009-11-18 07:57:50 +00002025 LookupName(R, S);
John McCall67c00872009-12-02 08:25:40 +00002026 return R.getAsSingle<NamedDecl>();
John McCall5cebab12009-11-18 07:57:50 +00002027}
2028
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002029/// \brief Find the protocol with the given name, if any.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002030ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2031 SourceLocation IdLoc) {
2032 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2033 LookupObjCProtocolName);
Douglas Gregorde9f17e2009-04-23 23:18:26 +00002034 return cast_or_null<ObjCProtocolDecl>(D);
2035}
2036
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002037void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00002038 QualType T1, QualType T2,
John McCall4c4c1df2010-01-26 03:27:55 +00002039 UnresolvedSetImpl &Functions) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002040 // C++ [over.match.oper]p3:
2041 // -- The set of non-member candidates is the result of the
2042 // unqualified lookup of operator@ in the context of the
2043 // expression according to the usual rules for name lookup in
2044 // unqualified function calls (3.4.2) except that all member
2045 // functions are ignored. However, if no operand has a class
2046 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00002047 // that have a first parameter of type T1 or "reference to
2048 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002049 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00002050 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002051 // when T2 is an enumeration type, are candidate functions.
2052 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCall27b18f82009-11-17 02:14:36 +00002053 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2054 LookupName(Operators, S);
Mike Stump11289f42009-09-09 15:08:12 +00002055
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002056 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2057
John McCall9f3059a2009-10-09 21:13:30 +00002058 if (Operators.empty())
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002059 return;
2060
2061 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2062 Op != OpEnd; ++Op) {
Douglas Gregor645d76f2010-04-25 20:25:43 +00002063 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2064 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002065 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor645d76f2010-04-25 20:25:43 +00002066 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00002067 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor645d76f2010-04-25 20:25:43 +00002068 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor15448f82009-06-27 21:05:07 +00002069 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00002070 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00002071 // later?
2072 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor645d76f2010-04-25 20:25:43 +00002073 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor15448f82009-06-27 21:05:07 +00002074 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002075 }
2076}
2077
Douglas Gregor52b72822010-07-02 23:12:18 +00002078/// \brief Look up the constructors for the given class.
2079DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregora6d69502010-07-02 23:41:54 +00002080 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor9672f922010-07-03 00:47:00 +00002081 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2082 if (!Class->hasDeclaredDefaultConstructor())
2083 DeclareImplicitDefaultConstructor(Class);
2084 if (!Class->hasDeclaredCopyConstructor())
2085 DeclareImplicitCopyConstructor(Class);
2086 }
Douglas Gregora6d69502010-07-02 23:41:54 +00002087
Douglas Gregor52b72822010-07-02 23:12:18 +00002088 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2089 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2090 return Class->lookup(Name);
2091}
2092
Douglas Gregore71edda2010-07-01 22:47:18 +00002093/// \brief Look for the destructor of the given class.
2094///
2095/// During semantic analysis, this routine should be used in lieu of
2096/// CXXRecordDecl::getDestructor().
2097///
2098/// \returns The destructor for this class.
2099CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor7454c562010-07-02 20:37:36 +00002100 // If the destructor has not yet been declared, do so now.
2101 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2102 !Class->hasDeclaredDestructor())
2103 DeclareImplicitDestructor(Class);
2104
Douglas Gregore71edda2010-07-01 22:47:18 +00002105 return Class->getDestructor();
2106}
2107
John McCall8fe68082010-01-26 07:16:45 +00002108void ADLResult::insert(NamedDecl *New) {
2109 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2110
2111 // If we haven't yet seen a decl for this key, or the last decl
2112 // was exactly this one, we're done.
2113 if (Old == 0 || Old == New) {
2114 Old = New;
2115 return;
2116 }
2117
2118 // Otherwise, decide which is a more recent redeclaration.
2119 FunctionDecl *OldFD, *NewFD;
2120 if (isa<FunctionTemplateDecl>(New)) {
2121 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2122 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2123 } else {
2124 OldFD = cast<FunctionDecl>(Old);
2125 NewFD = cast<FunctionDecl>(New);
2126 }
2127
2128 FunctionDecl *Cursor = NewFD;
2129 while (true) {
2130 Cursor = Cursor->getPreviousDeclaration();
2131
2132 // If we got to the end without finding OldFD, OldFD is the newer
2133 // declaration; leave things as they are.
2134 if (!Cursor) return;
2135
2136 // If we do find OldFD, then NewFD is newer.
2137 if (Cursor == OldFD) break;
2138
2139 // Otherwise, keep looking.
2140 }
2141
2142 Old = New;
2143}
2144
Sebastian Redlc057f422009-10-23 19:23:15 +00002145void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002146 Expr **Args, unsigned NumArgs,
John McCall8fe68082010-01-26 07:16:45 +00002147 ADLResult &Result) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002148 // Find all of the associated namespaces and classes based on the
2149 // arguments we have.
2150 AssociatedNamespaceSet AssociatedNamespaces;
2151 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00002152 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00002153 AssociatedNamespaces,
2154 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002155
Sebastian Redlc057f422009-10-23 19:23:15 +00002156 QualType T1, T2;
2157 if (Operator) {
2158 T1 = Args[0]->getType();
2159 if (NumArgs >= 2)
2160 T2 = Args[1]->getType();
2161 }
2162
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002163 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002164 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2165 // and let Y be the lookup set produced by argument dependent
2166 // lookup (defined as follows). If X contains [...] then Y is
2167 // empty. Otherwise Y is the set of declarations found in the
2168 // namespaces associated with the argument types as described
2169 // below. The set of declarations found by the lookup of the name
2170 // is the union of X and Y.
2171 //
2172 // Here, we compute Y and add its members to the overloaded
2173 // candidate set.
2174 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00002175 NSEnd = AssociatedNamespaces.end();
2176 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002177 // When considering an associated namespace, the lookup is the
2178 // same as the lookup performed when the associated namespace is
2179 // used as a qualifier (3.4.3.2) except that:
2180 //
2181 // -- Any using-directives in the associated namespace are
2182 // ignored.
2183 //
John McCallc7e8e792009-08-07 22:18:02 +00002184 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002185 // associated classes are visible within their respective
2186 // namespaces even if they are not visible during an ordinary
2187 // lookup (11.4).
2188 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00002189 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall4c4c1df2010-01-26 03:27:55 +00002190 NamedDecl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00002191 // If the only declaration here is an ordinary friend, consider
2192 // it only if it was declared in an associated classes.
2193 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00002194 DeclContext *LexDC = D->getLexicalDeclContext();
2195 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2196 continue;
2197 }
Mike Stump11289f42009-09-09 15:08:12 +00002198
John McCall91f61fc2010-01-26 06:04:06 +00002199 if (isa<UsingShadowDecl>(D))
2200 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall4c4c1df2010-01-26 03:27:55 +00002201
John McCall91f61fc2010-01-26 06:04:06 +00002202 if (isa<FunctionDecl>(D)) {
2203 if (Operator &&
2204 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2205 T1, T2, Context))
2206 continue;
John McCall8fe68082010-01-26 07:16:45 +00002207 } else if (!isa<FunctionTemplateDecl>(D))
2208 continue;
2209
2210 Result.insert(D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00002211 }
2212 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00002213}
Douglas Gregor2d435302009-12-30 17:04:44 +00002214
2215//----------------------------------------------------------------------------
2216// Search for all visible declarations.
2217//----------------------------------------------------------------------------
2218VisibleDeclConsumer::~VisibleDeclConsumer() { }
2219
2220namespace {
2221
2222class ShadowContextRAII;
2223
2224class VisibleDeclsRecord {
2225public:
2226 /// \brief An entry in the shadow map, which is optimized to store a
2227 /// single declaration (the common case) but can also store a list
2228 /// of declarations.
2229 class ShadowMapEntry {
2230 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2231
2232 /// \brief Contains either the solitary NamedDecl * or a vector
2233 /// of declarations.
2234 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2235
2236 public:
2237 ShadowMapEntry() : DeclOrVector() { }
2238
2239 void Add(NamedDecl *ND);
2240 void Destroy();
2241
2242 // Iteration.
2243 typedef NamedDecl **iterator;
2244 iterator begin();
2245 iterator end();
2246 };
2247
2248private:
2249 /// \brief A mapping from declaration names to the declarations that have
2250 /// this name within a particular scope.
2251 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2252
2253 /// \brief A list of shadow maps, which is used to model name hiding.
2254 std::list<ShadowMap> ShadowMaps;
2255
2256 /// \brief The declaration contexts we have already visited.
2257 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2258
2259 friend class ShadowContextRAII;
2260
2261public:
2262 /// \brief Determine whether we have already visited this context
2263 /// (and, if not, note that we are going to visit that context now).
2264 bool visitedContext(DeclContext *Ctx) {
2265 return !VisitedContexts.insert(Ctx);
2266 }
2267
Douglas Gregor39982192010-08-15 06:18:01 +00002268 bool alreadyVisitedContext(DeclContext *Ctx) {
2269 return VisitedContexts.count(Ctx);
2270 }
2271
Douglas Gregor2d435302009-12-30 17:04:44 +00002272 /// \brief Determine whether the given declaration is hidden in the
2273 /// current scope.
2274 ///
2275 /// \returns the declaration that hides the given declaration, or
2276 /// NULL if no such declaration exists.
2277 NamedDecl *checkHidden(NamedDecl *ND);
2278
2279 /// \brief Add a declaration to the current shadow map.
2280 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2281};
2282
2283/// \brief RAII object that records when we've entered a shadow context.
2284class ShadowContextRAII {
2285 VisibleDeclsRecord &Visible;
2286
2287 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2288
2289public:
2290 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2291 Visible.ShadowMaps.push_back(ShadowMap());
2292 }
2293
2294 ~ShadowContextRAII() {
2295 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2296 EEnd = Visible.ShadowMaps.back().end();
2297 E != EEnd;
2298 ++E)
2299 E->second.Destroy();
2300
2301 Visible.ShadowMaps.pop_back();
2302 }
2303};
2304
2305} // end anonymous namespace
2306
2307void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2308 if (DeclOrVector.isNull()) {
2309 // 0 - > 1 elements: just set the single element information.
2310 DeclOrVector = ND;
2311 return;
2312 }
2313
2314 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2315 // 1 -> 2 elements: create the vector of results and push in the
2316 // existing declaration.
2317 DeclVector *Vec = new DeclVector;
2318 Vec->push_back(PrevND);
2319 DeclOrVector = Vec;
2320 }
2321
2322 // Add the new element to the end of the vector.
2323 DeclOrVector.get<DeclVector*>()->push_back(ND);
2324}
2325
2326void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2327 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2328 delete Vec;
2329 DeclOrVector = ((NamedDecl *)0);
2330 }
2331}
2332
2333VisibleDeclsRecord::ShadowMapEntry::iterator
2334VisibleDeclsRecord::ShadowMapEntry::begin() {
2335 if (DeclOrVector.isNull())
2336 return 0;
2337
2338 if (DeclOrVector.dyn_cast<NamedDecl *>())
2339 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2340
2341 return DeclOrVector.get<DeclVector *>()->begin();
2342}
2343
2344VisibleDeclsRecord::ShadowMapEntry::iterator
2345VisibleDeclsRecord::ShadowMapEntry::end() {
2346 if (DeclOrVector.isNull())
2347 return 0;
2348
2349 if (DeclOrVector.dyn_cast<NamedDecl *>())
2350 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2351
2352 return DeclOrVector.get<DeclVector *>()->end();
2353}
2354
2355NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregor0235c422010-01-14 00:06:47 +00002356 // Look through using declarations.
2357 ND = ND->getUnderlyingDecl();
2358
Douglas Gregor2d435302009-12-30 17:04:44 +00002359 unsigned IDNS = ND->getIdentifierNamespace();
2360 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2361 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2362 SM != SMEnd; ++SM) {
2363 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2364 if (Pos == SM->end())
2365 continue;
2366
2367 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2368 IEnd = Pos->second.end();
2369 I != IEnd; ++I) {
2370 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +00002371 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor2d435302009-12-30 17:04:44 +00002372 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2373 Decl::IDNS_ObjCProtocol)))
2374 continue;
2375
2376 // Protocols are in distinct namespaces from everything else.
2377 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2378 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2379 (*I)->getIdentifierNamespace() != IDNS)
2380 continue;
2381
Douglas Gregor09bbc652010-01-14 15:47:35 +00002382 // Functions and function templates in the same scope overload
2383 // rather than hide. FIXME: Look for hiding based on function
2384 // signatures!
Douglas Gregor200c99d2010-01-14 03:35:48 +00002385 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor09bbc652010-01-14 15:47:35 +00002386 ND->isFunctionOrFunctionTemplate() &&
2387 SM == ShadowMaps.rbegin())
Douglas Gregor200c99d2010-01-14 03:35:48 +00002388 continue;
2389
Douglas Gregor2d435302009-12-30 17:04:44 +00002390 // We've found a declaration that hides this one.
2391 return *I;
2392 }
2393 }
2394
2395 return 0;
2396}
2397
2398static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2399 bool QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002400 bool InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002401 VisibleDeclConsumer &Consumer,
2402 VisibleDeclsRecord &Visited) {
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002403 if (!Ctx)
2404 return;
2405
Douglas Gregor2d435302009-12-30 17:04:44 +00002406 // Make sure we don't visit the same context twice.
2407 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2408 return;
2409
Douglas Gregor7454c562010-07-02 20:37:36 +00002410 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2411 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2412
Douglas Gregor2d435302009-12-30 17:04:44 +00002413 // Enumerate all of the results in this context.
2414 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2415 CurCtx = CurCtx->getNextContext()) {
2416 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2417 DEnd = CurCtx->decls_end();
2418 D != DEnd; ++D) {
2419 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2420 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002421 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor2d435302009-12-30 17:04:44 +00002422 Visited.add(ND);
2423 }
2424
2425 // Visit transparent contexts inside this context.
2426 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2427 if (InnerCtx->isTransparentContext())
Douglas Gregor09bbc652010-01-14 15:47:35 +00002428 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor2d435302009-12-30 17:04:44 +00002429 Consumer, Visited);
2430 }
2431 }
2432 }
2433
2434 // Traverse using directives for qualified name lookup.
2435 if (QualifiedNameLookup) {
2436 ShadowContextRAII Shadow(Visited);
2437 DeclContext::udir_iterator I, E;
2438 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2439 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002440 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002441 }
2442 }
2443
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002444 // Traverse the contexts of inherited C++ classes.
Douglas Gregor2d435302009-12-30 17:04:44 +00002445 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall67da35c2010-02-04 22:26:26 +00002446 if (!Record->hasDefinition())
2447 return;
2448
Douglas Gregor2d435302009-12-30 17:04:44 +00002449 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2450 BEnd = Record->bases_end();
2451 B != BEnd; ++B) {
2452 QualType BaseType = B->getType();
2453
2454 // Don't look into dependent bases, because name lookup can't look
2455 // there anyway.
2456 if (BaseType->isDependentType())
2457 continue;
2458
2459 const RecordType *Record = BaseType->getAs<RecordType>();
2460 if (!Record)
2461 continue;
2462
2463 // FIXME: It would be nice to be able to determine whether referencing
2464 // a particular member would be ambiguous. For example, given
2465 //
2466 // struct A { int member; };
2467 // struct B { int member; };
2468 // struct C : A, B { };
2469 //
2470 // void f(C *c) { c->### }
2471 //
2472 // accessing 'member' would result in an ambiguity. However, we
2473 // could be smart enough to qualify the member with the base
2474 // class, e.g.,
2475 //
2476 // c->B::member
2477 //
2478 // or
2479 //
2480 // c->A::member
2481
2482 // Find results in this base class (and its bases).
2483 ShadowContextRAII Shadow(Visited);
2484 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002485 true, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002486 }
2487 }
2488
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002489 // Traverse the contexts of Objective-C classes.
2490 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2491 // Traverse categories.
2492 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2493 Category; Category = Category->getNextClassCategory()) {
2494 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002495 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2496 Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002497 }
2498
2499 // Traverse protocols.
2500 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2501 E = IFace->protocol_end(); I != E; ++I) {
2502 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002503 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2504 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002505 }
2506
2507 // Traverse the superclass.
2508 if (IFace->getSuperClass()) {
2509 ShadowContextRAII Shadow(Visited);
2510 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002511 true, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002512 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002513
2514 // If there is an implementation, traverse it. We do this to find
2515 // synthesized ivars.
2516 if (IFace->getImplementation()) {
2517 ShadowContextRAII Shadow(Visited);
2518 LookupVisibleDecls(IFace->getImplementation(), Result,
2519 QualifiedNameLookup, true, Consumer, Visited);
2520 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002521 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2522 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2523 E = Protocol->protocol_end(); I != E; ++I) {
2524 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002525 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2526 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002527 }
2528 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2529 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2530 E = Category->protocol_end(); I != E; ++I) {
2531 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002532 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2533 Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002534 }
Douglas Gregor0b59e802010-04-19 18:02:19 +00002535
2536 // If there is an implementation, traverse it.
2537 if (Category->getImplementation()) {
2538 ShadowContextRAII Shadow(Visited);
2539 LookupVisibleDecls(Category->getImplementation(), Result,
2540 QualifiedNameLookup, true, Consumer, Visited);
2541 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002542 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002543}
2544
2545static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2546 UnqualUsingDirectiveSet &UDirs,
2547 VisibleDeclConsumer &Consumer,
2548 VisibleDeclsRecord &Visited) {
2549 if (!S)
2550 return;
2551
Douglas Gregor39982192010-08-15 06:18:01 +00002552 if (!S->getEntity() ||
2553 (!S->getParent() &&
2554 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002555 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2556 // Walk through the declarations in this Scope.
2557 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2558 D != DEnd; ++D) {
John McCall48871652010-08-21 09:40:31 +00002559 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002560 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor09bbc652010-01-14 15:47:35 +00002561 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002562 Visited.add(ND);
2563 }
2564 }
2565 }
2566
Douglas Gregor66230062010-03-15 14:33:29 +00002567 // FIXME: C++ [temp.local]p8
Douglas Gregor2d435302009-12-30 17:04:44 +00002568 DeclContext *Entity = 0;
Douglas Gregor4f248632010-01-01 17:44:25 +00002569 if (S->getEntity()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002570 // Look into this scope's declaration context, along with any of its
2571 // parent lookup contexts (e.g., enclosing classes), up to the point
2572 // where we hit the context stored in the next outer scope.
2573 Entity = (DeclContext *)S->getEntity();
Douglas Gregor66230062010-03-15 14:33:29 +00002574 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor2d435302009-12-30 17:04:44 +00002575
Douglas Gregorea166062010-03-15 15:26:48 +00002576 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor2d435302009-12-30 17:04:44 +00002577 Ctx = Ctx->getLookupParent()) {
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002578 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2579 if (Method->isInstanceMethod()) {
2580 // For instance methods, look for ivars in the method's interface.
2581 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2582 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor0c8a1722010-02-04 23:42:48 +00002583 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2584 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2585 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002586 }
2587
2588 // We've already performed all of the name lookup that we need
2589 // to for Objective-C methods; the next context will be the
2590 // outer scope.
2591 break;
2592 }
2593
Douglas Gregor2d435302009-12-30 17:04:44 +00002594 if (Ctx->isFunctionOrMethod())
2595 continue;
2596
2597 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002598 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002599 }
2600 } else if (!S->getParent()) {
2601 // Look into the translation unit scope. We walk through the translation
2602 // unit's declaration context, because the Scope itself won't have all of
2603 // the declarations if we loaded a precompiled header.
2604 // FIXME: We would like the translation unit's Scope object to point to the
2605 // translation unit, so we don't need this special "if" branch. However,
2606 // doing so would force the normal C++ name-lookup code to look into the
2607 // translation unit decl when the IdentifierInfo chains would suffice.
2608 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002609 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor2d435302009-12-30 17:04:44 +00002610 Entity = Result.getSema().Context.getTranslationUnitDecl();
2611 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor09bbc652010-01-14 15:47:35 +00002612 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor712dcfe2010-01-07 00:31:29 +00002613 }
Douglas Gregor2d435302009-12-30 17:04:44 +00002614
2615 if (Entity) {
2616 // Lookup visible declarations in any namespaces found by using
2617 // directives.
2618 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2619 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2620 for (; UI != UEnd; ++UI)
2621 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor09bbc652010-01-14 15:47:35 +00002622 Result, /*QualifiedNameLookup=*/false,
2623 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002624 }
2625
2626 // Lookup names in the parent scope.
2627 ShadowContextRAII Shadow(Visited);
2628 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2629}
2630
2631void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002632 VisibleDeclConsumer &Consumer,
2633 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002634 // Determine the set of using directives available during
2635 // unqualified name lookup.
2636 Scope *Initial = S;
2637 UnqualUsingDirectiveSet UDirs;
2638 if (getLangOptions().CPlusPlus) {
2639 // Find the first namespace or translation-unit scope.
2640 while (S && !isNamespaceOrTranslationUnitScope(S))
2641 S = S->getParent();
2642
2643 UDirs.visitScopeChain(Initial, S);
2644 }
2645 UDirs.done();
2646
2647 // Look for visible declarations.
2648 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2649 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002650 if (!IncludeGlobalScope)
2651 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002652 ShadowContextRAII Shadow(Visited);
2653 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2654}
2655
2656void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor39982192010-08-15 06:18:01 +00002657 VisibleDeclConsumer &Consumer,
2658 bool IncludeGlobalScope) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002659 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2660 VisibleDeclsRecord Visited;
Douglas Gregor39982192010-08-15 06:18:01 +00002661 if (!IncludeGlobalScope)
2662 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor2d435302009-12-30 17:04:44 +00002663 ShadowContextRAII Shadow(Visited);
Douglas Gregor09bbc652010-01-14 15:47:35 +00002664 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2665 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor2d435302009-12-30 17:04:44 +00002666}
2667
2668//----------------------------------------------------------------------------
2669// Typo correction
2670//----------------------------------------------------------------------------
2671
2672namespace {
2673class TypoCorrectionConsumer : public VisibleDeclConsumer {
2674 /// \brief The name written that is a typo in the source.
2675 llvm::StringRef Typo;
2676
2677 /// \brief The results found that have the smallest edit distance
2678 /// found (so far) with the typo name.
2679 llvm::SmallVector<NamedDecl *, 4> BestResults;
2680
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002681 /// \brief The keywords that have the smallest edit distance.
2682 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2683
Douglas Gregor2d435302009-12-30 17:04:44 +00002684 /// \brief The best edit distance found so far.
2685 unsigned BestEditDistance;
2686
2687public:
2688 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2689 : Typo(Typo->getName()) { }
2690
Douglas Gregor09bbc652010-01-14 15:47:35 +00002691 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002692 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor2d435302009-12-30 17:04:44 +00002693
2694 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2695 iterator begin() const { return BestResults.begin(); }
2696 iterator end() const { return BestResults.end(); }
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002697 void clear_decls() { BestResults.clear(); }
2698
2699 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor2d435302009-12-30 17:04:44 +00002700
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002701 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2702 keyword_iterator;
2703 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2704 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2705 bool keyword_empty() const { return BestKeywords.empty(); }
2706 unsigned keyword_size() const { return BestKeywords.size(); }
2707
2708 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor2d435302009-12-30 17:04:44 +00002709};
2710
2711}
2712
Douglas Gregor09bbc652010-01-14 15:47:35 +00002713void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2714 bool InBaseClass) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002715 // Don't consider hidden names for typo correction.
2716 if (Hiding)
2717 return;
2718
2719 // Only consider entities with identifiers for names, ignoring
2720 // special names (constructors, overloaded operators, selectors,
2721 // etc.).
2722 IdentifierInfo *Name = ND->getIdentifier();
2723 if (!Name)
2724 return;
2725
2726 // Compute the edit distance between the typo and the name of this
2727 // entity. If this edit distance is not worse than the best edit
2728 // distance we've seen so far, add it to the list of results.
2729 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002730 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002731 if (ED < BestEditDistance) {
2732 // This result is better than any we've seen before; clear out
2733 // the previous results.
2734 BestResults.clear();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002735 BestKeywords.clear();
Douglas Gregor2d435302009-12-30 17:04:44 +00002736 BestEditDistance = ED;
2737 } else if (ED > BestEditDistance) {
2738 // This result is worse than the best results we've seen so far;
2739 // ignore it.
2740 return;
2741 }
2742 } else
2743 BestEditDistance = ED;
2744
2745 BestResults.push_back(ND);
2746}
2747
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002748void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2749 llvm::StringRef Keyword) {
2750 // Compute the edit distance between the typo and this keyword.
2751 // If this edit distance is not worse than the best edit
2752 // distance we've seen so far, add it to the list of results.
2753 unsigned ED = Typo.edit_distance(Keyword);
2754 if (!BestResults.empty() || !BestKeywords.empty()) {
2755 if (ED < BestEditDistance) {
2756 BestResults.clear();
2757 BestKeywords.clear();
2758 BestEditDistance = ED;
2759 } else if (ED > BestEditDistance) {
2760 // This result is worse than the best results we've seen so far;
2761 // ignore it.
2762 return;
2763 }
2764 } else
2765 BestEditDistance = ED;
2766
2767 BestKeywords.push_back(&Context.Idents.get(Keyword));
2768}
2769
Douglas Gregor2d435302009-12-30 17:04:44 +00002770/// \brief Try to "correct" a typo in the source code by finding
2771/// visible declarations whose names are similar to the name that was
2772/// present in the source code.
2773///
2774/// \param Res the \c LookupResult structure that contains the name
2775/// that was present in the source code along with the name-lookup
2776/// criteria used to search for the name. On success, this structure
2777/// will contain the results of name lookup.
2778///
2779/// \param S the scope in which name lookup occurs.
2780///
2781/// \param SS the nested-name-specifier that precedes the name we're
2782/// looking for, if present.
2783///
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002784/// \param MemberContext if non-NULL, the context in which to look for
2785/// a member access expression.
2786///
Douglas Gregor598b08f2009-12-31 05:20:13 +00002787/// \param EnteringContext whether we're entering the context described by
2788/// the nested-name-specifier SS.
2789///
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002790/// \param CTC The context in which typo correction occurs, which impacts the
2791/// set of keywords permitted.
2792///
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002793/// \param OPT when non-NULL, the search for visible declarations will
2794/// also walk the protocols in the qualified interfaces of \p OPT.
2795///
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002796/// \returns the corrected name if the typo was corrected, otherwise returns an
2797/// empty \c DeclarationName. When a typo was corrected, the result structure
2798/// may contain the results of name lookup for the correct name or it may be
2799/// empty.
2800DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002801 DeclContext *MemberContext,
2802 bool EnteringContext,
2803 CorrectTypoContext CTC,
2804 const ObjCObjectPointerType *OPT) {
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00002805 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002806 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002807
2808 // Provide a stop gap for files that are just seriously broken. Trying
2809 // to correct all typos can turn into a HUGE performance penalty, causing
2810 // some files to take minutes to get rejected by the parser.
2811 // FIXME: Is this the right solution?
2812 if (TyposCorrected == 20)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002813 return DeclarationName();
Ted Kremenek54516822010-02-02 02:07:01 +00002814 ++TyposCorrected;
Ted Kremeneke51136e2010-01-06 00:23:04 +00002815
Douglas Gregor2d435302009-12-30 17:04:44 +00002816 // We only attempt to correct typos for identifiers.
2817 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2818 if (!Typo)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002819 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002820
2821 // If the scope specifier itself was invalid, don't try to correct
2822 // typos.
2823 if (SS && SS->isInvalid())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002824 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002825
2826 // Never try to correct typos during template deduction or
2827 // instantiation.
2828 if (!ActiveTemplateInstantiations.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002829 return DeclarationName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002830
Douglas Gregor2d435302009-12-30 17:04:44 +00002831 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002832
2833 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002834 if (MemberContext) {
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002835 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002836
2837 // Look in qualified interfaces.
2838 if (OPT) {
2839 for (ObjCObjectPointerType::qual_iterator
2840 I = OPT->qual_begin(), E = OPT->qual_end();
2841 I != E; ++I)
2842 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2843 }
2844 } else if (SS && SS->isSet()) {
Douglas Gregor2d435302009-12-30 17:04:44 +00002845 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2846 if (!DC)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00002847 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00002848
2849 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2850 } else {
2851 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2852 }
2853
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002854 // Add context-dependent keywords.
2855 bool WantTypeSpecifiers = false;
2856 bool WantExpressionKeywords = false;
2857 bool WantCXXNamedCasts = false;
2858 bool WantRemainingKeywords = false;
2859 switch (CTC) {
2860 case CTC_Unknown:
2861 WantTypeSpecifiers = true;
2862 WantExpressionKeywords = true;
2863 WantCXXNamedCasts = true;
2864 WantRemainingKeywords = true;
Douglas Gregor5fd04d42010-05-18 16:14:23 +00002865
2866 if (ObjCMethodDecl *Method = getCurMethodDecl())
2867 if (Method->getClassInterface() &&
2868 Method->getClassInterface()->getSuperClass())
2869 Consumer.addKeywordResult(Context, "super");
2870
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002871 break;
2872
2873 case CTC_NoKeywords:
2874 break;
2875
2876 case CTC_Type:
2877 WantTypeSpecifiers = true;
2878 break;
2879
2880 case CTC_ObjCMessageReceiver:
2881 Consumer.addKeywordResult(Context, "super");
2882 // Fall through to handle message receivers like expressions.
2883
2884 case CTC_Expression:
2885 if (getLangOptions().CPlusPlus)
2886 WantTypeSpecifiers = true;
2887 WantExpressionKeywords = true;
2888 // Fall through to get C++ named casts.
2889
2890 case CTC_CXXCasts:
2891 WantCXXNamedCasts = true;
2892 break;
2893
2894 case CTC_MemberLookup:
2895 if (getLangOptions().CPlusPlus)
2896 Consumer.addKeywordResult(Context, "template");
2897 break;
2898 }
2899
2900 if (WantTypeSpecifiers) {
2901 // Add type-specifier keywords to the set of results.
2902 const char *CTypeSpecs[] = {
2903 "char", "const", "double", "enum", "float", "int", "long", "short",
2904 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2905 "_Complex", "_Imaginary",
2906 // storage-specifiers as well
2907 "extern", "inline", "static", "typedef"
2908 };
2909
2910 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2911 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2912 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2913
2914 if (getLangOptions().C99)
2915 Consumer.addKeywordResult(Context, "restrict");
2916 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2917 Consumer.addKeywordResult(Context, "bool");
2918
2919 if (getLangOptions().CPlusPlus) {
2920 Consumer.addKeywordResult(Context, "class");
2921 Consumer.addKeywordResult(Context, "typename");
2922 Consumer.addKeywordResult(Context, "wchar_t");
2923
2924 if (getLangOptions().CPlusPlus0x) {
2925 Consumer.addKeywordResult(Context, "char16_t");
2926 Consumer.addKeywordResult(Context, "char32_t");
2927 Consumer.addKeywordResult(Context, "constexpr");
2928 Consumer.addKeywordResult(Context, "decltype");
2929 Consumer.addKeywordResult(Context, "thread_local");
2930 }
2931 }
2932
2933 if (getLangOptions().GNUMode)
2934 Consumer.addKeywordResult(Context, "typeof");
2935 }
2936
Douglas Gregor86ad0852010-05-18 16:30:22 +00002937 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002938 Consumer.addKeywordResult(Context, "const_cast");
2939 Consumer.addKeywordResult(Context, "dynamic_cast");
2940 Consumer.addKeywordResult(Context, "reinterpret_cast");
2941 Consumer.addKeywordResult(Context, "static_cast");
2942 }
2943
2944 if (WantExpressionKeywords) {
2945 Consumer.addKeywordResult(Context, "sizeof");
2946 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2947 Consumer.addKeywordResult(Context, "false");
2948 Consumer.addKeywordResult(Context, "true");
2949 }
2950
2951 if (getLangOptions().CPlusPlus) {
2952 const char *CXXExprs[] = {
2953 "delete", "new", "operator", "throw", "typeid"
2954 };
2955 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2956 for (unsigned I = 0; I != NumCXXExprs; ++I)
2957 Consumer.addKeywordResult(Context, CXXExprs[I]);
2958
2959 if (isa<CXXMethodDecl>(CurContext) &&
2960 cast<CXXMethodDecl>(CurContext)->isInstance())
2961 Consumer.addKeywordResult(Context, "this");
2962
2963 if (getLangOptions().CPlusPlus0x) {
2964 Consumer.addKeywordResult(Context, "alignof");
2965 Consumer.addKeywordResult(Context, "nullptr");
2966 }
2967 }
2968 }
2969
2970 if (WantRemainingKeywords) {
2971 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2972 // Statements.
2973 const char *CStmts[] = {
2974 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2975 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2976 for (unsigned I = 0; I != NumCStmts; ++I)
2977 Consumer.addKeywordResult(Context, CStmts[I]);
2978
2979 if (getLangOptions().CPlusPlus) {
2980 Consumer.addKeywordResult(Context, "catch");
2981 Consumer.addKeywordResult(Context, "try");
2982 }
2983
2984 if (S && S->getBreakParent())
2985 Consumer.addKeywordResult(Context, "break");
2986
2987 if (S && S->getContinueParent())
2988 Consumer.addKeywordResult(Context, "continue");
2989
John McCallaab3e412010-08-25 08:40:02 +00002990 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002991 Consumer.addKeywordResult(Context, "case");
2992 Consumer.addKeywordResult(Context, "default");
2993 }
2994 } else {
2995 if (getLangOptions().CPlusPlus) {
2996 Consumer.addKeywordResult(Context, "namespace");
2997 Consumer.addKeywordResult(Context, "template");
2998 }
2999
3000 if (S && S->isClassScope()) {
3001 Consumer.addKeywordResult(Context, "explicit");
3002 Consumer.addKeywordResult(Context, "friend");
3003 Consumer.addKeywordResult(Context, "mutable");
3004 Consumer.addKeywordResult(Context, "private");
3005 Consumer.addKeywordResult(Context, "protected");
3006 Consumer.addKeywordResult(Context, "public");
3007 Consumer.addKeywordResult(Context, "virtual");
3008 }
3009 }
3010
3011 if (getLangOptions().CPlusPlus) {
3012 Consumer.addKeywordResult(Context, "using");
3013
3014 if (getLangOptions().CPlusPlus0x)
3015 Consumer.addKeywordResult(Context, "static_assert");
3016 }
3017 }
3018
3019 // If we haven't found anything, we're done.
Douglas Gregor2d435302009-12-30 17:04:44 +00003020 if (Consumer.empty())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003021 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003022
3023 // Only allow a single, closest name in the result set (it's okay to
3024 // have overloads of that name, though).
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003025 DeclarationName BestName;
3026 NamedDecl *BestIvarOrPropertyDecl = 0;
3027 bool FoundIvarOrPropertyDecl = false;
3028
3029 // Check all of the declaration results to find the best name so far.
3030 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3031 IEnd = Consumer.end();
3032 I != IEnd; ++I) {
3033 if (!BestName)
3034 BestName = (*I)->getDeclName();
3035 else if (BestName != (*I)->getDeclName())
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003036 return DeclarationName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003037
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003038 // \brief Keep track of either an Objective-C ivar or a property, but not
3039 // both.
3040 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
3041 if (FoundIvarOrPropertyDecl)
3042 BestIvarOrPropertyDecl = 0;
3043 else {
3044 BestIvarOrPropertyDecl = *I;
3045 FoundIvarOrPropertyDecl = true;
3046 }
3047 }
Douglas Gregor2d435302009-12-30 17:04:44 +00003048 }
3049
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003050 // Now check all of the keyword results to find the best name.
3051 switch (Consumer.keyword_size()) {
3052 case 0:
3053 // No keywords matched.
3054 break;
3055
3056 case 1:
3057 // If we already have a name
3058 if (!BestName) {
3059 // We did not have anything previously,
3060 BestName = *Consumer.keyword_begin();
3061 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
3062 // We have a declaration with the same name as a context-sensitive
3063 // keyword. The keyword takes precedence.
3064 BestIvarOrPropertyDecl = 0;
3065 FoundIvarOrPropertyDecl = false;
3066 Consumer.clear_decls();
Douglas Gregor86ad0852010-05-18 16:30:22 +00003067 } else if (CTC == CTC_ObjCMessageReceiver &&
3068 (*Consumer.keyword_begin())->isStr("super")) {
3069 // In an Objective-C message send, give the "super" keyword a slight
3070 // edge over entities not in function or method scope.
3071 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3072 IEnd = Consumer.end();
3073 I != IEnd; ++I) {
3074 if ((*I)->getDeclName() == BestName) {
3075 if ((*I)->getDeclContext()->isFunctionOrMethod())
3076 return DeclarationName();
3077 }
3078 }
3079
3080 // Everything found was outside a function or method; the 'super'
3081 // keyword takes precedence.
3082 BestIvarOrPropertyDecl = 0;
3083 FoundIvarOrPropertyDecl = false;
3084 Consumer.clear_decls();
3085 BestName = *Consumer.keyword_begin();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003086 } else {
3087 // Name collision; we will not correct typos.
3088 return DeclarationName();
3089 }
3090 break;
3091
3092 default:
3093 // Name collision; we will not correct typos.
3094 return DeclarationName();
3095 }
3096
Douglas Gregor2d435302009-12-30 17:04:44 +00003097 // BestName is the closest viable name to what the user
3098 // typed. However, to make sure that we don't pick something that's
3099 // way off, make sure that the user typed at least 3 characters for
3100 // each correction.
3101 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003102 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
3103 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003104 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003105
3106 // Perform name lookup again with the name we chose, and declare
3107 // success if we found something that was not ambiguous.
3108 Res.clear();
3109 Res.setLookupName(BestName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003110
3111 // If we found an ivar or property, add that result; no further
3112 // lookup is required.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003113 if (BestIvarOrPropertyDecl)
3114 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003115 // If we're looking into the context of a member, perform qualified
3116 // name lookup on the best name.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003117 else if (!Consumer.keyword_empty()) {
3118 // The best match was a keyword. Return it.
3119 return BestName;
3120 } else if (MemberContext)
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003121 LookupQualifiedName(Res, MemberContext);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003122 // Perform lookup as if we had just parsed the best name.
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003123 else
3124 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3125 EnteringContext);
Douglas Gregor598b08f2009-12-31 05:20:13 +00003126
3127 if (Res.isAmbiguous()) {
3128 Res.suppressDiagnostics();
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003129 return DeclarationName();
Douglas Gregor598b08f2009-12-31 05:20:13 +00003130 }
3131
Douglas Gregorfd0e2e32010-04-14 17:09:22 +00003132 if (Res.getResultKind() != LookupResult::NotFound)
3133 return BestName;
3134
3135 return DeclarationName();
Douglas Gregor2d435302009-12-30 17:04:44 +00003136}