blob: 8c8c0073b3ab83e3e8855de8e5f19c5982688426 [file] [log] [blame]
Douglas Gregoreb11cd02009-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 Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/DeclSpec.h"
John McCall5f1e0942010-08-24 08:50:51 +000017#include "clang/Sema/Scope.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000021#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000024#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000025#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000026#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000028#include "clang/Basic/LangOptions.h"
John McCall50df6ae2010-08-25 07:03:20 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000031#include "llvm/ADT/SmallPtrSet.h"
John McCall6e247262009-10-10 05:48:19 +000032#include "llvm/Support/ErrorHandling.h"
Douglas Gregor546be3c2009-12-30 17:04:44 +000033#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000034#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000035#include <vector>
36#include <iterator>
37#include <utility>
38#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000039
40using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000041using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000042
John McCalld7be78a2009-11-10 07:01:13 +000043namespace {
44 class UnqualUsingEntry {
45 const DeclContext *Nominated;
46 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000047
John McCalld7be78a2009-11-10 07:01:13 +000048 public:
49 UnqualUsingEntry(const DeclContext *Nominated,
50 const DeclContext *CommonAncestor)
51 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
52 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000053
John McCalld7be78a2009-11-10 07:01:13 +000054 const DeclContext *getCommonAncestor() const {
55 return CommonAncestor;
56 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000057
John McCalld7be78a2009-11-10 07:01:13 +000058 const DeclContext *getNominatedNamespace() const {
59 return Nominated;
60 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000061
John McCalld7be78a2009-11-10 07:01:13 +000062 // Sort by the pointer value of the common ancestor.
63 struct Comparator {
64 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
65 return L.getCommonAncestor() < R.getCommonAncestor();
66 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000067
John McCalld7be78a2009-11-10 07:01:13 +000068 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
69 return E.getCommonAncestor() < DC;
70 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000071
John McCalld7be78a2009-11-10 07:01:13 +000072 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
73 return DC < E.getCommonAncestor();
74 }
75 };
76 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000077
John McCalld7be78a2009-11-10 07:01:13 +000078 /// A collection of using directives, as used by C++ unqualified
79 /// lookup.
80 class UnqualUsingDirectiveSet {
81 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000082
John McCalld7be78a2009-11-10 07:01:13 +000083 ListTy list;
84 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000085
John McCalld7be78a2009-11-10 07:01:13 +000086 public:
87 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000088
John McCalld7be78a2009-11-10 07:01:13 +000089 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
90 // C++ [namespace.udir]p1:
91 // During unqualified name lookup, the names appear as if they
92 // were declared in the nearest enclosing namespace which contains
93 // both the using-directive and the nominated namespace.
94 DeclContext *InnermostFileDC
95 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
96 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +000097
John McCalld7be78a2009-11-10 07:01:13 +000098 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +000099 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
100 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
101 visit(Ctx, EffectiveDC);
102 } else {
103 Scope::udir_iterator I = S->using_directives_begin(),
104 End = S->using_directives_end();
105
106 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000107 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000108 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000109 }
110 }
John McCalld7be78a2009-11-10 07:01:13 +0000111
112 // Visits a context and collect all of its using directives
113 // recursively. Treats all using directives as if they were
114 // declared in the context.
115 //
116 // A given context is only every visited once, so it is important
117 // that contexts be visited from the inside out in order to get
118 // the effective DCs right.
119 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
120 if (!visited.insert(DC))
121 return;
122
123 addUsingDirectives(DC, EffectiveDC);
124 }
125
126 // Visits a using directive and collects all of its using
127 // directives recursively. Treats all using directives as if they
128 // were declared in the effective DC.
129 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
130 DeclContext *NS = UD->getNominatedNamespace();
131 if (!visited.insert(NS))
132 return;
133
134 addUsingDirective(UD, EffectiveDC);
135 addUsingDirectives(NS, EffectiveDC);
136 }
137
138 // Adds all the using directives in a context (and those nominated
139 // by its using directives, transitively) as if they appeared in
140 // the given effective context.
141 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
142 llvm::SmallVector<DeclContext*,4> queue;
143 while (true) {
144 DeclContext::udir_iterator I, End;
145 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
146 UsingDirectiveDecl *UD = *I;
147 DeclContext *NS = UD->getNominatedNamespace();
148 if (visited.insert(NS)) {
149 addUsingDirective(UD, EffectiveDC);
150 queue.push_back(NS);
151 }
152 }
153
154 if (queue.empty())
155 return;
156
157 DC = queue.back();
158 queue.pop_back();
159 }
160 }
161
162 // Add a using directive as if it had been declared in the given
163 // context. This helps implement C++ [namespace.udir]p3:
164 // The using-directive is transitive: if a scope contains a
165 // using-directive that nominates a second namespace that itself
166 // contains using-directives, the effect is as if the
167 // using-directives from the second namespace also appeared in
168 // the first.
169 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
170 // Find the common ancestor between the effective context and
171 // the nominated namespace.
172 DeclContext *Common = UD->getNominatedNamespace();
173 while (!Common->Encloses(EffectiveDC))
174 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000175 Common = Common->getPrimaryContext();
John McCalld7be78a2009-11-10 07:01:13 +0000176
177 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
178 }
179
180 void done() {
181 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
182 }
183
184 typedef ListTy::iterator iterator;
185 typedef ListTy::const_iterator const_iterator;
186
187 iterator begin() { return list.begin(); }
188 iterator end() { return list.end(); }
189 const_iterator begin() const { return list.begin(); }
190 const_iterator end() const { return list.end(); }
191
192 std::pair<const_iterator,const_iterator>
193 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000194 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000195 UnqualUsingEntry::Comparator());
196 }
197 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000198}
199
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000200// Retrieve the set of identifier namespaces that correspond to a
201// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000202static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
203 bool CPlusPlus,
204 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000205 unsigned IDNS = 0;
206 switch (NameKind) {
207 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000208 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000209 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000210 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000211 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCall1d7c5282009-12-18 10:40:03 +0000212 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
213 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000214 break;
215
John McCall76d32642010-04-24 01:30:58 +0000216 case Sema::LookupOperatorName:
217 // Operator lookup is its own crazy thing; it is not the same
218 // as (e.g.) looking up an operator name for redeclaration.
219 assert(!Redeclaration && "cannot do redeclaration operator lookup");
220 IDNS = Decl::IDNS_NonMemberOperator;
221 break;
222
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000223 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000224 if (CPlusPlus) {
225 IDNS = Decl::IDNS_Type;
226
227 // When looking for a redeclaration of a tag name, we add:
228 // 1) TagFriend to find undeclared friend decls
229 // 2) Namespace because they can't "overload" with tag decls.
230 // 3) Tag because it includes class templates, which can't
231 // "overload" with tag decls.
232 if (Redeclaration)
233 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
234 } else {
235 IDNS = Decl::IDNS_Tag;
236 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000237 break;
238
239 case Sema::LookupMemberName:
240 IDNS = Decl::IDNS_Member;
241 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000242 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000243 break;
244
245 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000246 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
247 break;
248
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000249 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000250 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000251 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000252
John McCall9f54ad42009-12-10 09:41:52 +0000253 case Sema::LookupUsingDeclName:
254 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
255 | Decl::IDNS_Member | Decl::IDNS_Using;
256 break;
257
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000258 case Sema::LookupObjCProtocolName:
259 IDNS = Decl::IDNS_ObjCProtocol;
260 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000261
262 case Sema::LookupAnyName:
263 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
264 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
265 | Decl::IDNS_Type;
266 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000267 }
268 return IDNS;
269}
270
John McCall1d7c5282009-12-18 10:40:03 +0000271void LookupResult::configure() {
272 IDNS = getIDNS(LookupKind,
273 SemaRef.getLangOptions().CPlusPlus,
274 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000275
276 // If we're looking for one of the allocation or deallocation
277 // operators, make sure that the implicitly-declared new and delete
278 // operators can be found.
279 if (!isForRedeclaration()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000280 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000281 case OO_New:
282 case OO_Delete:
283 case OO_Array_New:
284 case OO_Array_Delete:
285 SemaRef.DeclareGlobalNewDelete();
286 break;
287
288 default:
289 break;
290 }
291 }
John McCall1d7c5282009-12-18 10:40:03 +0000292}
293
John McCall2a7fb272010-08-25 05:32:35 +0000294#ifndef NDEBUG
295void LookupResult::sanity() const {
296 assert(ResultKind != NotFound || Decls.size() == 0);
297 assert(ResultKind != Found || Decls.size() == 1);
298 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
299 (Decls.size() == 1 &&
300 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
301 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
302 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
303 (Decls.size() == 1 && Ambiguity == AmbiguousBaseSubobjects));
304 assert((Paths != NULL) == (ResultKind == Ambiguous &&
305 (Ambiguity == AmbiguousBaseSubobjectTypes ||
306 Ambiguity == AmbiguousBaseSubobjects)));
307}
308#endif
309
John McCallf36e02d2009-10-09 21:13:30 +0000310// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000311void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000312 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000313}
314
John McCall7453ed42009-11-22 00:44:51 +0000315/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000316void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000317 unsigned N = Decls.size();
John McCall9f54ad42009-12-10 09:41:52 +0000318
John McCallf36e02d2009-10-09 21:13:30 +0000319 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000320 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000321 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000322 return;
323 }
324
John McCall7453ed42009-11-22 00:44:51 +0000325 // If there's a single decl, we need to examine it to decide what
326 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000327 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000328 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
329 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000330 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000331 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000332 ResultKind = FoundUnresolvedValue;
333 return;
334 }
John McCallf36e02d2009-10-09 21:13:30 +0000335
John McCall6e247262009-10-10 05:48:19 +0000336 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000337 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000338
John McCallf36e02d2009-10-09 21:13:30 +0000339 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000340 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
341
John McCallf36e02d2009-10-09 21:13:30 +0000342 bool Ambiguous = false;
343 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000344 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000345
346 unsigned UniqueTagIndex = 0;
347
348 unsigned I = 0;
349 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000350 NamedDecl *D = Decls[I]->getUnderlyingDecl();
351 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000352
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000353 // Redeclarations of types via typedef can occur both within a scope
354 // and, through using declarations and directives, across scopes. There is
355 // no ambiguity if they all refer to the same type, so unique based on the
356 // canonical type.
357 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
358 if (!TD->getDeclContext()->isRecord()) {
359 QualType T = SemaRef.Context.getTypeDeclType(TD);
360 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
361 // The type is not unique; pull something off the back and continue
362 // at this index.
363 Decls[I] = Decls[--N];
364 continue;
365 }
366 }
367 }
368
John McCall314be4e2009-11-17 07:50:12 +0000369 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000370 // If it's not unique, pull something off the back (and
371 // continue at this index).
372 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000373 continue;
374 }
375
376 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000377
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000378 if (isa<UnresolvedUsingValueDecl>(D)) {
379 HasUnresolved = true;
380 } else if (isa<TagDecl>(D)) {
381 if (HasTag)
382 Ambiguous = true;
383 UniqueTagIndex = I;
384 HasTag = true;
385 } else if (isa<FunctionTemplateDecl>(D)) {
386 HasFunction = true;
387 HasFunctionTemplate = true;
388 } else if (isa<FunctionDecl>(D)) {
389 HasFunction = true;
390 } else {
391 if (HasNonFunction)
392 Ambiguous = true;
393 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000394 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000395 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000396 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000397
John McCallf36e02d2009-10-09 21:13:30 +0000398 // C++ [basic.scope.hiding]p2:
399 // A class name or enumeration name can be hidden by the name of
400 // an object, function, or enumerator declared in the same
401 // scope. If a class or enumeration name and an object, function,
402 // or enumerator are declared in the same scope (in any order)
403 // with the same name, the class or enumeration name is hidden
404 // wherever the object, function, or enumerator name is visible.
405 // But it's still an error if there are distinct tag types found,
406 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000407 if (HideTags && HasTag && !Ambiguous &&
408 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000409 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000410
John McCallf36e02d2009-10-09 21:13:30 +0000411 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000412
John McCallfda8e122009-12-03 00:58:24 +0000413 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000414 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000415
John McCallf36e02d2009-10-09 21:13:30 +0000416 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000417 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000418 else if (HasUnresolved)
419 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000420 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000421 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000422 else
John McCalla24dc2e2009-11-17 02:14:36 +0000423 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000424}
425
John McCall7d384dd2009-11-18 07:57:50 +0000426void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000427 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000428 DeclContext::lookup_iterator DI, DE;
429 for (I = P.begin(), E = P.end(); I != E; ++I)
430 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
431 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000432}
433
John McCall7d384dd2009-11-18 07:57:50 +0000434void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000435 Paths = new CXXBasePaths;
436 Paths->swap(P);
437 addDeclsFromBasePaths(*Paths);
438 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000439 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000440}
441
John McCall7d384dd2009-11-18 07:57:50 +0000442void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000443 Paths = new CXXBasePaths;
444 Paths->swap(P);
445 addDeclsFromBasePaths(*Paths);
446 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000447 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000448}
449
John McCall7d384dd2009-11-18 07:57:50 +0000450void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000451 Out << Decls.size() << " result(s)";
452 if (isAmbiguous()) Out << ", ambiguous";
453 if (Paths) Out << ", base paths present";
454
455 for (iterator I = begin(), E = end(); I != E; ++I) {
456 Out << "\n";
457 (*I)->print(Out, 2);
458 }
459}
460
Douglas Gregor85910982010-02-12 05:48:04 +0000461/// \brief Lookup a builtin function, when name lookup would otherwise
462/// fail.
463static bool LookupBuiltin(Sema &S, LookupResult &R) {
464 Sema::LookupNameKind NameKind = R.getLookupKind();
465
466 // If we didn't find a use of this identifier, and if the identifier
467 // corresponds to a compiler builtin, create the decl object for the builtin
468 // now, injecting it into translation unit scope, and return it.
469 if (NameKind == Sema::LookupOrdinaryName ||
470 NameKind == Sema::LookupRedeclarationWithLinkage) {
471 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
472 if (II) {
473 // If this is a builtin on this (or all) targets, create the decl.
474 if (unsigned BuiltinID = II->getBuiltinID()) {
475 // In C++, we don't have any predefined library functions like
476 // 'malloc'. Instead, we'll just error.
477 if (S.getLangOptions().CPlusPlus &&
478 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
479 return false;
480
481 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
482 S.TUScope, R.isForRedeclaration(),
483 R.getNameLoc());
484 if (D)
485 R.addDecl(D);
486 return (D != NULL);
487 }
488 }
489 }
490
491 return false;
492}
493
Douglas Gregor4923aa22010-07-02 20:37:36 +0000494/// \brief Determine whether we can declare a special member function within
495/// the class at this point.
496static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
497 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000498 // Don't do it if the class is invalid.
499 if (Class->isInvalidDecl())
500 return false;
501
Douglas Gregor4923aa22010-07-02 20:37:36 +0000502 // We need to have a definition for the class.
503 if (!Class->getDefinition() || Class->isDependentContext())
504 return false;
505
506 // We can't be in the middle of defining the class.
507 if (const RecordType *RecordTy
508 = Context.getTypeDeclType(Class)->getAs<RecordType>())
509 return !RecordTy->isBeingDefined();
510
511 return false;
512}
513
514void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000515 if (!CanDeclareSpecialMemberFunction(Context, Class))
516 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000517
518 // If the default constructor has not yet been declared, do so now.
519 if (!Class->hasDeclaredDefaultConstructor())
520 DeclareImplicitDefaultConstructor(Class);
Douglas Gregor22584312010-07-02 23:41:54 +0000521
522 // If the copy constructor has not yet been declared, do so now.
523 if (!Class->hasDeclaredCopyConstructor())
524 DeclareImplicitCopyConstructor(Class);
525
Douglas Gregora376d102010-07-02 21:50:04 +0000526 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000527 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000528 DeclareImplicitCopyAssignment(Class);
529
Douglas Gregor4923aa22010-07-02 20:37:36 +0000530 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000531 if (!Class->hasDeclaredDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +0000532 DeclareImplicitDestructor(Class);
533}
534
Douglas Gregora376d102010-07-02 21:50:04 +0000535/// \brief Determine whether this is the name of an implicitly-declared
536/// special member function.
537static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
538 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000539 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000540 case DeclarationName::CXXDestructorName:
541 return true;
542
543 case DeclarationName::CXXOperatorName:
544 return Name.getCXXOverloadedOperator() == OO_Equal;
545
546 default:
547 break;
548 }
549
550 return false;
551}
552
553/// \brief If there are any implicit member functions with the given name
554/// that need to be declared in the given declaration context, do so.
555static void DeclareImplicitMemberFunctionsWithName(Sema &S,
556 DeclarationName Name,
557 const DeclContext *DC) {
558 if (!DC)
559 return;
560
561 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000562 case DeclarationName::CXXConstructorName:
563 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000564 if (Record->getDefinition() &&
565 CanDeclareSpecialMemberFunction(S.Context, Record)) {
566 if (!Record->hasDeclaredDefaultConstructor())
567 S.DeclareImplicitDefaultConstructor(
568 const_cast<CXXRecordDecl *>(Record));
569 if (!Record->hasDeclaredCopyConstructor())
570 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
571 }
Douglas Gregor22584312010-07-02 23:41:54 +0000572 break;
573
Douglas Gregora376d102010-07-02 21:50:04 +0000574 case DeclarationName::CXXDestructorName:
575 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
576 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
577 CanDeclareSpecialMemberFunction(S.Context, Record))
578 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000579 break;
580
581 case DeclarationName::CXXOperatorName:
582 if (Name.getCXXOverloadedOperator() != OO_Equal)
583 break;
584
585 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
586 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
587 CanDeclareSpecialMemberFunction(S.Context, Record))
588 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
589 break;
590
591 default:
592 break;
593 }
594}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000595
John McCallf36e02d2009-10-09 21:13:30 +0000596// Adds all qualifying matches for a name within a decl context to the
597// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000598static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000599 bool Found = false;
600
Douglas Gregor4923aa22010-07-02 20:37:36 +0000601 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000602 if (S.getLangOptions().CPlusPlus)
603 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000604
605 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000606 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000607 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000608 NamedDecl *D = *I;
609 if (R.isAcceptableDecl(D)) {
610 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000611 Found = true;
612 }
613 }
John McCallf36e02d2009-10-09 21:13:30 +0000614
Douglas Gregor85910982010-02-12 05:48:04 +0000615 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
616 return true;
617
Douglas Gregor48026d22010-01-11 18:40:55 +0000618 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000619 != DeclarationName::CXXConversionFunctionName ||
620 R.getLookupName().getCXXNameType()->isDependentType() ||
621 !isa<CXXRecordDecl>(DC))
622 return Found;
623
624 // C++ [temp.mem]p6:
625 // A specialization of a conversion function template is not found by
626 // name lookup. Instead, any conversion function templates visible in the
627 // context of the use are considered. [...]
628 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
629 if (!Record->isDefinition())
630 return Found;
631
632 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
633 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
634 UEnd = Unresolved->end(); U != UEnd; ++U) {
635 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
636 if (!ConvTemplate)
637 continue;
638
639 // When we're performing lookup for the purposes of redeclaration, just
640 // add the conversion function template. When we deduce template
641 // arguments for specializations, we'll end up unifying the return
642 // type of the new declaration with the type of the function template.
643 if (R.isForRedeclaration()) {
644 R.addDecl(ConvTemplate);
645 Found = true;
646 continue;
647 }
648
Douglas Gregor48026d22010-01-11 18:40:55 +0000649 // C++ [temp.mem]p6:
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000650 // [...] For each such operator, if argument deduction succeeds
651 // (14.9.2.3), the resulting specialization is used as if found by
652 // name lookup.
653 //
654 // When referencing a conversion function for any purpose other than
655 // a redeclaration (such that we'll be building an expression with the
656 // result), perform template argument deduction and place the
657 // specialization into the result set. We do this to avoid forcing all
658 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000659 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000660 FunctionDecl *Specialization = 0;
661
662 const FunctionProtoType *ConvProto
663 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
664 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000665
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000666 // Compute the type of the function that we would expect the conversion
667 // function to have, if it were to match the name given.
668 // FIXME: Calling convention!
Rafael Espindola264ba482010-03-30 20:24:48 +0000669 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000670 QualType ExpectedType
671 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
672 0, 0, ConvProto->isVariadic(),
673 ConvProto->getTypeQuals(),
674 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000675 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000676
677 // Perform template argument deduction against the type that we would
678 // expect the function to have.
679 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
680 Specialization, Info)
681 == Sema::TDK_Success) {
682 R.addDecl(Specialization);
683 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000684 }
685 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000686
John McCallf36e02d2009-10-09 21:13:30 +0000687 return Found;
688}
689
John McCalld7be78a2009-11-10 07:01:13 +0000690// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000691static bool
Douglas Gregor85910982010-02-12 05:48:04 +0000692CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
693 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000694
695 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
696
John McCalld7be78a2009-11-10 07:01:13 +0000697 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000698 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000699
John McCalld7be78a2009-11-10 07:01:13 +0000700 // Perform direct name lookup into the namespaces nominated by the
701 // using directives whose common ancestor is this namespace.
702 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
703 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000704
John McCalld7be78a2009-11-10 07:01:13 +0000705 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000706 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000707 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000708
709 R.resolveKind();
710
711 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000712}
713
714static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000715 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000716 return Ctx->isFileContext();
717 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000718}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000719
Douglas Gregor711be1e2010-03-15 14:33:29 +0000720// Find the next outer declaration context from this scope. This
721// routine actually returns the semantic outer context, which may
722// differ from the lexical context (encoded directly in the Scope
723// stack) when we are parsing a member of a class template. In this
724// case, the second element of the pair will be true, to indicate that
725// name lookup should continue searching in this semantic context when
726// it leaves the current template parameter scope.
727static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
728 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
729 DeclContext *Lexical = 0;
730 for (Scope *OuterS = S->getParent(); OuterS;
731 OuterS = OuterS->getParent()) {
732 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000733 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000734 break;
735 }
736 }
737
738 // C++ [temp.local]p8:
739 // In the definition of a member of a class template that appears
740 // outside of the namespace containing the class template
741 // definition, the name of a template-parameter hides the name of
742 // a member of this namespace.
743 //
744 // Example:
745 //
746 // namespace N {
747 // class C { };
748 //
749 // template<class T> class B {
750 // void f(T);
751 // };
752 // }
753 //
754 // template<class C> void N::B<C>::f(C) {
755 // C b; // C is the template parameter, not N::C
756 // }
757 //
758 // In this example, the lexical context we return is the
759 // TranslationUnit, while the semantic context is the namespace N.
760 if (!Lexical || !DC || !S->getParent() ||
761 !S->getParent()->isTemplateParamScope())
762 return std::make_pair(Lexical, false);
763
764 // Find the outermost template parameter scope.
765 // For the example, this is the scope for the template parameters of
766 // template<class C>.
767 Scope *OutermostTemplateScope = S->getParent();
768 while (OutermostTemplateScope->getParent() &&
769 OutermostTemplateScope->getParent()->isTemplateParamScope())
770 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregore942bbe2009-09-10 16:57:35 +0000771
Douglas Gregor711be1e2010-03-15 14:33:29 +0000772 // Find the namespace context in which the original scope occurs. In
773 // the example, this is namespace N.
774 DeclContext *Semantic = DC;
775 while (!Semantic->isFileContext())
776 Semantic = Semantic->getParent();
777
778 // Find the declaration context just outside of the template
779 // parameter scope. This is the context in which the template is
780 // being lexically declaration (a namespace context). In the
781 // example, this is the global scope.
782 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
783 Lexical->Encloses(Semantic))
784 return std::make_pair(Semantic, true);
785
786 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000787}
788
John McCalla24dc2e2009-11-17 02:14:36 +0000789bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000790 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000791
792 DeclarationName Name = R.getLookupName();
793
Douglas Gregora376d102010-07-02 21:50:04 +0000794 // If this is the name of an implicitly-declared special member function,
795 // go through the scope stack to implicitly declare
796 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
797 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
798 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
799 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
800 }
801
802 // Implicitly declare member functions with the name we're looking for, if in
803 // fact we are in a scope where it matters.
804
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000805 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000806 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000807 I = IdResolver.begin(Name),
808 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000809
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000810 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000811 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000812 // ...During unqualified name lookup (3.4.1), the names appear as if
813 // they were declared in the nearest enclosing namespace which contains
814 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000815 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000816 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000817 //
818 // For example:
819 // namespace A { int i; }
820 // void foo() {
821 // int i;
822 // {
823 // using namespace A;
824 // ++i; // finds local 'i', A::i appears at global scope
825 // }
826 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000827 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000828 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000829 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000830 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
831
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000832 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000833 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000834 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000835 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000836 Found = true;
837 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000838 }
839 }
John McCallf36e02d2009-10-09 21:13:30 +0000840 if (Found) {
841 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000842 if (S->isClassScope())
843 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
844 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000845 return true;
846 }
847
Douglas Gregor711be1e2010-03-15 14:33:29 +0000848 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
849 S->getParent() && !S->getParent()->isTemplateParamScope()) {
850 // We've just searched the last template parameter scope and
851 // found nothing, so look into the the contexts between the
852 // lexical and semantic declaration contexts returned by
853 // findOuterContext(). This implements the name lookup behavior
854 // of C++ [temp.local]p8.
855 Ctx = OutsideOfTemplateParamDC;
856 OutsideOfTemplateParamDC = 0;
857 }
858
859 if (Ctx) {
860 DeclContext *OuterCtx;
861 bool SearchAfterTemplateScope;
862 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
863 if (SearchAfterTemplateScope)
864 OutsideOfTemplateParamDC = OuterCtx;
865
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000866 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000867 // We do not directly look into transparent contexts, since
868 // those entities will be found in the nearest enclosing
869 // non-transparent context.
870 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000871 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000872
873 // We do not look directly into function or method contexts,
874 // since all of the local variables and parameters of the
875 // function/method are present within the Scope.
876 if (Ctx->isFunctionOrMethod()) {
877 // If we have an Objective-C instance method, look for ivars
878 // in the corresponding interface.
879 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
880 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
881 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
882 ObjCInterfaceDecl *ClassDeclared;
883 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
884 Name.getAsIdentifierInfo(),
885 ClassDeclared)) {
886 if (R.isAcceptableDecl(Ivar)) {
887 R.addDecl(Ivar);
888 R.resolveKind();
889 return true;
890 }
891 }
892 }
893 }
894
895 continue;
896 }
897
Douglas Gregore942bbe2009-09-10 16:57:35 +0000898 // Perform qualified name lookup into this context.
899 // FIXME: In some cases, we know that every name that could be found by
900 // this qualified name lookup will also be on the identifier chain. For
901 // example, inside a class without any base classes, we never need to
902 // perform qualified lookup because all of the members are on top of the
903 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000904 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000905 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000906 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000907 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000908 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000909
John McCalld7be78a2009-11-10 07:01:13 +0000910 // Stop if we ran out of scopes.
911 // FIXME: This really, really shouldn't be happening.
912 if (!S) return false;
913
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000914 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000915 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000916 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000917 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
918 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000919
John McCalld7be78a2009-11-10 07:01:13 +0000920 UnqualUsingDirectiveSet UDirs;
921 UDirs.visitScopeChain(Initial, S);
922 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000923
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000924 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000925 // Unqualified name lookup in C++ requires looking into scopes
926 // that aren't strictly lexical, and therefore we walk through the
927 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000928
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000929 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000930 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000931 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000932 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000933 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000934 // We found something. Look for anything else in our scope
935 // with this same name and in an acceptable identifier
936 // namespace, so that we can construct an overload set if we
937 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000938 Found = true;
939 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000940 }
941 }
942
Douglas Gregor00b4b032010-05-14 04:53:42 +0000943 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000944 R.resolveKind();
945 return true;
946 }
947
Douglas Gregor00b4b032010-05-14 04:53:42 +0000948 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
949 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
950 S->getParent() && !S->getParent()->isTemplateParamScope()) {
951 // We've just searched the last template parameter scope and
952 // found nothing, so look into the the contexts between the
953 // lexical and semantic declaration contexts returned by
954 // findOuterContext(). This implements the name lookup behavior
955 // of C++ [temp.local]p8.
956 Ctx = OutsideOfTemplateParamDC;
957 OutsideOfTemplateParamDC = 0;
958 }
959
960 if (Ctx) {
961 DeclContext *OuterCtx;
962 bool SearchAfterTemplateScope;
963 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
964 if (SearchAfterTemplateScope)
965 OutsideOfTemplateParamDC = OuterCtx;
966
967 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
968 // We do not directly look into transparent contexts, since
969 // those entities will be found in the nearest enclosing
970 // non-transparent context.
971 if (Ctx->isTransparentContext())
972 continue;
973
974 // If we have a context, and it's not a context stashed in the
975 // template parameter scope for an out-of-line definition, also
976 // look into that context.
977 if (!(Found && S && S->isTemplateParamScope())) {
978 assert(Ctx->isFileContext() &&
979 "We should have been looking only at file context here already.");
980
981 // Look into context considering using-directives.
982 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
983 Found = true;
984 }
985
986 if (Found) {
987 R.resolveKind();
988 return true;
989 }
990
991 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
992 return false;
993 }
994 }
995
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000996 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000997 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000998 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000999
John McCallf36e02d2009-10-09 21:13:30 +00001000 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001001}
1002
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001003/// @brief Perform unqualified name lookup starting from a given
1004/// scope.
1005///
1006/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1007/// used to find names within the current scope. For example, 'x' in
1008/// @code
1009/// int x;
1010/// int f() {
1011/// return x; // unqualified name look finds 'x' in the global scope
1012/// }
1013/// @endcode
1014///
1015/// Different lookup criteria can find different names. For example, a
1016/// particular scope can have both a struct and a function of the same
1017/// name, and each can be found by certain lookup criteria. For more
1018/// information about lookup criteria, see the documentation for the
1019/// class LookupCriteria.
1020///
1021/// @param S The scope from which unqualified name lookup will
1022/// begin. If the lookup criteria permits, name lookup may also search
1023/// in the parent scopes.
1024///
1025/// @param Name The name of the entity that we are searching for.
1026///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001027/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001028/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001029/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001030///
1031/// @returns The result of name lookup, which includes zero or more
1032/// declarations and possibly additional information used to diagnose
1033/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001034bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1035 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001036 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001037
John McCalla24dc2e2009-11-17 02:14:36 +00001038 LookupNameKind NameKind = R.getLookupKind();
1039
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001040 if (!getLangOptions().CPlusPlus) {
1041 // Unqualified name lookup in C/Objective-C is purely lexical, so
1042 // search in the declarations attached to the name.
1043
John McCall1d7c5282009-12-18 10:40:03 +00001044 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001045 // Find the nearest non-transparent declaration scope.
1046 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001047 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001048 static_cast<DeclContext *>(S->getEntity())
1049 ->isTransparentContext()))
1050 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001051 }
1052
John McCall1d7c5282009-12-18 10:40:03 +00001053 unsigned IDNS = R.getIdentifierNamespace();
1054
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001055 // Scan up the scope chain looking for a decl that matches this
1056 // identifier that is in the appropriate namespace. This search
1057 // should not take long, as shadowing of names is uncommon, and
1058 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001059 bool LeftStartingScope = false;
1060
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001061 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001062 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001063 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001064 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001065 if (NameKind == LookupRedeclarationWithLinkage) {
1066 // Determine whether this (or a previous) declaration is
1067 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001068 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001069 LeftStartingScope = true;
1070
1071 // If we found something outside of our starting scope that
1072 // does not have linkage, skip it.
1073 if (LeftStartingScope && !((*I)->hasLinkage()))
1074 continue;
1075 }
1076
John McCallf36e02d2009-10-09 21:13:30 +00001077 R.addDecl(*I);
1078
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001079 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001080 // If this declaration has the "overloadable" attribute, we
1081 // might have a set of overloaded functions.
1082
1083 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001084 while (!(S->getFlags() & Scope::DeclScope) ||
John McCalld226f652010-08-21 09:40:31 +00001085 !S->isDeclScope(*I))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001086 S = S->getParent();
1087
1088 // Find the last declaration in this scope (with the same
1089 // name, naturally).
1090 IdentifierResolver::iterator LastI = I;
1091 for (++LastI; LastI != IEnd; ++LastI) {
John McCalld226f652010-08-21 09:40:31 +00001092 if (!S->isDeclScope(*LastI))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001093 break;
John McCallf36e02d2009-10-09 21:13:30 +00001094 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001095 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001096 }
1097
John McCallf36e02d2009-10-09 21:13:30 +00001098 R.resolveKind();
1099
1100 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001101 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001102 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001103 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001104 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001105 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001106 }
1107
1108 // If we didn't find a use of this identifier, and if the identifier
1109 // corresponds to a compiler builtin, create the decl object for the builtin
1110 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +00001111 if (AllowBuiltinCreation)
1112 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001113
John McCallf36e02d2009-10-09 21:13:30 +00001114 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001115}
1116
John McCall6e247262009-10-10 05:48:19 +00001117/// @brief Perform qualified name lookup in the namespaces nominated by
1118/// using directives by the given context.
1119///
1120/// C++98 [namespace.qual]p2:
1121/// Given X::m (where X is a user-declared namespace), or given ::m
1122/// (where X is the global namespace), let S be the set of all
1123/// declarations of m in X and in the transitive closure of all
1124/// namespaces nominated by using-directives in X and its used
1125/// namespaces, except that using-directives are ignored in any
1126/// namespace, including X, directly containing one or more
1127/// declarations of m. No namespace is searched more than once in
1128/// the lookup of a name. If S is the empty set, the program is
1129/// ill-formed. Otherwise, if S has exactly one member, or if the
1130/// context of the reference is a using-declaration
1131/// (namespace.udecl), S is the required set of declarations of
1132/// m. Otherwise if the use of m is not one that allows a unique
1133/// declaration to be chosen from S, the program is ill-formed.
1134/// C++98 [namespace.qual]p5:
1135/// During the lookup of a qualified namespace member name, if the
1136/// lookup finds more than one declaration of the member, and if one
1137/// declaration introduces a class name or enumeration name and the
1138/// other declarations either introduce the same object, the same
1139/// enumerator or a set of functions, the non-type name hides the
1140/// class or enumeration name if and only if the declarations are
1141/// from the same namespace; otherwise (the declarations are from
1142/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001143static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001144 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001145 assert(StartDC->isFileContext() && "start context is not a file context");
1146
1147 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1148 DeclContext::udir_iterator E = StartDC->using_directives_end();
1149
1150 if (I == E) return false;
1151
1152 // We have at least added all these contexts to the queue.
1153 llvm::DenseSet<DeclContext*> Visited;
1154 Visited.insert(StartDC);
1155
1156 // We have not yet looked into these namespaces, much less added
1157 // their "using-children" to the queue.
1158 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1159
1160 // We have already looked into the initial namespace; seed the queue
1161 // with its using-children.
1162 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001163 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001164 if (Visited.insert(ND).second)
1165 Queue.push_back(ND);
1166 }
1167
1168 // The easiest way to implement the restriction in [namespace.qual]p5
1169 // is to check whether any of the individual results found a tag
1170 // and, if so, to declare an ambiguity if the final result is not
1171 // a tag.
1172 bool FoundTag = false;
1173 bool FoundNonTag = false;
1174
John McCall7d384dd2009-11-18 07:57:50 +00001175 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001176
1177 bool Found = false;
1178 while (!Queue.empty()) {
1179 NamespaceDecl *ND = Queue.back();
1180 Queue.pop_back();
1181
1182 // We go through some convolutions here to avoid copying results
1183 // between LookupResults.
1184 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001185 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001186 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001187
1188 if (FoundDirect) {
1189 // First do any local hiding.
1190 DirectR.resolveKind();
1191
1192 // If the local result is a tag, remember that.
1193 if (DirectR.isSingleTagDecl())
1194 FoundTag = true;
1195 else
1196 FoundNonTag = true;
1197
1198 // Append the local results to the total results if necessary.
1199 if (UseLocal) {
1200 R.addAllDecls(LocalR);
1201 LocalR.clear();
1202 }
1203 }
1204
1205 // If we find names in this namespace, ignore its using directives.
1206 if (FoundDirect) {
1207 Found = true;
1208 continue;
1209 }
1210
1211 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1212 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1213 if (Visited.insert(Nom).second)
1214 Queue.push_back(Nom);
1215 }
1216 }
1217
1218 if (Found) {
1219 if (FoundTag && FoundNonTag)
1220 R.setAmbiguousQualifiedTagHiding();
1221 else
1222 R.resolveKind();
1223 }
1224
1225 return Found;
1226}
1227
Douglas Gregor8071e422010-08-15 06:18:01 +00001228/// \brief Callback that looks for any member of a class with the given name.
1229static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1230 CXXBasePath &Path,
1231 void *Name) {
1232 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1233
1234 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1235 Path.Decls = BaseRecord->lookup(N);
1236 return Path.Decls.first != Path.Decls.second;
1237}
1238
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001239/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001240///
1241/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1242/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001243/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001244///
1245/// Different lookup criteria can find different names. For example, a
1246/// particular scope can have both a struct and a function of the same
1247/// name, and each can be found by certain lookup criteria. For more
1248/// information about lookup criteria, see the documentation for the
1249/// class LookupCriteria.
1250///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001251/// \param R captures both the lookup criteria and any lookup results found.
1252///
1253/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001254/// search. If the lookup criteria permits, name lookup may also search
1255/// in the parent contexts or (for C++ classes) base classes.
1256///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001257/// \param InUnqualifiedLookup true if this is qualified name lookup that
1258/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001259///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001260/// \returns true if lookup succeeded, false if it failed.
1261bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1262 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001263 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001264
John McCalla24dc2e2009-11-17 02:14:36 +00001265 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001266 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001268 // Make sure that the declaration context is complete.
1269 assert((!isa<TagDecl>(LookupCtx) ||
1270 LookupCtx->isDependentContext() ||
1271 cast<TagDecl>(LookupCtx)->isDefinition() ||
1272 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1273 ->isBeingDefined()) &&
1274 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001276 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001277 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001278 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001279 if (isa<CXXRecordDecl>(LookupCtx))
1280 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001281 return true;
1282 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001283
John McCall6e247262009-10-10 05:48:19 +00001284 // Don't descend into implied contexts for redeclarations.
1285 // C++98 [namespace.qual]p6:
1286 // In a declaration for a namespace member in which the
1287 // declarator-id is a qualified-id, given that the qualified-id
1288 // for the namespace member has the form
1289 // nested-name-specifier unqualified-id
1290 // the unqualified-id shall name a member of the namespace
1291 // designated by the nested-name-specifier.
1292 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001293 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001294 return false;
1295
John McCalla24dc2e2009-11-17 02:14:36 +00001296 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001297 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001298 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001299
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001300 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001301 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001302 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001303 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001304 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001305
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001306 // If we're performing qualified name lookup into a dependent class,
1307 // then we are actually looking into a current instantiation. If we have any
1308 // dependent base classes, then we either have to delay lookup until
1309 // template instantiation time (at which point all bases will be available)
1310 // or we have to fail.
1311 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1312 LookupRec->hasAnyDependentBases()) {
1313 R.setNotFoundInCurrentInstantiation();
1314 return false;
1315 }
1316
Douglas Gregor7176fff2009-01-15 00:26:24 +00001317 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001318 CXXBasePaths Paths;
1319 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001320
1321 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001322 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001323 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001324 case LookupOrdinaryName:
1325 case LookupMemberName:
1326 case LookupRedeclarationWithLinkage:
1327 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1328 break;
1329
1330 case LookupTagName:
1331 BaseCallback = &CXXRecordDecl::FindTagMember;
1332 break;
John McCall9f54ad42009-12-10 09:41:52 +00001333
Douglas Gregor8071e422010-08-15 06:18:01 +00001334 case LookupAnyName:
1335 BaseCallback = &LookupAnyMember;
1336 break;
1337
John McCall9f54ad42009-12-10 09:41:52 +00001338 case LookupUsingDeclName:
1339 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001340
1341 case LookupOperatorName:
1342 case LookupNamespaceName:
1343 case LookupObjCProtocolName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001344 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001345 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001346
1347 case LookupNestedNameSpecifierName:
1348 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1349 break;
1350 }
1351
John McCalla24dc2e2009-11-17 02:14:36 +00001352 if (!LookupRec->lookupInBases(BaseCallback,
1353 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001354 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001355
John McCall92f88312010-01-23 00:46:32 +00001356 R.setNamingClass(LookupRec);
1357
Douglas Gregor7176fff2009-01-15 00:26:24 +00001358 // C++ [class.member.lookup]p2:
1359 // [...] If the resulting set of declarations are not all from
1360 // sub-objects of the same type, or the set has a nonstatic member
1361 // and includes members from distinct sub-objects, there is an
1362 // ambiguity and the program is ill-formed. Otherwise that set is
1363 // the result of the lookup.
1364 // FIXME: support using declarations!
1365 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001366 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001367 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001368 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001369 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001370 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001371
John McCall46460a62010-01-20 21:53:11 +00001372 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1373 // across all paths.
1374 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1375
Douglas Gregor7176fff2009-01-15 00:26:24 +00001376 // Determine whether we're looking at a distinct sub-object or not.
1377 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001378 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001379 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1380 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00001381 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001382 != Context.getCanonicalType(PathElement.Base->getType())) {
1383 // We found members of the given name in two subobjects of
1384 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001385 R.setAmbiguousBaseSubobjectTypes(Paths);
1386 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001387 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1388 // We have a different subobject of the same type.
1389
1390 // C++ [class.member.lookup]p5:
1391 // A static member, a nested type or an enumerator defined in
1392 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001393 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001394 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001395 if (isa<VarDecl>(FirstDecl) ||
1396 isa<TypeDecl>(FirstDecl) ||
1397 isa<EnumConstantDecl>(FirstDecl))
1398 continue;
1399
1400 if (isa<CXXMethodDecl>(FirstDecl)) {
1401 // Determine whether all of the methods are static.
1402 bool AllMethodsAreStatic = true;
1403 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1404 Func != Path->Decls.second; ++Func) {
1405 if (!isa<CXXMethodDecl>(*Func)) {
1406 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1407 break;
1408 }
1409
1410 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1411 AllMethodsAreStatic = false;
1412 break;
1413 }
1414 }
1415
1416 if (AllMethodsAreStatic)
1417 continue;
1418 }
1419
1420 // We have found a nonstatic member name in multiple, distinct
1421 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001422 R.setAmbiguousBaseSubobjects(Paths);
1423 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001424 }
1425 }
1426
1427 // Lookup in a base class succeeded; return these results.
1428
John McCallf36e02d2009-10-09 21:13:30 +00001429 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001430 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1431 NamedDecl *D = *I;
1432 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1433 D->getAccess());
1434 R.addDecl(D, AS);
1435 }
John McCallf36e02d2009-10-09 21:13:30 +00001436 R.resolveKind();
1437 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001438}
1439
1440/// @brief Performs name lookup for a name that was parsed in the
1441/// source code, and may contain a C++ scope specifier.
1442///
1443/// This routine is a convenience routine meant to be called from
1444/// contexts that receive a name and an optional C++ scope specifier
1445/// (e.g., "N::M::x"). It will then perform either qualified or
1446/// unqualified name lookup (with LookupQualifiedName or LookupName,
1447/// respectively) on the given name and return those results.
1448///
1449/// @param S The scope from which unqualified name lookup will
1450/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001451///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001452/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001453///
1454/// @param Name The name of the entity that name lookup will
1455/// search for.
1456///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001457/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001458/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001459/// C library functions (like "malloc") are implicitly declared.
1460///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001461/// @param EnteringContext Indicates whether we are going to enter the
1462/// context of the scope-specifier SS (if present).
1463///
John McCallf36e02d2009-10-09 21:13:30 +00001464/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001465bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001466 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001467 if (SS && SS->isInvalid()) {
1468 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001469 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001470 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001471 }
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Douglas Gregor495c35d2009-08-25 22:51:20 +00001473 if (SS && SS->isSet()) {
1474 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001475 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001476 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001477 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001478 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001479
John McCalla24dc2e2009-11-17 02:14:36 +00001480 R.setContextRange(SS->getRange());
1481
1482 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001483 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001484
Douglas Gregor495c35d2009-08-25 22:51:20 +00001485 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001486 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001487 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001488 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001489 }
1490
Mike Stump1eb44332009-09-09 15:08:12 +00001491 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001492 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001493}
1494
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001495
Douglas Gregor7176fff2009-01-15 00:26:24 +00001496/// @brief Produce a diagnostic describing the ambiguity that resulted
1497/// from name lookup.
1498///
1499/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001500///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001501/// @param Name The name of the entity that name lookup was
1502/// searching for.
1503///
1504/// @param NameLoc The location of the name within the source code.
1505///
1506/// @param LookupRange A source range that provides more
1507/// source-location information concerning the lookup itself. For
1508/// example, this range might highlight a nested-name-specifier that
1509/// precedes the name.
1510///
1511/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001512bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001513 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1514
John McCalla24dc2e2009-11-17 02:14:36 +00001515 DeclarationName Name = Result.getLookupName();
1516 SourceLocation NameLoc = Result.getNameLoc();
1517 SourceRange LookupRange = Result.getContextRange();
1518
John McCall6e247262009-10-10 05:48:19 +00001519 switch (Result.getAmbiguityKind()) {
1520 case LookupResult::AmbiguousBaseSubobjects: {
1521 CXXBasePaths *Paths = Result.getBasePaths();
1522 QualType SubobjectType = Paths->front().back().Base->getType();
1523 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1524 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1525 << LookupRange;
1526
1527 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1528 while (isa<CXXMethodDecl>(*Found) &&
1529 cast<CXXMethodDecl>(*Found)->isStatic())
1530 ++Found;
1531
1532 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1533
1534 return true;
1535 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001536
John McCall6e247262009-10-10 05:48:19 +00001537 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001538 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1539 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001540
1541 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001542 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001543 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1544 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001545 Path != PathEnd; ++Path) {
1546 Decl *D = *Path->Decls.first;
1547 if (DeclsPrinted.insert(D).second)
1548 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1549 }
1550
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001551 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001552 }
1553
John McCall6e247262009-10-10 05:48:19 +00001554 case LookupResult::AmbiguousTagHiding: {
1555 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001556
John McCall6e247262009-10-10 05:48:19 +00001557 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1558
1559 LookupResult::iterator DI, DE = Result.end();
1560 for (DI = Result.begin(); DI != DE; ++DI)
1561 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1562 TagDecls.insert(TD);
1563 Diag(TD->getLocation(), diag::note_hidden_tag);
1564 }
1565
1566 for (DI = Result.begin(); DI != DE; ++DI)
1567 if (!isa<TagDecl>(*DI))
1568 Diag((*DI)->getLocation(), diag::note_hiding_object);
1569
1570 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001571 LookupResult::Filter F = Result.makeFilter();
1572 while (F.hasNext()) {
1573 if (TagDecls.count(F.next()))
1574 F.erase();
1575 }
1576 F.done();
John McCall6e247262009-10-10 05:48:19 +00001577
1578 return true;
1579 }
1580
1581 case LookupResult::AmbiguousReference: {
1582 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001583
John McCall6e247262009-10-10 05:48:19 +00001584 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1585 for (; DI != DE; ++DI)
1586 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001587
John McCall6e247262009-10-10 05:48:19 +00001588 return true;
1589 }
1590 }
1591
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001592 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001593 return true;
1594}
Douglas Gregorfa047642009-02-04 00:32:51 +00001595
John McCallc7e04da2010-05-28 18:45:08 +00001596namespace {
1597 struct AssociatedLookup {
1598 AssociatedLookup(Sema &S,
1599 Sema::AssociatedNamespaceSet &Namespaces,
1600 Sema::AssociatedClassSet &Classes)
1601 : S(S), Namespaces(Namespaces), Classes(Classes) {
1602 }
1603
1604 Sema &S;
1605 Sema::AssociatedNamespaceSet &Namespaces;
1606 Sema::AssociatedClassSet &Classes;
1607 };
1608}
1609
Mike Stump1eb44332009-09-09 15:08:12 +00001610static void
John McCallc7e04da2010-05-28 18:45:08 +00001611addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001612
Douglas Gregor54022952010-04-30 07:08:38 +00001613static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1614 DeclContext *Ctx) {
1615 // Add the associated namespace for this class.
1616
1617 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1618 // be a locally scoped record.
1619
1620 while (Ctx->isRecord() || Ctx->isTransparentContext())
1621 Ctx = Ctx->getParent();
1622
John McCall6ff07852009-08-07 22:18:02 +00001623 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001624 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001625}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001626
Mike Stump1eb44332009-09-09 15:08:12 +00001627// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001628// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001629static void
John McCallc7e04da2010-05-28 18:45:08 +00001630addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1631 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001632 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001633 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001634 switch (Arg.getKind()) {
1635 case TemplateArgument::Null:
1636 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Douglas Gregor69be8d62009-07-08 07:51:57 +00001638 case TemplateArgument::Type:
1639 // [...] the namespaces and classes associated with the types of the
1640 // template arguments provided for template type parameters (excluding
1641 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001642 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001643 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Douglas Gregor788cd062009-11-11 01:00:40 +00001645 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001646 // [...] the namespaces in which any template template arguments are
1647 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001648 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001649 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001650 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001651 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001652 DeclContext *Ctx = ClassTemplate->getDeclContext();
1653 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001654 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001655 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001656 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001657 }
1658 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001659 }
1660
1661 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001662 case TemplateArgument::Integral:
1663 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001664 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001665 // associated namespaces. ]
1666 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Douglas Gregor69be8d62009-07-08 07:51:57 +00001668 case TemplateArgument::Pack:
1669 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1670 PEnd = Arg.pack_end();
1671 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001672 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001673 break;
1674 }
1675}
1676
Douglas Gregorfa047642009-02-04 00:32:51 +00001677// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001678// argument-dependent lookup with an argument of class type
1679// (C++ [basic.lookup.koenig]p2).
1680static void
John McCallc7e04da2010-05-28 18:45:08 +00001681addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1682 CXXRecordDecl *Class) {
1683
1684 // Just silently ignore anything whose name is __va_list_tag.
1685 if (Class->getDeclName() == Result.S.VAListTagName)
1686 return;
1687
Douglas Gregorfa047642009-02-04 00:32:51 +00001688 // C++ [basic.lookup.koenig]p2:
1689 // [...]
1690 // -- If T is a class type (including unions), its associated
1691 // classes are: the class itself; the class of which it is a
1692 // member, if any; and its direct and indirect base
1693 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001694 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001695
1696 // Add the class of which it is a member, if any.
1697 DeclContext *Ctx = Class->getDeclContext();
1698 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001699 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001700 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001701 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Douglas Gregorfa047642009-02-04 00:32:51 +00001703 // Add the class itself. If we've already seen this class, we don't
1704 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001705 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001706 return;
1707
Mike Stump1eb44332009-09-09 15:08:12 +00001708 // -- If T is a template-id, its associated namespaces and classes are
1709 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001710 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001711 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001712 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001713 // namespaces in which any template template arguments are defined; and
1714 // the classes in which any member templates used as template template
1715 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001716 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001717 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001718 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1719 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1720 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001721 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001722 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001723 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Douglas Gregor69be8d62009-07-08 07:51:57 +00001725 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1726 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001727 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001728 }
Mike Stump1eb44332009-09-09 15:08:12 +00001729
John McCall86ff3082010-02-04 22:26:26 +00001730 // Only recurse into base classes for complete types.
1731 if (!Class->hasDefinition()) {
1732 // FIXME: we might need to instantiate templates here
1733 return;
1734 }
1735
Douglas Gregorfa047642009-02-04 00:32:51 +00001736 // Add direct and indirect base classes along with their associated
1737 // namespaces.
1738 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1739 Bases.push_back(Class);
1740 while (!Bases.empty()) {
1741 // Pop this class off the stack.
1742 Class = Bases.back();
1743 Bases.pop_back();
1744
1745 // Visit the base classes.
1746 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1747 BaseEnd = Class->bases_end();
1748 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001749 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001750 // In dependent contexts, we do ADL twice, and the first time around,
1751 // the base type might be a dependent TemplateSpecializationType, or a
1752 // TemplateTypeParmType. If that happens, simply ignore it.
1753 // FIXME: If we want to support export, we probably need to add the
1754 // namespace of the template in a TemplateSpecializationType, or even
1755 // the classes and namespaces of known non-dependent arguments.
1756 if (!BaseType)
1757 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001758 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001759 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001760 // Find the associated namespace for this base class.
1761 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001762 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001763
1764 // Make sure we visit the bases of this base class.
1765 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1766 Bases.push_back(BaseDecl);
1767 }
1768 }
1769 }
1770}
1771
1772// \brief Add the associated classes and namespaces for
1773// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001774// (C++ [basic.lookup.koenig]p2).
1775static void
John McCallc7e04da2010-05-28 18:45:08 +00001776addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001777 // C++ [basic.lookup.koenig]p2:
1778 //
1779 // For each argument type T in the function call, there is a set
1780 // of zero or more associated namespaces and a set of zero or more
1781 // associated classes to be considered. The sets of namespaces and
1782 // classes is determined entirely by the types of the function
1783 // arguments (and the namespace of any template template
1784 // argument). Typedef names and using-declarations used to specify
1785 // the types do not contribute to this set. The sets of namespaces
1786 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001787
John McCallfa4edcf2010-05-28 06:08:54 +00001788 llvm::SmallVector<const Type *, 16> Queue;
1789 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1790
Douglas Gregorfa047642009-02-04 00:32:51 +00001791 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001792 switch (T->getTypeClass()) {
1793
1794#define TYPE(Class, Base)
1795#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1796#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1797#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1798#define ABSTRACT_TYPE(Class, Base)
1799#include "clang/AST/TypeNodes.def"
1800 // T is canonical. We can also ignore dependent types because
1801 // we don't need to do ADL at the definition point, but if we
1802 // wanted to implement template export (or if we find some other
1803 // use for associated classes and namespaces...) this would be
1804 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001805 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001806
John McCallfa4edcf2010-05-28 06:08:54 +00001807 // -- If T is a pointer to U or an array of U, its associated
1808 // namespaces and classes are those associated with U.
1809 case Type::Pointer:
1810 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1811 continue;
1812 case Type::ConstantArray:
1813 case Type::IncompleteArray:
1814 case Type::VariableArray:
1815 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1816 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001817
John McCallfa4edcf2010-05-28 06:08:54 +00001818 // -- If T is a fundamental type, its associated sets of
1819 // namespaces and classes are both empty.
1820 case Type::Builtin:
1821 break;
1822
1823 // -- If T is a class type (including unions), its associated
1824 // classes are: the class itself; the class of which it is a
1825 // member, if any; and its direct and indirect base
1826 // classes. Its associated namespaces are the namespaces in
1827 // which its associated classes are defined.
1828 case Type::Record: {
1829 CXXRecordDecl *Class
1830 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001831 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001832 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001833 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001834
John McCallfa4edcf2010-05-28 06:08:54 +00001835 // -- If T is an enumeration type, its associated namespace is
1836 // the namespace in which it is defined. If it is class
1837 // member, its associated class is the member’s class; else
1838 // it has no associated class.
1839 case Type::Enum: {
1840 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001841
John McCallfa4edcf2010-05-28 06:08:54 +00001842 DeclContext *Ctx = Enum->getDeclContext();
1843 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001844 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001845
John McCallfa4edcf2010-05-28 06:08:54 +00001846 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001847 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001848
John McCallfa4edcf2010-05-28 06:08:54 +00001849 break;
1850 }
1851
1852 // -- If T is a function type, its associated namespaces and
1853 // classes are those associated with the function parameter
1854 // types and those associated with the return type.
1855 case Type::FunctionProto: {
1856 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1857 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1858 ArgEnd = Proto->arg_type_end();
1859 Arg != ArgEnd; ++Arg)
1860 Queue.push_back(Arg->getTypePtr());
1861 // fallthrough
1862 }
1863 case Type::FunctionNoProto: {
1864 const FunctionType *FnType = cast<FunctionType>(T);
1865 T = FnType->getResultType().getTypePtr();
1866 continue;
1867 }
1868
1869 // -- If T is a pointer to a member function of a class X, its
1870 // associated namespaces and classes are those associated
1871 // with the function parameter types and return type,
1872 // together with those associated with X.
1873 //
1874 // -- If T is a pointer to a data member of class X, its
1875 // associated namespaces and classes are those associated
1876 // with the member type together with those associated with
1877 // X.
1878 case Type::MemberPointer: {
1879 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1880
1881 // Queue up the class type into which this points.
1882 Queue.push_back(MemberPtr->getClass());
1883
1884 // And directly continue with the pointee type.
1885 T = MemberPtr->getPointeeType().getTypePtr();
1886 continue;
1887 }
1888
1889 // As an extension, treat this like a normal pointer.
1890 case Type::BlockPointer:
1891 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1892 continue;
1893
1894 // References aren't covered by the standard, but that's such an
1895 // obvious defect that we cover them anyway.
1896 case Type::LValueReference:
1897 case Type::RValueReference:
1898 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1899 continue;
1900
1901 // These are fundamental types.
1902 case Type::Vector:
1903 case Type::ExtVector:
1904 case Type::Complex:
1905 break;
1906
1907 // These are ignored by ADL.
1908 case Type::ObjCObject:
1909 case Type::ObjCInterface:
1910 case Type::ObjCObjectPointer:
1911 break;
1912 }
1913
1914 if (Queue.empty()) break;
1915 T = Queue.back();
1916 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001917 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001918}
1919
1920/// \brief Find the associated classes and namespaces for
1921/// argument-dependent lookup for a call with the given set of
1922/// arguments.
1923///
1924/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001925/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001926/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001927void
Douglas Gregorfa047642009-02-04 00:32:51 +00001928Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1929 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001930 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001931 AssociatedNamespaces.clear();
1932 AssociatedClasses.clear();
1933
John McCallc7e04da2010-05-28 18:45:08 +00001934 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1935
Douglas Gregorfa047642009-02-04 00:32:51 +00001936 // C++ [basic.lookup.koenig]p2:
1937 // For each argument type T in the function call, there is a set
1938 // of zero or more associated namespaces and a set of zero or more
1939 // associated classes to be considered. The sets of namespaces and
1940 // classes is determined entirely by the types of the function
1941 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001942 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001943 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1944 Expr *Arg = Args[ArgIdx];
1945
1946 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00001947 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001948 continue;
1949 }
1950
1951 // [...] In addition, if the argument is the name or address of a
1952 // set of overloaded functions and/or function templates, its
1953 // associated classes and namespaces are the union of those
1954 // associated with each of the members of the set: the namespace
1955 // in which the function or function template is defined and the
1956 // classes and namespaces associated with its (non-dependent)
1957 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001958 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001959 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1960 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1961 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001962
John McCallc7e04da2010-05-28 18:45:08 +00001963 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1964 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00001965
John McCallc7e04da2010-05-28 18:45:08 +00001966 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1967 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001968 // Look through any using declarations to find the underlying function.
1969 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001970
Chandler Carruthbd647292009-12-29 06:17:27 +00001971 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1972 if (!FDecl)
1973 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001974
1975 // Add the classes and namespaces associated with the parameter
1976 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00001977 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001978 }
1979 }
1980}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001981
1982/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1983/// an acceptable non-member overloaded operator for a call whose
1984/// arguments have types T1 (and, if non-empty, T2). This routine
1985/// implements the check in C++ [over.match.oper]p3b2 concerning
1986/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001987static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001988IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1989 QualType T1, QualType T2,
1990 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001991 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1992 return true;
1993
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001994 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1995 return true;
1996
John McCall183700f2009-09-21 23:43:11 +00001997 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001998 if (Proto->getNumArgs() < 1)
1999 return false;
2000
2001 if (T1->isEnumeralType()) {
2002 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002003 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002004 return true;
2005 }
2006
2007 if (Proto->getNumArgs() < 2)
2008 return false;
2009
2010 if (!T2.isNull() && T2->isEnumeralType()) {
2011 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002012 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002013 return true;
2014 }
2015
2016 return false;
2017}
2018
John McCall7d384dd2009-11-18 07:57:50 +00002019NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002020 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002021 LookupNameKind NameKind,
2022 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002023 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002024 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002025 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002026}
2027
Douglas Gregor6e378de2009-04-23 23:18:26 +00002028/// \brief Find the protocol with the given name, if any.
Douglas Gregorc83c6872010-04-15 22:33:43 +00002029ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2030 SourceLocation IdLoc) {
2031 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2032 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002033 return cast_or_null<ObjCProtocolDecl>(D);
2034}
2035
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002036void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002037 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002038 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002039 // C++ [over.match.oper]p3:
2040 // -- The set of non-member candidates is the result of the
2041 // unqualified lookup of operator@ in the context of the
2042 // expression according to the usual rules for name lookup in
2043 // unqualified function calls (3.4.2) except that all member
2044 // functions are ignored. However, if no operand has a class
2045 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002046 // that have a first parameter of type T1 or "reference to
2047 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002048 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002049 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002050 // when T2 is an enumeration type, are candidate functions.
2051 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002052 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2053 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002055 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2056
John McCallf36e02d2009-10-09 21:13:30 +00002057 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002058 return;
2059
2060 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2061 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002062 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2063 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002064 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002065 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002066 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002067 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002068 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002069 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002070 // later?
2071 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002072 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002073 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002074 }
2075}
2076
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002077/// \brief Look up the constructors for the given class.
2078DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +00002079 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002080 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2081 if (!Class->hasDeclaredDefaultConstructor())
2082 DeclareImplicitDefaultConstructor(Class);
2083 if (!Class->hasDeclaredCopyConstructor())
2084 DeclareImplicitCopyConstructor(Class);
2085 }
Douglas Gregor22584312010-07-02 23:41:54 +00002086
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002087 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2088 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2089 return Class->lookup(Name);
2090}
2091
Douglas Gregordb89f282010-07-01 22:47:18 +00002092/// \brief Look for the destructor of the given class.
2093///
2094/// During semantic analysis, this routine should be used in lieu of
2095/// CXXRecordDecl::getDestructor().
2096///
2097/// \returns The destructor for this class.
2098CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +00002099 // If the destructor has not yet been declared, do so now.
2100 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2101 !Class->hasDeclaredDestructor())
2102 DeclareImplicitDestructor(Class);
2103
Douglas Gregordb89f282010-07-01 22:47:18 +00002104 return Class->getDestructor();
2105}
2106
John McCall7edb5fd2010-01-26 07:16:45 +00002107void ADLResult::insert(NamedDecl *New) {
2108 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2109
2110 // If we haven't yet seen a decl for this key, or the last decl
2111 // was exactly this one, we're done.
2112 if (Old == 0 || Old == New) {
2113 Old = New;
2114 return;
2115 }
2116
2117 // Otherwise, decide which is a more recent redeclaration.
2118 FunctionDecl *OldFD, *NewFD;
2119 if (isa<FunctionTemplateDecl>(New)) {
2120 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2121 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2122 } else {
2123 OldFD = cast<FunctionDecl>(Old);
2124 NewFD = cast<FunctionDecl>(New);
2125 }
2126
2127 FunctionDecl *Cursor = NewFD;
2128 while (true) {
2129 Cursor = Cursor->getPreviousDeclaration();
2130
2131 // If we got to the end without finding OldFD, OldFD is the newer
2132 // declaration; leave things as they are.
2133 if (!Cursor) return;
2134
2135 // If we do find OldFD, then NewFD is newer.
2136 if (Cursor == OldFD) break;
2137
2138 // Otherwise, keep looking.
2139 }
2140
2141 Old = New;
2142}
2143
Sebastian Redl644be852009-10-23 19:23:15 +00002144void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002145 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00002146 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002147 // Find all of the associated namespaces and classes based on the
2148 // arguments we have.
2149 AssociatedNamespaceSet AssociatedNamespaces;
2150 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002151 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002152 AssociatedNamespaces,
2153 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002154
Sebastian Redl644be852009-10-23 19:23:15 +00002155 QualType T1, T2;
2156 if (Operator) {
2157 T1 = Args[0]->getType();
2158 if (NumArgs >= 2)
2159 T2 = Args[1]->getType();
2160 }
2161
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002162 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002163 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2164 // and let Y be the lookup set produced by argument dependent
2165 // lookup (defined as follows). If X contains [...] then Y is
2166 // empty. Otherwise Y is the set of declarations found in the
2167 // namespaces associated with the argument types as described
2168 // below. The set of declarations found by the lookup of the name
2169 // is the union of X and Y.
2170 //
2171 // Here, we compute Y and add its members to the overloaded
2172 // candidate set.
2173 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002174 NSEnd = AssociatedNamespaces.end();
2175 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002176 // When considering an associated namespace, the lookup is the
2177 // same as the lookup performed when the associated namespace is
2178 // used as a qualifier (3.4.3.2) except that:
2179 //
2180 // -- Any using-directives in the associated namespace are
2181 // ignored.
2182 //
John McCall6ff07852009-08-07 22:18:02 +00002183 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002184 // associated classes are visible within their respective
2185 // namespaces even if they are not visible during an ordinary
2186 // lookup (11.4).
2187 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002188 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002189 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002190 // If the only declaration here is an ordinary friend, consider
2191 // it only if it was declared in an associated classes.
2192 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002193 DeclContext *LexDC = D->getLexicalDeclContext();
2194 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2195 continue;
2196 }
Mike Stump1eb44332009-09-09 15:08:12 +00002197
John McCalla113e722010-01-26 06:04:06 +00002198 if (isa<UsingShadowDecl>(D))
2199 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002200
John McCalla113e722010-01-26 06:04:06 +00002201 if (isa<FunctionDecl>(D)) {
2202 if (Operator &&
2203 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2204 T1, T2, Context))
2205 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002206 } else if (!isa<FunctionTemplateDecl>(D))
2207 continue;
2208
2209 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002210 }
2211 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002212}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002213
2214//----------------------------------------------------------------------------
2215// Search for all visible declarations.
2216//----------------------------------------------------------------------------
2217VisibleDeclConsumer::~VisibleDeclConsumer() { }
2218
2219namespace {
2220
2221class ShadowContextRAII;
2222
2223class VisibleDeclsRecord {
2224public:
2225 /// \brief An entry in the shadow map, which is optimized to store a
2226 /// single declaration (the common case) but can also store a list
2227 /// of declarations.
2228 class ShadowMapEntry {
2229 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2230
2231 /// \brief Contains either the solitary NamedDecl * or a vector
2232 /// of declarations.
2233 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2234
2235 public:
2236 ShadowMapEntry() : DeclOrVector() { }
2237
2238 void Add(NamedDecl *ND);
2239 void Destroy();
2240
2241 // Iteration.
2242 typedef NamedDecl **iterator;
2243 iterator begin();
2244 iterator end();
2245 };
2246
2247private:
2248 /// \brief A mapping from declaration names to the declarations that have
2249 /// this name within a particular scope.
2250 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2251
2252 /// \brief A list of shadow maps, which is used to model name hiding.
2253 std::list<ShadowMap> ShadowMaps;
2254
2255 /// \brief The declaration contexts we have already visited.
2256 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2257
2258 friend class ShadowContextRAII;
2259
2260public:
2261 /// \brief Determine whether we have already visited this context
2262 /// (and, if not, note that we are going to visit that context now).
2263 bool visitedContext(DeclContext *Ctx) {
2264 return !VisitedContexts.insert(Ctx);
2265 }
2266
Douglas Gregor8071e422010-08-15 06:18:01 +00002267 bool alreadyVisitedContext(DeclContext *Ctx) {
2268 return VisitedContexts.count(Ctx);
2269 }
2270
Douglas Gregor546be3c2009-12-30 17:04:44 +00002271 /// \brief Determine whether the given declaration is hidden in the
2272 /// current scope.
2273 ///
2274 /// \returns the declaration that hides the given declaration, or
2275 /// NULL if no such declaration exists.
2276 NamedDecl *checkHidden(NamedDecl *ND);
2277
2278 /// \brief Add a declaration to the current shadow map.
2279 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2280};
2281
2282/// \brief RAII object that records when we've entered a shadow context.
2283class ShadowContextRAII {
2284 VisibleDeclsRecord &Visible;
2285
2286 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2287
2288public:
2289 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2290 Visible.ShadowMaps.push_back(ShadowMap());
2291 }
2292
2293 ~ShadowContextRAII() {
2294 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2295 EEnd = Visible.ShadowMaps.back().end();
2296 E != EEnd;
2297 ++E)
2298 E->second.Destroy();
2299
2300 Visible.ShadowMaps.pop_back();
2301 }
2302};
2303
2304} // end anonymous namespace
2305
2306void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2307 if (DeclOrVector.isNull()) {
2308 // 0 - > 1 elements: just set the single element information.
2309 DeclOrVector = ND;
2310 return;
2311 }
2312
2313 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2314 // 1 -> 2 elements: create the vector of results and push in the
2315 // existing declaration.
2316 DeclVector *Vec = new DeclVector;
2317 Vec->push_back(PrevND);
2318 DeclOrVector = Vec;
2319 }
2320
2321 // Add the new element to the end of the vector.
2322 DeclOrVector.get<DeclVector*>()->push_back(ND);
2323}
2324
2325void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2326 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2327 delete Vec;
2328 DeclOrVector = ((NamedDecl *)0);
2329 }
2330}
2331
2332VisibleDeclsRecord::ShadowMapEntry::iterator
2333VisibleDeclsRecord::ShadowMapEntry::begin() {
2334 if (DeclOrVector.isNull())
2335 return 0;
2336
2337 if (DeclOrVector.dyn_cast<NamedDecl *>())
2338 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2339
2340 return DeclOrVector.get<DeclVector *>()->begin();
2341}
2342
2343VisibleDeclsRecord::ShadowMapEntry::iterator
2344VisibleDeclsRecord::ShadowMapEntry::end() {
2345 if (DeclOrVector.isNull())
2346 return 0;
2347
2348 if (DeclOrVector.dyn_cast<NamedDecl *>())
2349 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2350
2351 return DeclOrVector.get<DeclVector *>()->end();
2352}
2353
2354NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002355 // Look through using declarations.
2356 ND = ND->getUnderlyingDecl();
2357
Douglas Gregor546be3c2009-12-30 17:04:44 +00002358 unsigned IDNS = ND->getIdentifierNamespace();
2359 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2360 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2361 SM != SMEnd; ++SM) {
2362 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2363 if (Pos == SM->end())
2364 continue;
2365
2366 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2367 IEnd = Pos->second.end();
2368 I != IEnd; ++I) {
2369 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002370 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor546be3c2009-12-30 17:04:44 +00002371 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2372 Decl::IDNS_ObjCProtocol)))
2373 continue;
2374
2375 // Protocols are in distinct namespaces from everything else.
2376 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2377 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2378 (*I)->getIdentifierNamespace() != IDNS)
2379 continue;
2380
Douglas Gregor0cc84042010-01-14 15:47:35 +00002381 // Functions and function templates in the same scope overload
2382 // rather than hide. FIXME: Look for hiding based on function
2383 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002384 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002385 ND->isFunctionOrFunctionTemplate() &&
2386 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002387 continue;
2388
Douglas Gregor546be3c2009-12-30 17:04:44 +00002389 // We've found a declaration that hides this one.
2390 return *I;
2391 }
2392 }
2393
2394 return 0;
2395}
2396
2397static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2398 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002399 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002400 VisibleDeclConsumer &Consumer,
2401 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002402 if (!Ctx)
2403 return;
2404
Douglas Gregor546be3c2009-12-30 17:04:44 +00002405 // Make sure we don't visit the same context twice.
2406 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2407 return;
2408
Douglas Gregor4923aa22010-07-02 20:37:36 +00002409 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2410 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2411
Douglas Gregor546be3c2009-12-30 17:04:44 +00002412 // Enumerate all of the results in this context.
2413 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2414 CurCtx = CurCtx->getNextContext()) {
2415 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2416 DEnd = CurCtx->decls_end();
2417 D != DEnd; ++D) {
2418 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2419 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002420 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002421 Visited.add(ND);
2422 }
2423
2424 // Visit transparent contexts inside this context.
2425 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2426 if (InnerCtx->isTransparentContext())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002427 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002428 Consumer, Visited);
2429 }
2430 }
2431 }
2432
2433 // Traverse using directives for qualified name lookup.
2434 if (QualifiedNameLookup) {
2435 ShadowContextRAII Shadow(Visited);
2436 DeclContext::udir_iterator I, E;
2437 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2438 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002439 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002440 }
2441 }
2442
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002443 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002444 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002445 if (!Record->hasDefinition())
2446 return;
2447
Douglas Gregor546be3c2009-12-30 17:04:44 +00002448 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2449 BEnd = Record->bases_end();
2450 B != BEnd; ++B) {
2451 QualType BaseType = B->getType();
2452
2453 // Don't look into dependent bases, because name lookup can't look
2454 // there anyway.
2455 if (BaseType->isDependentType())
2456 continue;
2457
2458 const RecordType *Record = BaseType->getAs<RecordType>();
2459 if (!Record)
2460 continue;
2461
2462 // FIXME: It would be nice to be able to determine whether referencing
2463 // a particular member would be ambiguous. For example, given
2464 //
2465 // struct A { int member; };
2466 // struct B { int member; };
2467 // struct C : A, B { };
2468 //
2469 // void f(C *c) { c->### }
2470 //
2471 // accessing 'member' would result in an ambiguity. However, we
2472 // could be smart enough to qualify the member with the base
2473 // class, e.g.,
2474 //
2475 // c->B::member
2476 //
2477 // or
2478 //
2479 // c->A::member
2480
2481 // Find results in this base class (and its bases).
2482 ShadowContextRAII Shadow(Visited);
2483 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002484 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002485 }
2486 }
2487
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002488 // Traverse the contexts of Objective-C classes.
2489 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2490 // Traverse categories.
2491 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2492 Category; Category = Category->getNextClassCategory()) {
2493 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002494 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2495 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002496 }
2497
2498 // Traverse protocols.
2499 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2500 E = IFace->protocol_end(); I != E; ++I) {
2501 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002502 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2503 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002504 }
2505
2506 // Traverse the superclass.
2507 if (IFace->getSuperClass()) {
2508 ShadowContextRAII Shadow(Visited);
2509 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002510 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002511 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002512
2513 // If there is an implementation, traverse it. We do this to find
2514 // synthesized ivars.
2515 if (IFace->getImplementation()) {
2516 ShadowContextRAII Shadow(Visited);
2517 LookupVisibleDecls(IFace->getImplementation(), Result,
2518 QualifiedNameLookup, true, Consumer, Visited);
2519 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002520 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2521 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2522 E = Protocol->protocol_end(); I != E; ++I) {
2523 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002524 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2525 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002526 }
2527 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2528 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2529 E = Category->protocol_end(); I != E; ++I) {
2530 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002531 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2532 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002533 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002534
2535 // If there is an implementation, traverse it.
2536 if (Category->getImplementation()) {
2537 ShadowContextRAII Shadow(Visited);
2538 LookupVisibleDecls(Category->getImplementation(), Result,
2539 QualifiedNameLookup, true, Consumer, Visited);
2540 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002541 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002542}
2543
2544static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2545 UnqualUsingDirectiveSet &UDirs,
2546 VisibleDeclConsumer &Consumer,
2547 VisibleDeclsRecord &Visited) {
2548 if (!S)
2549 return;
2550
Douglas Gregor8071e422010-08-15 06:18:01 +00002551 if (!S->getEntity() ||
2552 (!S->getParent() &&
2553 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002554 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2555 // Walk through the declarations in this Scope.
2556 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2557 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002558 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor539c5c32010-01-07 00:31:29 +00002559 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002560 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002561 Visited.add(ND);
2562 }
2563 }
2564 }
2565
Douglas Gregor711be1e2010-03-15 14:33:29 +00002566 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002567 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002568 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002569 // Look into this scope's declaration context, along with any of its
2570 // parent lookup contexts (e.g., enclosing classes), up to the point
2571 // where we hit the context stored in the next outer scope.
2572 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002573 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor546be3c2009-12-30 17:04:44 +00002574
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002575 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002576 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002577 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2578 if (Method->isInstanceMethod()) {
2579 // For instance methods, look for ivars in the method's interface.
2580 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2581 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor62021192010-02-04 23:42:48 +00002582 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2583 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2584 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002585 }
2586
2587 // We've already performed all of the name lookup that we need
2588 // to for Objective-C methods; the next context will be the
2589 // outer scope.
2590 break;
2591 }
2592
Douglas Gregor546be3c2009-12-30 17:04:44 +00002593 if (Ctx->isFunctionOrMethod())
2594 continue;
2595
2596 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002597 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002598 }
2599 } else if (!S->getParent()) {
2600 // Look into the translation unit scope. We walk through the translation
2601 // unit's declaration context, because the Scope itself won't have all of
2602 // the declarations if we loaded a precompiled header.
2603 // FIXME: We would like the translation unit's Scope object to point to the
2604 // translation unit, so we don't need this special "if" branch. However,
2605 // doing so would force the normal C++ name-lookup code to look into the
2606 // translation unit decl when the IdentifierInfo chains would suffice.
2607 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002608 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002609 Entity = Result.getSema().Context.getTranslationUnitDecl();
2610 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002611 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002612 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002613
2614 if (Entity) {
2615 // Lookup visible declarations in any namespaces found by using
2616 // directives.
2617 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2618 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2619 for (; UI != UEnd; ++UI)
2620 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002621 Result, /*QualifiedNameLookup=*/false,
2622 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002623 }
2624
2625 // Lookup names in the parent scope.
2626 ShadowContextRAII Shadow(Visited);
2627 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2628}
2629
2630void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002631 VisibleDeclConsumer &Consumer,
2632 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002633 // Determine the set of using directives available during
2634 // unqualified name lookup.
2635 Scope *Initial = S;
2636 UnqualUsingDirectiveSet UDirs;
2637 if (getLangOptions().CPlusPlus) {
2638 // Find the first namespace or translation-unit scope.
2639 while (S && !isNamespaceOrTranslationUnitScope(S))
2640 S = S->getParent();
2641
2642 UDirs.visitScopeChain(Initial, S);
2643 }
2644 UDirs.done();
2645
2646 // Look for visible declarations.
2647 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2648 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002649 if (!IncludeGlobalScope)
2650 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002651 ShadowContextRAII Shadow(Visited);
2652 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2653}
2654
2655void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002656 VisibleDeclConsumer &Consumer,
2657 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002658 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2659 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002660 if (!IncludeGlobalScope)
2661 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002662 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002663 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2664 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002665}
2666
2667//----------------------------------------------------------------------------
2668// Typo correction
2669//----------------------------------------------------------------------------
2670
2671namespace {
2672class TypoCorrectionConsumer : public VisibleDeclConsumer {
2673 /// \brief The name written that is a typo in the source.
2674 llvm::StringRef Typo;
2675
2676 /// \brief The results found that have the smallest edit distance
2677 /// found (so far) with the typo name.
2678 llvm::SmallVector<NamedDecl *, 4> BestResults;
2679
Douglas Gregoraaf87162010-04-14 20:04:41 +00002680 /// \brief The keywords that have the smallest edit distance.
2681 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2682
Douglas Gregor546be3c2009-12-30 17:04:44 +00002683 /// \brief The best edit distance found so far.
2684 unsigned BestEditDistance;
2685
2686public:
2687 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2688 : Typo(Typo->getName()) { }
2689
Douglas Gregor0cc84042010-01-14 15:47:35 +00002690 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002691 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002692
2693 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2694 iterator begin() const { return BestResults.begin(); }
2695 iterator end() const { return BestResults.end(); }
Douglas Gregoraaf87162010-04-14 20:04:41 +00002696 void clear_decls() { BestResults.clear(); }
2697
2698 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002699
Douglas Gregoraaf87162010-04-14 20:04:41 +00002700 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2701 keyword_iterator;
2702 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2703 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2704 bool keyword_empty() const { return BestKeywords.empty(); }
2705 unsigned keyword_size() const { return BestKeywords.size(); }
2706
2707 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002708};
2709
2710}
2711
Douglas Gregor0cc84042010-01-14 15:47:35 +00002712void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2713 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002714 // Don't consider hidden names for typo correction.
2715 if (Hiding)
2716 return;
2717
2718 // Only consider entities with identifiers for names, ignoring
2719 // special names (constructors, overloaded operators, selectors,
2720 // etc.).
2721 IdentifierInfo *Name = ND->getIdentifier();
2722 if (!Name)
2723 return;
2724
2725 // Compute the edit distance between the typo and the name of this
2726 // entity. If this edit distance is not worse than the best edit
2727 // distance we've seen so far, add it to the list of results.
2728 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregoraaf87162010-04-14 20:04:41 +00002729 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002730 if (ED < BestEditDistance) {
2731 // This result is better than any we've seen before; clear out
2732 // the previous results.
2733 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002734 BestKeywords.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002735 BestEditDistance = ED;
2736 } else if (ED > BestEditDistance) {
2737 // This result is worse than the best results we've seen so far;
2738 // ignore it.
2739 return;
2740 }
2741 } else
2742 BestEditDistance = ED;
2743
2744 BestResults.push_back(ND);
2745}
2746
Douglas Gregoraaf87162010-04-14 20:04:41 +00002747void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2748 llvm::StringRef Keyword) {
2749 // Compute the edit distance between the typo and this keyword.
2750 // If this edit distance is not worse than the best edit
2751 // distance we've seen so far, add it to the list of results.
2752 unsigned ED = Typo.edit_distance(Keyword);
2753 if (!BestResults.empty() || !BestKeywords.empty()) {
2754 if (ED < BestEditDistance) {
2755 BestResults.clear();
2756 BestKeywords.clear();
2757 BestEditDistance = ED;
2758 } else if (ED > BestEditDistance) {
2759 // This result is worse than the best results we've seen so far;
2760 // ignore it.
2761 return;
2762 }
2763 } else
2764 BestEditDistance = ED;
2765
2766 BestKeywords.push_back(&Context.Idents.get(Keyword));
2767}
2768
Douglas Gregor546be3c2009-12-30 17:04:44 +00002769/// \brief Try to "correct" a typo in the source code by finding
2770/// visible declarations whose names are similar to the name that was
2771/// present in the source code.
2772///
2773/// \param Res the \c LookupResult structure that contains the name
2774/// that was present in the source code along with the name-lookup
2775/// criteria used to search for the name. On success, this structure
2776/// will contain the results of name lookup.
2777///
2778/// \param S the scope in which name lookup occurs.
2779///
2780/// \param SS the nested-name-specifier that precedes the name we're
2781/// looking for, if present.
2782///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002783/// \param MemberContext if non-NULL, the context in which to look for
2784/// a member access expression.
2785///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002786/// \param EnteringContext whether we're entering the context described by
2787/// the nested-name-specifier SS.
2788///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002789/// \param CTC The context in which typo correction occurs, which impacts the
2790/// set of keywords permitted.
2791///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002792/// \param OPT when non-NULL, the search for visible declarations will
2793/// also walk the protocols in the qualified interfaces of \p OPT.
2794///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002795/// \returns the corrected name if the typo was corrected, otherwise returns an
2796/// empty \c DeclarationName. When a typo was corrected, the result structure
2797/// may contain the results of name lookup for the correct name or it may be
2798/// empty.
2799DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002800 DeclContext *MemberContext,
2801 bool EnteringContext,
2802 CorrectTypoContext CTC,
2803 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00002804 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002805 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002806
2807 // Provide a stop gap for files that are just seriously broken. Trying
2808 // to correct all typos can turn into a HUGE performance penalty, causing
2809 // some files to take minutes to get rejected by the parser.
2810 // FIXME: Is this the right solution?
2811 if (TyposCorrected == 20)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002812 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002813 ++TyposCorrected;
Ted Kremenek1dac3412010-01-06 00:23:04 +00002814
Douglas Gregor546be3c2009-12-30 17:04:44 +00002815 // We only attempt to correct typos for identifiers.
2816 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2817 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002818 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002819
2820 // If the scope specifier itself was invalid, don't try to correct
2821 // typos.
2822 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002823 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002824
2825 // Never try to correct typos during template deduction or
2826 // instantiation.
2827 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002828 return DeclarationName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002829
Douglas Gregor546be3c2009-12-30 17:04:44 +00002830 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002831
2832 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002833 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002834 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002835
2836 // Look in qualified interfaces.
2837 if (OPT) {
2838 for (ObjCObjectPointerType::qual_iterator
2839 I = OPT->qual_begin(), E = OPT->qual_end();
2840 I != E; ++I)
2841 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2842 }
2843 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002844 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2845 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002846 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002847
2848 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2849 } else {
2850 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2851 }
2852
Douglas Gregoraaf87162010-04-14 20:04:41 +00002853 // Add context-dependent keywords.
2854 bool WantTypeSpecifiers = false;
2855 bool WantExpressionKeywords = false;
2856 bool WantCXXNamedCasts = false;
2857 bool WantRemainingKeywords = false;
2858 switch (CTC) {
2859 case CTC_Unknown:
2860 WantTypeSpecifiers = true;
2861 WantExpressionKeywords = true;
2862 WantCXXNamedCasts = true;
2863 WantRemainingKeywords = true;
Douglas Gregor91f7ac72010-05-18 16:14:23 +00002864
2865 if (ObjCMethodDecl *Method = getCurMethodDecl())
2866 if (Method->getClassInterface() &&
2867 Method->getClassInterface()->getSuperClass())
2868 Consumer.addKeywordResult(Context, "super");
2869
Douglas Gregoraaf87162010-04-14 20:04:41 +00002870 break;
2871
2872 case CTC_NoKeywords:
2873 break;
2874
2875 case CTC_Type:
2876 WantTypeSpecifiers = true;
2877 break;
2878
2879 case CTC_ObjCMessageReceiver:
2880 Consumer.addKeywordResult(Context, "super");
2881 // Fall through to handle message receivers like expressions.
2882
2883 case CTC_Expression:
2884 if (getLangOptions().CPlusPlus)
2885 WantTypeSpecifiers = true;
2886 WantExpressionKeywords = true;
2887 // Fall through to get C++ named casts.
2888
2889 case CTC_CXXCasts:
2890 WantCXXNamedCasts = true;
2891 break;
2892
2893 case CTC_MemberLookup:
2894 if (getLangOptions().CPlusPlus)
2895 Consumer.addKeywordResult(Context, "template");
2896 break;
2897 }
2898
2899 if (WantTypeSpecifiers) {
2900 // Add type-specifier keywords to the set of results.
2901 const char *CTypeSpecs[] = {
2902 "char", "const", "double", "enum", "float", "int", "long", "short",
2903 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2904 "_Complex", "_Imaginary",
2905 // storage-specifiers as well
2906 "extern", "inline", "static", "typedef"
2907 };
2908
2909 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2910 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2911 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2912
2913 if (getLangOptions().C99)
2914 Consumer.addKeywordResult(Context, "restrict");
2915 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2916 Consumer.addKeywordResult(Context, "bool");
2917
2918 if (getLangOptions().CPlusPlus) {
2919 Consumer.addKeywordResult(Context, "class");
2920 Consumer.addKeywordResult(Context, "typename");
2921 Consumer.addKeywordResult(Context, "wchar_t");
2922
2923 if (getLangOptions().CPlusPlus0x) {
2924 Consumer.addKeywordResult(Context, "char16_t");
2925 Consumer.addKeywordResult(Context, "char32_t");
2926 Consumer.addKeywordResult(Context, "constexpr");
2927 Consumer.addKeywordResult(Context, "decltype");
2928 Consumer.addKeywordResult(Context, "thread_local");
2929 }
2930 }
2931
2932 if (getLangOptions().GNUMode)
2933 Consumer.addKeywordResult(Context, "typeof");
2934 }
2935
Douglas Gregord0785ea2010-05-18 16:30:22 +00002936 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00002937 Consumer.addKeywordResult(Context, "const_cast");
2938 Consumer.addKeywordResult(Context, "dynamic_cast");
2939 Consumer.addKeywordResult(Context, "reinterpret_cast");
2940 Consumer.addKeywordResult(Context, "static_cast");
2941 }
2942
2943 if (WantExpressionKeywords) {
2944 Consumer.addKeywordResult(Context, "sizeof");
2945 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2946 Consumer.addKeywordResult(Context, "false");
2947 Consumer.addKeywordResult(Context, "true");
2948 }
2949
2950 if (getLangOptions().CPlusPlus) {
2951 const char *CXXExprs[] = {
2952 "delete", "new", "operator", "throw", "typeid"
2953 };
2954 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2955 for (unsigned I = 0; I != NumCXXExprs; ++I)
2956 Consumer.addKeywordResult(Context, CXXExprs[I]);
2957
2958 if (isa<CXXMethodDecl>(CurContext) &&
2959 cast<CXXMethodDecl>(CurContext)->isInstance())
2960 Consumer.addKeywordResult(Context, "this");
2961
2962 if (getLangOptions().CPlusPlus0x) {
2963 Consumer.addKeywordResult(Context, "alignof");
2964 Consumer.addKeywordResult(Context, "nullptr");
2965 }
2966 }
2967 }
2968
2969 if (WantRemainingKeywords) {
2970 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2971 // Statements.
2972 const char *CStmts[] = {
2973 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2974 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2975 for (unsigned I = 0; I != NumCStmts; ++I)
2976 Consumer.addKeywordResult(Context, CStmts[I]);
2977
2978 if (getLangOptions().CPlusPlus) {
2979 Consumer.addKeywordResult(Context, "catch");
2980 Consumer.addKeywordResult(Context, "try");
2981 }
2982
2983 if (S && S->getBreakParent())
2984 Consumer.addKeywordResult(Context, "break");
2985
2986 if (S && S->getContinueParent())
2987 Consumer.addKeywordResult(Context, "continue");
2988
2989 if (!getSwitchStack().empty()) {
2990 Consumer.addKeywordResult(Context, "case");
2991 Consumer.addKeywordResult(Context, "default");
2992 }
2993 } else {
2994 if (getLangOptions().CPlusPlus) {
2995 Consumer.addKeywordResult(Context, "namespace");
2996 Consumer.addKeywordResult(Context, "template");
2997 }
2998
2999 if (S && S->isClassScope()) {
3000 Consumer.addKeywordResult(Context, "explicit");
3001 Consumer.addKeywordResult(Context, "friend");
3002 Consumer.addKeywordResult(Context, "mutable");
3003 Consumer.addKeywordResult(Context, "private");
3004 Consumer.addKeywordResult(Context, "protected");
3005 Consumer.addKeywordResult(Context, "public");
3006 Consumer.addKeywordResult(Context, "virtual");
3007 }
3008 }
3009
3010 if (getLangOptions().CPlusPlus) {
3011 Consumer.addKeywordResult(Context, "using");
3012
3013 if (getLangOptions().CPlusPlus0x)
3014 Consumer.addKeywordResult(Context, "static_assert");
3015 }
3016 }
3017
3018 // If we haven't found anything, we're done.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003019 if (Consumer.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003020 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003021
3022 // Only allow a single, closest name in the result set (it's okay to
3023 // have overloads of that name, though).
Douglas Gregoraaf87162010-04-14 20:04:41 +00003024 DeclarationName BestName;
3025 NamedDecl *BestIvarOrPropertyDecl = 0;
3026 bool FoundIvarOrPropertyDecl = false;
3027
3028 // Check all of the declaration results to find the best name so far.
3029 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3030 IEnd = Consumer.end();
3031 I != IEnd; ++I) {
3032 if (!BestName)
3033 BestName = (*I)->getDeclName();
3034 else if (BestName != (*I)->getDeclName())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003035 return DeclarationName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003036
Douglas Gregoraaf87162010-04-14 20:04:41 +00003037 // \brief Keep track of either an Objective-C ivar or a property, but not
3038 // both.
3039 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
3040 if (FoundIvarOrPropertyDecl)
3041 BestIvarOrPropertyDecl = 0;
3042 else {
3043 BestIvarOrPropertyDecl = *I;
3044 FoundIvarOrPropertyDecl = true;
3045 }
3046 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003047 }
3048
Douglas Gregoraaf87162010-04-14 20:04:41 +00003049 // Now check all of the keyword results to find the best name.
3050 switch (Consumer.keyword_size()) {
3051 case 0:
3052 // No keywords matched.
3053 break;
3054
3055 case 1:
3056 // If we already have a name
3057 if (!BestName) {
3058 // We did not have anything previously,
3059 BestName = *Consumer.keyword_begin();
3060 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
3061 // We have a declaration with the same name as a context-sensitive
3062 // keyword. The keyword takes precedence.
3063 BestIvarOrPropertyDecl = 0;
3064 FoundIvarOrPropertyDecl = false;
3065 Consumer.clear_decls();
Douglas Gregord0785ea2010-05-18 16:30:22 +00003066 } else if (CTC == CTC_ObjCMessageReceiver &&
3067 (*Consumer.keyword_begin())->isStr("super")) {
3068 // In an Objective-C message send, give the "super" keyword a slight
3069 // edge over entities not in function or method scope.
3070 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3071 IEnd = Consumer.end();
3072 I != IEnd; ++I) {
3073 if ((*I)->getDeclName() == BestName) {
3074 if ((*I)->getDeclContext()->isFunctionOrMethod())
3075 return DeclarationName();
3076 }
3077 }
3078
3079 // Everything found was outside a function or method; the 'super'
3080 // keyword takes precedence.
3081 BestIvarOrPropertyDecl = 0;
3082 FoundIvarOrPropertyDecl = false;
3083 Consumer.clear_decls();
3084 BestName = *Consumer.keyword_begin();
Douglas Gregoraaf87162010-04-14 20:04:41 +00003085 } else {
3086 // Name collision; we will not correct typos.
3087 return DeclarationName();
3088 }
3089 break;
3090
3091 default:
3092 // Name collision; we will not correct typos.
3093 return DeclarationName();
3094 }
3095
Douglas Gregor546be3c2009-12-30 17:04:44 +00003096 // BestName is the closest viable name to what the user
3097 // typed. However, to make sure that we don't pick something that's
3098 // way off, make sure that the user typed at least 3 characters for
3099 // each correction.
3100 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregoraaf87162010-04-14 20:04:41 +00003101 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
3102 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregor931f98a2010-04-14 17:09:22 +00003103 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003104
3105 // Perform name lookup again with the name we chose, and declare
3106 // success if we found something that was not ambiguous.
3107 Res.clear();
3108 Res.setLookupName(BestName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003109
3110 // If we found an ivar or property, add that result; no further
3111 // lookup is required.
Douglas Gregoraaf87162010-04-14 20:04:41 +00003112 if (BestIvarOrPropertyDecl)
3113 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003114 // If we're looking into the context of a member, perform qualified
3115 // name lookup on the best name.
Douglas Gregoraaf87162010-04-14 20:04:41 +00003116 else if (!Consumer.keyword_empty()) {
3117 // The best match was a keyword. Return it.
3118 return BestName;
3119 } else if (MemberContext)
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003120 LookupQualifiedName(Res, MemberContext);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003121 // Perform lookup as if we had just parsed the best name.
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003122 else
3123 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3124 EnteringContext);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003125
3126 if (Res.isAmbiguous()) {
3127 Res.suppressDiagnostics();
Douglas Gregor931f98a2010-04-14 17:09:22 +00003128 return DeclarationName();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003129 }
3130
Douglas Gregor931f98a2010-04-14 17:09:22 +00003131 if (Res.getResultKind() != LookupResult::NotFound)
3132 return BestName;
3133
3134 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003135}