blob: 6cd0207c80050184100841fa07f78a312a3c546e [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"
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
John McCall19510852010-08-20 18:27:03 +000017#include "clang/Sema/DeclSpec.h"
John McCall5f1e0942010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall2a7fb272010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000023#include "clang/AST/Decl.h"
24#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000026#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000027#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000028#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000030#include "clang/Basic/LangOptions.h"
John McCall50df6ae2010-08-25 07:03:20 +000031#include "llvm/ADT/DenseSet.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000034#include "llvm/ADT/StringMap.h"
John McCall6e247262009-10-10 05:48:19 +000035#include "llvm/Support/ErrorHandling.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000036#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000037#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000038#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000039#include <vector>
40#include <iterator>
41#include <utility>
42#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000043
44using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000045using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000046
John McCalld7be78a2009-11-10 07:01:13 +000047namespace {
48 class UnqualUsingEntry {
49 const DeclContext *Nominated;
50 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000051
John McCalld7be78a2009-11-10 07:01:13 +000052 public:
53 UnqualUsingEntry(const DeclContext *Nominated,
54 const DeclContext *CommonAncestor)
55 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
56 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000057
John McCalld7be78a2009-11-10 07:01:13 +000058 const DeclContext *getCommonAncestor() const {
59 return CommonAncestor;
60 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000061
John McCalld7be78a2009-11-10 07:01:13 +000062 const DeclContext *getNominatedNamespace() const {
63 return Nominated;
64 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000065
John McCalld7be78a2009-11-10 07:01:13 +000066 // Sort by the pointer value of the common ancestor.
67 struct Comparator {
68 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
69 return L.getCommonAncestor() < R.getCommonAncestor();
70 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000071
John McCalld7be78a2009-11-10 07:01:13 +000072 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
73 return E.getCommonAncestor() < DC;
74 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000075
John McCalld7be78a2009-11-10 07:01:13 +000076 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
77 return DC < E.getCommonAncestor();
78 }
79 };
80 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000081
John McCalld7be78a2009-11-10 07:01:13 +000082 /// A collection of using directives, as used by C++ unqualified
83 /// lookup.
84 class UnqualUsingDirectiveSet {
85 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000086
John McCalld7be78a2009-11-10 07:01:13 +000087 ListTy list;
88 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000089
John McCalld7be78a2009-11-10 07:01:13 +000090 public:
91 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000092
John McCalld7be78a2009-11-10 07:01:13 +000093 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
94 // C++ [namespace.udir]p1:
95 // During unqualified name lookup, the names appear as if they
96 // were declared in the nearest enclosing namespace which contains
97 // both the using-directive and the nominated namespace.
98 DeclContext *InnermostFileDC
99 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
100 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000101
John McCalld7be78a2009-11-10 07:01:13 +0000102 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +0000103 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
104 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
105 visit(Ctx, EffectiveDC);
106 } else {
107 Scope::udir_iterator I = S->using_directives_begin(),
108 End = S->using_directives_end();
109
110 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000111 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000112 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000113 }
114 }
John McCalld7be78a2009-11-10 07:01:13 +0000115
116 // Visits a context and collect all of its using directives
117 // recursively. Treats all using directives as if they were
118 // declared in the context.
119 //
120 // A given context is only every visited once, so it is important
121 // that contexts be visited from the inside out in order to get
122 // the effective DCs right.
123 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
124 if (!visited.insert(DC))
125 return;
126
127 addUsingDirectives(DC, EffectiveDC);
128 }
129
130 // Visits a using directive and collects all of its using
131 // directives recursively. Treats all using directives as if they
132 // were declared in the effective DC.
133 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
134 DeclContext *NS = UD->getNominatedNamespace();
135 if (!visited.insert(NS))
136 return;
137
138 addUsingDirective(UD, EffectiveDC);
139 addUsingDirectives(NS, EffectiveDC);
140 }
141
142 // Adds all the using directives in a context (and those nominated
143 // by its using directives, transitively) as if they appeared in
144 // the given effective context.
145 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
146 llvm::SmallVector<DeclContext*,4> queue;
147 while (true) {
148 DeclContext::udir_iterator I, End;
149 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
150 UsingDirectiveDecl *UD = *I;
151 DeclContext *NS = UD->getNominatedNamespace();
152 if (visited.insert(NS)) {
153 addUsingDirective(UD, EffectiveDC);
154 queue.push_back(NS);
155 }
156 }
157
158 if (queue.empty())
159 return;
160
161 DC = queue.back();
162 queue.pop_back();
163 }
164 }
165
166 // Add a using directive as if it had been declared in the given
167 // context. This helps implement C++ [namespace.udir]p3:
168 // The using-directive is transitive: if a scope contains a
169 // using-directive that nominates a second namespace that itself
170 // contains using-directives, the effect is as if the
171 // using-directives from the second namespace also appeared in
172 // the first.
173 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
174 // Find the common ancestor between the effective context and
175 // the nominated namespace.
176 DeclContext *Common = UD->getNominatedNamespace();
177 while (!Common->Encloses(EffectiveDC))
178 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000179 Common = Common->getPrimaryContext();
John McCalld7be78a2009-11-10 07:01:13 +0000180
181 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
182 }
183
184 void done() {
185 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
186 }
187
John McCalld7be78a2009-11-10 07:01:13 +0000188 typedef ListTy::const_iterator const_iterator;
189
John McCalld7be78a2009-11-10 07:01:13 +0000190 const_iterator begin() const { return list.begin(); }
191 const_iterator end() const { return list.end(); }
192
193 std::pair<const_iterator,const_iterator>
194 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000195 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000196 UnqualUsingEntry::Comparator());
197 }
198 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000199}
200
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000201// Retrieve the set of identifier namespaces that correspond to a
202// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000203static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
204 bool CPlusPlus,
205 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000206 unsigned IDNS = 0;
207 switch (NameKind) {
208 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000209 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000210 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000211 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000212 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCall1d7c5282009-12-18 10:40:03 +0000213 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
214 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000215 break;
216
John McCall76d32642010-04-24 01:30:58 +0000217 case Sema::LookupOperatorName:
218 // Operator lookup is its own crazy thing; it is not the same
219 // as (e.g.) looking up an operator name for redeclaration.
220 assert(!Redeclaration && "cannot do redeclaration operator lookup");
221 IDNS = Decl::IDNS_NonMemberOperator;
222 break;
223
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000224 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000225 if (CPlusPlus) {
226 IDNS = Decl::IDNS_Type;
227
228 // When looking for a redeclaration of a tag name, we add:
229 // 1) TagFriend to find undeclared friend decls
230 // 2) Namespace because they can't "overload" with tag decls.
231 // 3) Tag because it includes class templates, which can't
232 // "overload" with tag decls.
233 if (Redeclaration)
234 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
235 } else {
236 IDNS = Decl::IDNS_Tag;
237 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000238 break;
239
240 case Sema::LookupMemberName:
241 IDNS = Decl::IDNS_Member;
242 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000244 break;
245
246 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000247 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
248 break;
249
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000250 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000251 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000252 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000253
John McCall9f54ad42009-12-10 09:41:52 +0000254 case Sema::LookupUsingDeclName:
255 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
256 | Decl::IDNS_Member | Decl::IDNS_Using;
257 break;
258
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000259 case Sema::LookupObjCProtocolName:
260 IDNS = Decl::IDNS_ObjCProtocol;
261 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000262
263 case Sema::LookupAnyName:
264 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
265 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
266 | Decl::IDNS_Type;
267 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000268 }
269 return IDNS;
270}
271
John McCall1d7c5282009-12-18 10:40:03 +0000272void LookupResult::configure() {
273 IDNS = getIDNS(LookupKind,
274 SemaRef.getLangOptions().CPlusPlus,
275 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000276
277 // If we're looking for one of the allocation or deallocation
278 // operators, make sure that the implicitly-declared new and delete
279 // operators can be found.
280 if (!isForRedeclaration()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000281 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000282 case OO_New:
283 case OO_Delete:
284 case OO_Array_New:
285 case OO_Array_Delete:
286 SemaRef.DeclareGlobalNewDelete();
287 break;
288
289 default:
290 break;
291 }
292 }
John McCall1d7c5282009-12-18 10:40:03 +0000293}
294
John McCall2a7fb272010-08-25 05:32:35 +0000295#ifndef NDEBUG
296void LookupResult::sanity() const {
297 assert(ResultKind != NotFound || Decls.size() == 0);
298 assert(ResultKind != Found || Decls.size() == 1);
299 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
300 (Decls.size() == 1 &&
301 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
302 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
303 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
304 (Decls.size() == 1 && Ambiguity == AmbiguousBaseSubobjects));
305 assert((Paths != NULL) == (ResultKind == Ambiguous &&
306 (Ambiguity == AmbiguousBaseSubobjectTypes ||
307 Ambiguity == AmbiguousBaseSubobjects)));
308}
309#endif
310
John McCallf36e02d2009-10-09 21:13:30 +0000311// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000312void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000313 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000314}
315
John McCall7453ed42009-11-22 00:44:51 +0000316/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000317void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000318 unsigned N = Decls.size();
John McCall9f54ad42009-12-10 09:41:52 +0000319
John McCallf36e02d2009-10-09 21:13:30 +0000320 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000321 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000322 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000323 return;
324 }
325
John McCall7453ed42009-11-22 00:44:51 +0000326 // If there's a single decl, we need to examine it to decide what
327 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000328 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000329 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
330 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000331 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000332 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000333 ResultKind = FoundUnresolvedValue;
334 return;
335 }
John McCallf36e02d2009-10-09 21:13:30 +0000336
John McCall6e247262009-10-10 05:48:19 +0000337 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000338 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000339
John McCallf36e02d2009-10-09 21:13:30 +0000340 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000341 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
342
John McCallf36e02d2009-10-09 21:13:30 +0000343 bool Ambiguous = false;
344 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000345 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000346
347 unsigned UniqueTagIndex = 0;
348
349 unsigned I = 0;
350 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000351 NamedDecl *D = Decls[I]->getUnderlyingDecl();
352 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000353
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000354 // Redeclarations of types via typedef can occur both within a scope
355 // and, through using declarations and directives, across scopes. There is
356 // no ambiguity if they all refer to the same type, so unique based on the
357 // canonical type.
358 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
359 if (!TD->getDeclContext()->isRecord()) {
360 QualType T = SemaRef.Context.getTypeDeclType(TD);
361 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
362 // The type is not unique; pull something off the back and continue
363 // at this index.
364 Decls[I] = Decls[--N];
365 continue;
366 }
367 }
368 }
369
John McCall314be4e2009-11-17 07:50:12 +0000370 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000371 // If it's not unique, pull something off the back (and
372 // continue at this index).
373 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000374 continue;
375 }
376
377 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000378
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000379 if (isa<UnresolvedUsingValueDecl>(D)) {
380 HasUnresolved = true;
381 } else if (isa<TagDecl>(D)) {
382 if (HasTag)
383 Ambiguous = true;
384 UniqueTagIndex = I;
385 HasTag = true;
386 } else if (isa<FunctionTemplateDecl>(D)) {
387 HasFunction = true;
388 HasFunctionTemplate = true;
389 } else if (isa<FunctionDecl>(D)) {
390 HasFunction = true;
391 } else {
392 if (HasNonFunction)
393 Ambiguous = true;
394 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000395 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000396 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000397 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000398
John McCallf36e02d2009-10-09 21:13:30 +0000399 // C++ [basic.scope.hiding]p2:
400 // A class name or enumeration name can be hidden by the name of
401 // an object, function, or enumerator declared in the same
402 // scope. If a class or enumeration name and an object, function,
403 // or enumerator are declared in the same scope (in any order)
404 // with the same name, the class or enumeration name is hidden
405 // wherever the object, function, or enumerator name is visible.
406 // But it's still an error if there are distinct tag types found,
407 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000408 if (HideTags && HasTag && !Ambiguous &&
409 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000410 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000411
John McCallf36e02d2009-10-09 21:13:30 +0000412 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000413
John McCallfda8e122009-12-03 00:58:24 +0000414 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000415 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000416
John McCallf36e02d2009-10-09 21:13:30 +0000417 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000418 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000419 else if (HasUnresolved)
420 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000421 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000422 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000423 else
John McCalla24dc2e2009-11-17 02:14:36 +0000424 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000425}
426
John McCall7d384dd2009-11-18 07:57:50 +0000427void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000428 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000429 DeclContext::lookup_iterator DI, DE;
430 for (I = P.begin(), E = P.end(); I != E; ++I)
431 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
432 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000433}
434
John McCall7d384dd2009-11-18 07:57:50 +0000435void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000436 Paths = new CXXBasePaths;
437 Paths->swap(P);
438 addDeclsFromBasePaths(*Paths);
439 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000440 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000441}
442
John McCall7d384dd2009-11-18 07:57:50 +0000443void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000444 Paths = new CXXBasePaths;
445 Paths->swap(P);
446 addDeclsFromBasePaths(*Paths);
447 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000448 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000449}
450
John McCall7d384dd2009-11-18 07:57:50 +0000451void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000452 Out << Decls.size() << " result(s)";
453 if (isAmbiguous()) Out << ", ambiguous";
454 if (Paths) Out << ", base paths present";
455
456 for (iterator I = begin(), E = end(); I != E; ++I) {
457 Out << "\n";
458 (*I)->print(Out, 2);
459 }
460}
461
Douglas Gregor85910982010-02-12 05:48:04 +0000462/// \brief Lookup a builtin function, when name lookup would otherwise
463/// fail.
464static bool LookupBuiltin(Sema &S, LookupResult &R) {
465 Sema::LookupNameKind NameKind = R.getLookupKind();
466
467 // If we didn't find a use of this identifier, and if the identifier
468 // corresponds to a compiler builtin, create the decl object for the builtin
469 // now, injecting it into translation unit scope, and return it.
470 if (NameKind == Sema::LookupOrdinaryName ||
471 NameKind == Sema::LookupRedeclarationWithLinkage) {
472 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
473 if (II) {
474 // If this is a builtin on this (or all) targets, create the decl.
475 if (unsigned BuiltinID = II->getBuiltinID()) {
476 // In C++, we don't have any predefined library functions like
477 // 'malloc'. Instead, we'll just error.
478 if (S.getLangOptions().CPlusPlus &&
479 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
480 return false;
481
482 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
483 S.TUScope, R.isForRedeclaration(),
484 R.getNameLoc());
485 if (D)
486 R.addDecl(D);
487 return (D != NULL);
488 }
489 }
490 }
491
492 return false;
493}
494
Douglas Gregor4923aa22010-07-02 20:37:36 +0000495/// \brief Determine whether we can declare a special member function within
496/// the class at this point.
497static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
498 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000499 // Don't do it if the class is invalid.
500 if (Class->isInvalidDecl())
501 return false;
502
Douglas Gregor4923aa22010-07-02 20:37:36 +0000503 // We need to have a definition for the class.
504 if (!Class->getDefinition() || Class->isDependentContext())
505 return false;
506
507 // We can't be in the middle of defining the class.
508 if (const RecordType *RecordTy
509 = Context.getTypeDeclType(Class)->getAs<RecordType>())
510 return !RecordTy->isBeingDefined();
511
512 return false;
513}
514
515void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000516 if (!CanDeclareSpecialMemberFunction(Context, Class))
517 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000518
519 // If the default constructor has not yet been declared, do so now.
520 if (!Class->hasDeclaredDefaultConstructor())
521 DeclareImplicitDefaultConstructor(Class);
Douglas Gregor22584312010-07-02 23:41:54 +0000522
523 // If the copy constructor has not yet been declared, do so now.
524 if (!Class->hasDeclaredCopyConstructor())
525 DeclareImplicitCopyConstructor(Class);
526
Douglas Gregora376d102010-07-02 21:50:04 +0000527 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000528 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000529 DeclareImplicitCopyAssignment(Class);
530
Douglas Gregor4923aa22010-07-02 20:37:36 +0000531 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000532 if (!Class->hasDeclaredDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +0000533 DeclareImplicitDestructor(Class);
534}
535
Douglas Gregora376d102010-07-02 21:50:04 +0000536/// \brief Determine whether this is the name of an implicitly-declared
537/// special member function.
538static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
539 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000540 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000541 case DeclarationName::CXXDestructorName:
542 return true;
543
544 case DeclarationName::CXXOperatorName:
545 return Name.getCXXOverloadedOperator() == OO_Equal;
546
547 default:
548 break;
549 }
550
551 return false;
552}
553
554/// \brief If there are any implicit member functions with the given name
555/// that need to be declared in the given declaration context, do so.
556static void DeclareImplicitMemberFunctionsWithName(Sema &S,
557 DeclarationName Name,
558 const DeclContext *DC) {
559 if (!DC)
560 return;
561
562 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000563 case DeclarationName::CXXConstructorName:
564 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000565 if (Record->getDefinition() &&
566 CanDeclareSpecialMemberFunction(S.Context, Record)) {
567 if (!Record->hasDeclaredDefaultConstructor())
568 S.DeclareImplicitDefaultConstructor(
569 const_cast<CXXRecordDecl *>(Record));
570 if (!Record->hasDeclaredCopyConstructor())
571 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
572 }
Douglas Gregor22584312010-07-02 23:41:54 +0000573 break;
574
Douglas Gregora376d102010-07-02 21:50:04 +0000575 case DeclarationName::CXXDestructorName:
576 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
577 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
578 CanDeclareSpecialMemberFunction(S.Context, Record))
579 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000580 break;
581
582 case DeclarationName::CXXOperatorName:
583 if (Name.getCXXOverloadedOperator() != OO_Equal)
584 break;
585
586 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
587 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
588 CanDeclareSpecialMemberFunction(S.Context, Record))
589 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
590 break;
591
592 default:
593 break;
594 }
595}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000596
John McCallf36e02d2009-10-09 21:13:30 +0000597// Adds all qualifying matches for a name within a decl context to the
598// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000599static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000600 bool Found = false;
601
Douglas Gregor4923aa22010-07-02 20:37:36 +0000602 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000603 if (S.getLangOptions().CPlusPlus)
604 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000605
606 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000607 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000608 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000609 NamedDecl *D = *I;
610 if (R.isAcceptableDecl(D)) {
611 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000612 Found = true;
613 }
614 }
John McCallf36e02d2009-10-09 21:13:30 +0000615
Douglas Gregor85910982010-02-12 05:48:04 +0000616 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
617 return true;
618
Douglas Gregor48026d22010-01-11 18:40:55 +0000619 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000620 != DeclarationName::CXXConversionFunctionName ||
621 R.getLookupName().getCXXNameType()->isDependentType() ||
622 !isa<CXXRecordDecl>(DC))
623 return Found;
624
625 // C++ [temp.mem]p6:
626 // A specialization of a conversion function template is not found by
627 // name lookup. Instead, any conversion function templates visible in the
628 // context of the use are considered. [...]
629 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
630 if (!Record->isDefinition())
631 return Found;
632
633 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
634 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
635 UEnd = Unresolved->end(); U != UEnd; ++U) {
636 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
637 if (!ConvTemplate)
638 continue;
639
640 // When we're performing lookup for the purposes of redeclaration, just
641 // add the conversion function template. When we deduce template
642 // arguments for specializations, we'll end up unifying the return
643 // type of the new declaration with the type of the function template.
644 if (R.isForRedeclaration()) {
645 R.addDecl(ConvTemplate);
646 Found = true;
647 continue;
648 }
649
Douglas Gregor48026d22010-01-11 18:40:55 +0000650 // C++ [temp.mem]p6:
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000651 // [...] For each such operator, if argument deduction succeeds
652 // (14.9.2.3), the resulting specialization is used as if found by
653 // name lookup.
654 //
655 // When referencing a conversion function for any purpose other than
656 // a redeclaration (such that we'll be building an expression with the
657 // result), perform template argument deduction and place the
658 // specialization into the result set. We do this to avoid forcing all
659 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000660 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000661 FunctionDecl *Specialization = 0;
662
663 const FunctionProtoType *ConvProto
664 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
665 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000666
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000667 // Compute the type of the function that we would expect the conversion
668 // function to have, if it were to match the name given.
669 // FIXME: Calling convention!
Rafael Espindola264ba482010-03-30 20:24:48 +0000670 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000671 QualType ExpectedType
672 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
673 0, 0, ConvProto->isVariadic(),
674 ConvProto->getTypeQuals(),
675 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000676 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000677
678 // Perform template argument deduction against the type that we would
679 // expect the function to have.
680 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
681 Specialization, Info)
682 == Sema::TDK_Success) {
683 R.addDecl(Specialization);
684 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000685 }
686 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000687
John McCallf36e02d2009-10-09 21:13:30 +0000688 return Found;
689}
690
John McCalld7be78a2009-11-10 07:01:13 +0000691// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000692static bool
Douglas Gregor85910982010-02-12 05:48:04 +0000693CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
694 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000695
696 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
697
John McCalld7be78a2009-11-10 07:01:13 +0000698 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000699 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000700
John McCalld7be78a2009-11-10 07:01:13 +0000701 // Perform direct name lookup into the namespaces nominated by the
702 // using directives whose common ancestor is this namespace.
703 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
704 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000705
John McCalld7be78a2009-11-10 07:01:13 +0000706 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000707 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000708 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000709
710 R.resolveKind();
711
712 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000713}
714
715static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000716 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000717 return Ctx->isFileContext();
718 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000719}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000720
Douglas Gregor711be1e2010-03-15 14:33:29 +0000721// Find the next outer declaration context from this scope. This
722// routine actually returns the semantic outer context, which may
723// differ from the lexical context (encoded directly in the Scope
724// stack) when we are parsing a member of a class template. In this
725// case, the second element of the pair will be true, to indicate that
726// name lookup should continue searching in this semantic context when
727// it leaves the current template parameter scope.
728static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
729 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
730 DeclContext *Lexical = 0;
731 for (Scope *OuterS = S->getParent(); OuterS;
732 OuterS = OuterS->getParent()) {
733 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000734 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000735 break;
736 }
737 }
738
739 // C++ [temp.local]p8:
740 // In the definition of a member of a class template that appears
741 // outside of the namespace containing the class template
742 // definition, the name of a template-parameter hides the name of
743 // a member of this namespace.
744 //
745 // Example:
746 //
747 // namespace N {
748 // class C { };
749 //
750 // template<class T> class B {
751 // void f(T);
752 // };
753 // }
754 //
755 // template<class C> void N::B<C>::f(C) {
756 // C b; // C is the template parameter, not N::C
757 // }
758 //
759 // In this example, the lexical context we return is the
760 // TranslationUnit, while the semantic context is the namespace N.
761 if (!Lexical || !DC || !S->getParent() ||
762 !S->getParent()->isTemplateParamScope())
763 return std::make_pair(Lexical, false);
764
765 // Find the outermost template parameter scope.
766 // For the example, this is the scope for the template parameters of
767 // template<class C>.
768 Scope *OutermostTemplateScope = S->getParent();
769 while (OutermostTemplateScope->getParent() &&
770 OutermostTemplateScope->getParent()->isTemplateParamScope())
771 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregore942bbe2009-09-10 16:57:35 +0000772
Douglas Gregor711be1e2010-03-15 14:33:29 +0000773 // Find the namespace context in which the original scope occurs. In
774 // the example, this is namespace N.
775 DeclContext *Semantic = DC;
776 while (!Semantic->isFileContext())
777 Semantic = Semantic->getParent();
778
779 // Find the declaration context just outside of the template
780 // parameter scope. This is the context in which the template is
781 // being lexically declaration (a namespace context). In the
782 // example, this is the global scope.
783 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
784 Lexical->Encloses(Semantic))
785 return std::make_pair(Semantic, true);
786
787 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000788}
789
John McCalla24dc2e2009-11-17 02:14:36 +0000790bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000791 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000792
793 DeclarationName Name = R.getLookupName();
794
Douglas Gregora376d102010-07-02 21:50:04 +0000795 // If this is the name of an implicitly-declared special member function,
796 // go through the scope stack to implicitly declare
797 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
798 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
799 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
800 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
801 }
802
803 // Implicitly declare member functions with the name we're looking for, if in
804 // fact we are in a scope where it matters.
805
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000806 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000807 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000808 I = IdResolver.begin(Name),
809 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000810
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000811 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000812 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000813 // ...During unqualified name lookup (3.4.1), the names appear as if
814 // they were declared in the nearest enclosing namespace which contains
815 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000816 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000817 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000818 //
819 // For example:
820 // namespace A { int i; }
821 // void foo() {
822 // int i;
823 // {
824 // using namespace A;
825 // ++i; // finds local 'i', A::i appears at global scope
826 // }
827 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000828 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000829 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000830 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000831 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
832
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000833 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000834 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000835 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000836 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000837 Found = true;
838 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000839 }
840 }
John McCallf36e02d2009-10-09 21:13:30 +0000841 if (Found) {
842 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000843 if (S->isClassScope())
844 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
845 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000846 return true;
847 }
848
Douglas Gregor711be1e2010-03-15 14:33:29 +0000849 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
850 S->getParent() && !S->getParent()->isTemplateParamScope()) {
851 // We've just searched the last template parameter scope and
852 // found nothing, so look into the the contexts between the
853 // lexical and semantic declaration contexts returned by
854 // findOuterContext(). This implements the name lookup behavior
855 // of C++ [temp.local]p8.
856 Ctx = OutsideOfTemplateParamDC;
857 OutsideOfTemplateParamDC = 0;
858 }
859
860 if (Ctx) {
861 DeclContext *OuterCtx;
862 bool SearchAfterTemplateScope;
863 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
864 if (SearchAfterTemplateScope)
865 OutsideOfTemplateParamDC = OuterCtx;
866
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000867 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000868 // We do not directly look into transparent contexts, since
869 // those entities will be found in the nearest enclosing
870 // non-transparent context.
871 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000872 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000873
874 // We do not look directly into function or method contexts,
875 // since all of the local variables and parameters of the
876 // function/method are present within the Scope.
877 if (Ctx->isFunctionOrMethod()) {
878 // If we have an Objective-C instance method, look for ivars
879 // in the corresponding interface.
880 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
881 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
882 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
883 ObjCInterfaceDecl *ClassDeclared;
884 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
885 Name.getAsIdentifierInfo(),
886 ClassDeclared)) {
887 if (R.isAcceptableDecl(Ivar)) {
888 R.addDecl(Ivar);
889 R.resolveKind();
890 return true;
891 }
892 }
893 }
894 }
895
896 continue;
897 }
898
Douglas Gregore942bbe2009-09-10 16:57:35 +0000899 // Perform qualified name lookup into this context.
900 // FIXME: In some cases, we know that every name that could be found by
901 // this qualified name lookup will also be on the identifier chain. For
902 // example, inside a class without any base classes, we never need to
903 // perform qualified lookup because all of the members are on top of the
904 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000905 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000906 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000907 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000908 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000909 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000910
John McCalld7be78a2009-11-10 07:01:13 +0000911 // Stop if we ran out of scopes.
912 // FIXME: This really, really shouldn't be happening.
913 if (!S) return false;
914
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000915 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000916 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000917 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000918 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
919 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000920
John McCalld7be78a2009-11-10 07:01:13 +0000921 UnqualUsingDirectiveSet UDirs;
922 UDirs.visitScopeChain(Initial, S);
923 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000924
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000925 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000926 // Unqualified name lookup in C++ requires looking into scopes
927 // that aren't strictly lexical, and therefore we walk through the
928 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000929
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000930 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000931 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000932 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000933 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000934 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000935 // We found something. Look for anything else in our scope
936 // with this same name and in an acceptable identifier
937 // namespace, so that we can construct an overload set if we
938 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000939 Found = true;
940 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000941 }
942 }
943
Douglas Gregor00b4b032010-05-14 04:53:42 +0000944 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000945 R.resolveKind();
946 return true;
947 }
948
Douglas Gregor00b4b032010-05-14 04:53:42 +0000949 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
950 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
951 S->getParent() && !S->getParent()->isTemplateParamScope()) {
952 // We've just searched the last template parameter scope and
953 // found nothing, so look into the the contexts between the
954 // lexical and semantic declaration contexts returned by
955 // findOuterContext(). This implements the name lookup behavior
956 // of C++ [temp.local]p8.
957 Ctx = OutsideOfTemplateParamDC;
958 OutsideOfTemplateParamDC = 0;
959 }
960
961 if (Ctx) {
962 DeclContext *OuterCtx;
963 bool SearchAfterTemplateScope;
964 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
965 if (SearchAfterTemplateScope)
966 OutsideOfTemplateParamDC = OuterCtx;
967
968 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
969 // We do not directly look into transparent contexts, since
970 // those entities will be found in the nearest enclosing
971 // non-transparent context.
972 if (Ctx->isTransparentContext())
973 continue;
974
975 // If we have a context, and it's not a context stashed in the
976 // template parameter scope for an out-of-line definition, also
977 // look into that context.
978 if (!(Found && S && S->isTemplateParamScope())) {
979 assert(Ctx->isFileContext() &&
980 "We should have been looking only at file context here already.");
981
982 // Look into context considering using-directives.
983 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
984 Found = true;
985 }
986
987 if (Found) {
988 R.resolveKind();
989 return true;
990 }
991
992 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
993 return false;
994 }
995 }
996
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000997 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000998 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000999 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001000
John McCallf36e02d2009-10-09 21:13:30 +00001001 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001002}
1003
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001004/// @brief Perform unqualified name lookup starting from a given
1005/// scope.
1006///
1007/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1008/// used to find names within the current scope. For example, 'x' in
1009/// @code
1010/// int x;
1011/// int f() {
1012/// return x; // unqualified name look finds 'x' in the global scope
1013/// }
1014/// @endcode
1015///
1016/// Different lookup criteria can find different names. For example, a
1017/// particular scope can have both a struct and a function of the same
1018/// name, and each can be found by certain lookup criteria. For more
1019/// information about lookup criteria, see the documentation for the
1020/// class LookupCriteria.
1021///
1022/// @param S The scope from which unqualified name lookup will
1023/// begin. If the lookup criteria permits, name lookup may also search
1024/// in the parent scopes.
1025///
1026/// @param Name The name of the entity that we are searching for.
1027///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001028/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001029/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001030/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001031///
1032/// @returns The result of name lookup, which includes zero or more
1033/// declarations and possibly additional information used to diagnose
1034/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001035bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1036 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001037 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001038
John McCalla24dc2e2009-11-17 02:14:36 +00001039 LookupNameKind NameKind = R.getLookupKind();
1040
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001041 if (!getLangOptions().CPlusPlus) {
1042 // Unqualified name lookup in C/Objective-C is purely lexical, so
1043 // search in the declarations attached to the name.
1044
John McCall1d7c5282009-12-18 10:40:03 +00001045 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001046 // Find the nearest non-transparent declaration scope.
1047 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001048 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001049 static_cast<DeclContext *>(S->getEntity())
1050 ->isTransparentContext()))
1051 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001052 }
1053
John McCall1d7c5282009-12-18 10:40:03 +00001054 unsigned IDNS = R.getIdentifierNamespace();
1055
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001056 // Scan up the scope chain looking for a decl that matches this
1057 // identifier that is in the appropriate namespace. This search
1058 // should not take long, as shadowing of names is uncommon, and
1059 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001060 bool LeftStartingScope = false;
1061
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001062 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001063 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001064 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001065 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001066 if (NameKind == LookupRedeclarationWithLinkage) {
1067 // Determine whether this (or a previous) declaration is
1068 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001069 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001070 LeftStartingScope = true;
1071
1072 // If we found something outside of our starting scope that
1073 // does not have linkage, skip it.
1074 if (LeftStartingScope && !((*I)->hasLinkage()))
1075 continue;
1076 }
1077
John McCallf36e02d2009-10-09 21:13:30 +00001078 R.addDecl(*I);
1079
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001080 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001081 // If this declaration has the "overloadable" attribute, we
1082 // might have a set of overloaded functions.
1083
1084 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001085 while (!(S->getFlags() & Scope::DeclScope) ||
John McCalld226f652010-08-21 09:40:31 +00001086 !S->isDeclScope(*I))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001087 S = S->getParent();
1088
1089 // Find the last declaration in this scope (with the same
1090 // name, naturally).
1091 IdentifierResolver::iterator LastI = I;
1092 for (++LastI; LastI != IEnd; ++LastI) {
John McCalld226f652010-08-21 09:40:31 +00001093 if (!S->isDeclScope(*LastI))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001094 break;
John McCallf36e02d2009-10-09 21:13:30 +00001095 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001096 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001097 }
1098
John McCallf36e02d2009-10-09 21:13:30 +00001099 R.resolveKind();
1100
1101 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001102 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001103 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001104 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001105 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001106 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001107 }
1108
1109 // If we didn't find a use of this identifier, and if the identifier
1110 // corresponds to a compiler builtin, create the decl object for the builtin
1111 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +00001112 if (AllowBuiltinCreation)
1113 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001114
John McCallf36e02d2009-10-09 21:13:30 +00001115 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001116}
1117
John McCall6e247262009-10-10 05:48:19 +00001118/// @brief Perform qualified name lookup in the namespaces nominated by
1119/// using directives by the given context.
1120///
1121/// C++98 [namespace.qual]p2:
1122/// Given X::m (where X is a user-declared namespace), or given ::m
1123/// (where X is the global namespace), let S be the set of all
1124/// declarations of m in X and in the transitive closure of all
1125/// namespaces nominated by using-directives in X and its used
1126/// namespaces, except that using-directives are ignored in any
1127/// namespace, including X, directly containing one or more
1128/// declarations of m. No namespace is searched more than once in
1129/// the lookup of a name. If S is the empty set, the program is
1130/// ill-formed. Otherwise, if S has exactly one member, or if the
1131/// context of the reference is a using-declaration
1132/// (namespace.udecl), S is the required set of declarations of
1133/// m. Otherwise if the use of m is not one that allows a unique
1134/// declaration to be chosen from S, the program is ill-formed.
1135/// C++98 [namespace.qual]p5:
1136/// During the lookup of a qualified namespace member name, if the
1137/// lookup finds more than one declaration of the member, and if one
1138/// declaration introduces a class name or enumeration name and the
1139/// other declarations either introduce the same object, the same
1140/// enumerator or a set of functions, the non-type name hides the
1141/// class or enumeration name if and only if the declarations are
1142/// from the same namespace; otherwise (the declarations are from
1143/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001144static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001145 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001146 assert(StartDC->isFileContext() && "start context is not a file context");
1147
1148 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1149 DeclContext::udir_iterator E = StartDC->using_directives_end();
1150
1151 if (I == E) return false;
1152
1153 // We have at least added all these contexts to the queue.
1154 llvm::DenseSet<DeclContext*> Visited;
1155 Visited.insert(StartDC);
1156
1157 // We have not yet looked into these namespaces, much less added
1158 // their "using-children" to the queue.
1159 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1160
1161 // We have already looked into the initial namespace; seed the queue
1162 // with its using-children.
1163 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001164 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001165 if (Visited.insert(ND).second)
1166 Queue.push_back(ND);
1167 }
1168
1169 // The easiest way to implement the restriction in [namespace.qual]p5
1170 // is to check whether any of the individual results found a tag
1171 // and, if so, to declare an ambiguity if the final result is not
1172 // a tag.
1173 bool FoundTag = false;
1174 bool FoundNonTag = false;
1175
John McCall7d384dd2009-11-18 07:57:50 +00001176 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001177
1178 bool Found = false;
1179 while (!Queue.empty()) {
1180 NamespaceDecl *ND = Queue.back();
1181 Queue.pop_back();
1182
1183 // We go through some convolutions here to avoid copying results
1184 // between LookupResults.
1185 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001186 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001187 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001188
1189 if (FoundDirect) {
1190 // First do any local hiding.
1191 DirectR.resolveKind();
1192
1193 // If the local result is a tag, remember that.
1194 if (DirectR.isSingleTagDecl())
1195 FoundTag = true;
1196 else
1197 FoundNonTag = true;
1198
1199 // Append the local results to the total results if necessary.
1200 if (UseLocal) {
1201 R.addAllDecls(LocalR);
1202 LocalR.clear();
1203 }
1204 }
1205
1206 // If we find names in this namespace, ignore its using directives.
1207 if (FoundDirect) {
1208 Found = true;
1209 continue;
1210 }
1211
1212 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1213 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1214 if (Visited.insert(Nom).second)
1215 Queue.push_back(Nom);
1216 }
1217 }
1218
1219 if (Found) {
1220 if (FoundTag && FoundNonTag)
1221 R.setAmbiguousQualifiedTagHiding();
1222 else
1223 R.resolveKind();
1224 }
1225
1226 return Found;
1227}
1228
Douglas Gregor8071e422010-08-15 06:18:01 +00001229/// \brief Callback that looks for any member of a class with the given name.
1230static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1231 CXXBasePath &Path,
1232 void *Name) {
1233 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1234
1235 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1236 Path.Decls = BaseRecord->lookup(N);
1237 return Path.Decls.first != Path.Decls.second;
1238}
1239
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001240/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001241///
1242/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1243/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001244/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001245///
1246/// Different lookup criteria can find different names. For example, a
1247/// particular scope can have both a struct and a function of the same
1248/// name, and each can be found by certain lookup criteria. For more
1249/// information about lookup criteria, see the documentation for the
1250/// class LookupCriteria.
1251///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001252/// \param R captures both the lookup criteria and any lookup results found.
1253///
1254/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001255/// search. If the lookup criteria permits, name lookup may also search
1256/// in the parent contexts or (for C++ classes) base classes.
1257///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001258/// \param InUnqualifiedLookup true if this is qualified name lookup that
1259/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001260///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001261/// \returns true if lookup succeeded, false if it failed.
1262bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1263 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001264 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001265
John McCalla24dc2e2009-11-17 02:14:36 +00001266 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001267 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001269 // Make sure that the declaration context is complete.
1270 assert((!isa<TagDecl>(LookupCtx) ||
1271 LookupCtx->isDependentContext() ||
1272 cast<TagDecl>(LookupCtx)->isDefinition() ||
1273 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1274 ->isBeingDefined()) &&
1275 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001277 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001278 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001279 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001280 if (isa<CXXRecordDecl>(LookupCtx))
1281 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001282 return true;
1283 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001284
John McCall6e247262009-10-10 05:48:19 +00001285 // Don't descend into implied contexts for redeclarations.
1286 // C++98 [namespace.qual]p6:
1287 // In a declaration for a namespace member in which the
1288 // declarator-id is a qualified-id, given that the qualified-id
1289 // for the namespace member has the form
1290 // nested-name-specifier unqualified-id
1291 // the unqualified-id shall name a member of the namespace
1292 // designated by the nested-name-specifier.
1293 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001294 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001295 return false;
1296
John McCalla24dc2e2009-11-17 02:14:36 +00001297 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001298 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001299 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001300
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001301 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001302 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001303 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001304 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001305 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001306
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001307 // If we're performing qualified name lookup into a dependent class,
1308 // then we are actually looking into a current instantiation. If we have any
1309 // dependent base classes, then we either have to delay lookup until
1310 // template instantiation time (at which point all bases will be available)
1311 // or we have to fail.
1312 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1313 LookupRec->hasAnyDependentBases()) {
1314 R.setNotFoundInCurrentInstantiation();
1315 return false;
1316 }
1317
Douglas Gregor7176fff2009-01-15 00:26:24 +00001318 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001319 CXXBasePaths Paths;
1320 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001321
1322 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001323 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001324 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001325 case LookupOrdinaryName:
1326 case LookupMemberName:
1327 case LookupRedeclarationWithLinkage:
1328 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1329 break;
1330
1331 case LookupTagName:
1332 BaseCallback = &CXXRecordDecl::FindTagMember;
1333 break;
John McCall9f54ad42009-12-10 09:41:52 +00001334
Douglas Gregor8071e422010-08-15 06:18:01 +00001335 case LookupAnyName:
1336 BaseCallback = &LookupAnyMember;
1337 break;
1338
John McCall9f54ad42009-12-10 09:41:52 +00001339 case LookupUsingDeclName:
1340 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001341
1342 case LookupOperatorName:
1343 case LookupNamespaceName:
1344 case LookupObjCProtocolName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001345 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001346 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001347
1348 case LookupNestedNameSpecifierName:
1349 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1350 break;
1351 }
1352
John McCalla24dc2e2009-11-17 02:14:36 +00001353 if (!LookupRec->lookupInBases(BaseCallback,
1354 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001355 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001356
John McCall92f88312010-01-23 00:46:32 +00001357 R.setNamingClass(LookupRec);
1358
Douglas Gregor7176fff2009-01-15 00:26:24 +00001359 // C++ [class.member.lookup]p2:
1360 // [...] If the resulting set of declarations are not all from
1361 // sub-objects of the same type, or the set has a nonstatic member
1362 // and includes members from distinct sub-objects, there is an
1363 // ambiguity and the program is ill-formed. Otherwise that set is
1364 // the result of the lookup.
1365 // FIXME: support using declarations!
1366 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001367 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001368 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001369 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001370 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001371 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001372
John McCall46460a62010-01-20 21:53:11 +00001373 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1374 // across all paths.
1375 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1376
Douglas Gregor7176fff2009-01-15 00:26:24 +00001377 // Determine whether we're looking at a distinct sub-object or not.
1378 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001379 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001380 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1381 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00001382 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001383 != Context.getCanonicalType(PathElement.Base->getType())) {
1384 // We found members of the given name in two subobjects of
1385 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001386 R.setAmbiguousBaseSubobjectTypes(Paths);
1387 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001388 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1389 // We have a different subobject of the same type.
1390
1391 // C++ [class.member.lookup]p5:
1392 // A static member, a nested type or an enumerator defined in
1393 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001394 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001395 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001396 if (isa<VarDecl>(FirstDecl) ||
1397 isa<TypeDecl>(FirstDecl) ||
1398 isa<EnumConstantDecl>(FirstDecl))
1399 continue;
1400
1401 if (isa<CXXMethodDecl>(FirstDecl)) {
1402 // Determine whether all of the methods are static.
1403 bool AllMethodsAreStatic = true;
1404 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1405 Func != Path->Decls.second; ++Func) {
1406 if (!isa<CXXMethodDecl>(*Func)) {
1407 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1408 break;
1409 }
1410
1411 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1412 AllMethodsAreStatic = false;
1413 break;
1414 }
1415 }
1416
1417 if (AllMethodsAreStatic)
1418 continue;
1419 }
1420
1421 // We have found a nonstatic member name in multiple, distinct
1422 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001423 R.setAmbiguousBaseSubobjects(Paths);
1424 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001425 }
1426 }
1427
1428 // Lookup in a base class succeeded; return these results.
1429
John McCallf36e02d2009-10-09 21:13:30 +00001430 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001431 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1432 NamedDecl *D = *I;
1433 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1434 D->getAccess());
1435 R.addDecl(D, AS);
1436 }
John McCallf36e02d2009-10-09 21:13:30 +00001437 R.resolveKind();
1438 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001439}
1440
1441/// @brief Performs name lookup for a name that was parsed in the
1442/// source code, and may contain a C++ scope specifier.
1443///
1444/// This routine is a convenience routine meant to be called from
1445/// contexts that receive a name and an optional C++ scope specifier
1446/// (e.g., "N::M::x"). It will then perform either qualified or
1447/// unqualified name lookup (with LookupQualifiedName or LookupName,
1448/// respectively) on the given name and return those results.
1449///
1450/// @param S The scope from which unqualified name lookup will
1451/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001452///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001453/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001454///
1455/// @param Name The name of the entity that name lookup will
1456/// search for.
1457///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001458/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001459/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001460/// C library functions (like "malloc") are implicitly declared.
1461///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001462/// @param EnteringContext Indicates whether we are going to enter the
1463/// context of the scope-specifier SS (if present).
1464///
John McCallf36e02d2009-10-09 21:13:30 +00001465/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001466bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001467 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001468 if (SS && SS->isInvalid()) {
1469 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001470 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001471 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001472 }
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Douglas Gregor495c35d2009-08-25 22:51:20 +00001474 if (SS && SS->isSet()) {
1475 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001476 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001477 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001478 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001479 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001480
John McCalla24dc2e2009-11-17 02:14:36 +00001481 R.setContextRange(SS->getRange());
1482
1483 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001484 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001485
Douglas Gregor495c35d2009-08-25 22:51:20 +00001486 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001487 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001488 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001489 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001490 }
1491
Mike Stump1eb44332009-09-09 15:08:12 +00001492 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001493 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001494}
1495
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001496
Douglas Gregor7176fff2009-01-15 00:26:24 +00001497/// @brief Produce a diagnostic describing the ambiguity that resulted
1498/// from name lookup.
1499///
1500/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001501///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001502/// @param Name The name of the entity that name lookup was
1503/// searching for.
1504///
1505/// @param NameLoc The location of the name within the source code.
1506///
1507/// @param LookupRange A source range that provides more
1508/// source-location information concerning the lookup itself. For
1509/// example, this range might highlight a nested-name-specifier that
1510/// precedes the name.
1511///
1512/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001513bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001514 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1515
John McCalla24dc2e2009-11-17 02:14:36 +00001516 DeclarationName Name = Result.getLookupName();
1517 SourceLocation NameLoc = Result.getNameLoc();
1518 SourceRange LookupRange = Result.getContextRange();
1519
John McCall6e247262009-10-10 05:48:19 +00001520 switch (Result.getAmbiguityKind()) {
1521 case LookupResult::AmbiguousBaseSubobjects: {
1522 CXXBasePaths *Paths = Result.getBasePaths();
1523 QualType SubobjectType = Paths->front().back().Base->getType();
1524 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1525 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1526 << LookupRange;
1527
1528 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1529 while (isa<CXXMethodDecl>(*Found) &&
1530 cast<CXXMethodDecl>(*Found)->isStatic())
1531 ++Found;
1532
1533 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1534
1535 return true;
1536 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001537
John McCall6e247262009-10-10 05:48:19 +00001538 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001539 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1540 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001541
1542 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001543 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001544 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1545 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001546 Path != PathEnd; ++Path) {
1547 Decl *D = *Path->Decls.first;
1548 if (DeclsPrinted.insert(D).second)
1549 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1550 }
1551
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001552 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001553 }
1554
John McCall6e247262009-10-10 05:48:19 +00001555 case LookupResult::AmbiguousTagHiding: {
1556 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001557
John McCall6e247262009-10-10 05:48:19 +00001558 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1559
1560 LookupResult::iterator DI, DE = Result.end();
1561 for (DI = Result.begin(); DI != DE; ++DI)
1562 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1563 TagDecls.insert(TD);
1564 Diag(TD->getLocation(), diag::note_hidden_tag);
1565 }
1566
1567 for (DI = Result.begin(); DI != DE; ++DI)
1568 if (!isa<TagDecl>(*DI))
1569 Diag((*DI)->getLocation(), diag::note_hiding_object);
1570
1571 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001572 LookupResult::Filter F = Result.makeFilter();
1573 while (F.hasNext()) {
1574 if (TagDecls.count(F.next()))
1575 F.erase();
1576 }
1577 F.done();
John McCall6e247262009-10-10 05:48:19 +00001578
1579 return true;
1580 }
1581
1582 case LookupResult::AmbiguousReference: {
1583 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001584
John McCall6e247262009-10-10 05:48:19 +00001585 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1586 for (; DI != DE; ++DI)
1587 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001588
John McCall6e247262009-10-10 05:48:19 +00001589 return true;
1590 }
1591 }
1592
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001593 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001594 return true;
1595}
Douglas Gregorfa047642009-02-04 00:32:51 +00001596
John McCallc7e04da2010-05-28 18:45:08 +00001597namespace {
1598 struct AssociatedLookup {
1599 AssociatedLookup(Sema &S,
1600 Sema::AssociatedNamespaceSet &Namespaces,
1601 Sema::AssociatedClassSet &Classes)
1602 : S(S), Namespaces(Namespaces), Classes(Classes) {
1603 }
1604
1605 Sema &S;
1606 Sema::AssociatedNamespaceSet &Namespaces;
1607 Sema::AssociatedClassSet &Classes;
1608 };
1609}
1610
Mike Stump1eb44332009-09-09 15:08:12 +00001611static void
John McCallc7e04da2010-05-28 18:45:08 +00001612addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001613
Douglas Gregor54022952010-04-30 07:08:38 +00001614static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1615 DeclContext *Ctx) {
1616 // Add the associated namespace for this class.
1617
1618 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1619 // be a locally scoped record.
1620
Sebastian Redl410c4f22010-08-31 20:53:31 +00001621 // We skip out of inline namespaces. The innermost non-inline namespace
1622 // contains all names of all its nested inline namespaces anyway, so we can
1623 // replace the entire inline namespace tree with its root.
1624 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1625 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001626 Ctx = Ctx->getParent();
1627
John McCall6ff07852009-08-07 22:18:02 +00001628 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001629 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001630}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001631
Mike Stump1eb44332009-09-09 15:08:12 +00001632// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001633// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001634static void
John McCallc7e04da2010-05-28 18:45:08 +00001635addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1636 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001637 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001638 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001639 switch (Arg.getKind()) {
1640 case TemplateArgument::Null:
1641 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Douglas Gregor69be8d62009-07-08 07:51:57 +00001643 case TemplateArgument::Type:
1644 // [...] the namespaces and classes associated with the types of the
1645 // template arguments provided for template type parameters (excluding
1646 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001647 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001648 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Douglas Gregor788cd062009-11-11 01:00:40 +00001650 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001651 // [...] the namespaces in which any template template arguments are
1652 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001653 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001654 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001655 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001656 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001657 DeclContext *Ctx = ClassTemplate->getDeclContext();
1658 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001659 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001660 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001661 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001662 }
1663 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001664 }
1665
1666 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001667 case TemplateArgument::Integral:
1668 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001669 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001670 // associated namespaces. ]
1671 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Douglas Gregor69be8d62009-07-08 07:51:57 +00001673 case TemplateArgument::Pack:
1674 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1675 PEnd = Arg.pack_end();
1676 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001677 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001678 break;
1679 }
1680}
1681
Douglas Gregorfa047642009-02-04 00:32:51 +00001682// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001683// argument-dependent lookup with an argument of class type
1684// (C++ [basic.lookup.koenig]p2).
1685static void
John McCallc7e04da2010-05-28 18:45:08 +00001686addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1687 CXXRecordDecl *Class) {
1688
1689 // Just silently ignore anything whose name is __va_list_tag.
1690 if (Class->getDeclName() == Result.S.VAListTagName)
1691 return;
1692
Douglas Gregorfa047642009-02-04 00:32:51 +00001693 // C++ [basic.lookup.koenig]p2:
1694 // [...]
1695 // -- If T is a class type (including unions), its associated
1696 // classes are: the class itself; the class of which it is a
1697 // member, if any; and its direct and indirect base
1698 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001699 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001700
1701 // Add the class of which it is a member, if any.
1702 DeclContext *Ctx = Class->getDeclContext();
1703 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001704 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001705 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001706 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Douglas Gregorfa047642009-02-04 00:32:51 +00001708 // Add the class itself. If we've already seen this class, we don't
1709 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001710 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001711 return;
1712
Mike Stump1eb44332009-09-09 15:08:12 +00001713 // -- If T is a template-id, its associated namespaces and classes are
1714 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001715 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001716 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001717 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001718 // namespaces in which any template template arguments are defined; and
1719 // the classes in which any member templates used as template template
1720 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001721 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001722 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001723 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1724 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1725 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001726 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001727 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001728 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Douglas Gregor69be8d62009-07-08 07:51:57 +00001730 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1731 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001732 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001733 }
Mike Stump1eb44332009-09-09 15:08:12 +00001734
John McCall86ff3082010-02-04 22:26:26 +00001735 // Only recurse into base classes for complete types.
1736 if (!Class->hasDefinition()) {
1737 // FIXME: we might need to instantiate templates here
1738 return;
1739 }
1740
Douglas Gregorfa047642009-02-04 00:32:51 +00001741 // Add direct and indirect base classes along with their associated
1742 // namespaces.
1743 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1744 Bases.push_back(Class);
1745 while (!Bases.empty()) {
1746 // Pop this class off the stack.
1747 Class = Bases.back();
1748 Bases.pop_back();
1749
1750 // Visit the base classes.
1751 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1752 BaseEnd = Class->bases_end();
1753 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001754 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001755 // In dependent contexts, we do ADL twice, and the first time around,
1756 // the base type might be a dependent TemplateSpecializationType, or a
1757 // TemplateTypeParmType. If that happens, simply ignore it.
1758 // FIXME: If we want to support export, we probably need to add the
1759 // namespace of the template in a TemplateSpecializationType, or even
1760 // the classes and namespaces of known non-dependent arguments.
1761 if (!BaseType)
1762 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001763 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001764 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001765 // Find the associated namespace for this base class.
1766 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001767 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001768
1769 // Make sure we visit the bases of this base class.
1770 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1771 Bases.push_back(BaseDecl);
1772 }
1773 }
1774 }
1775}
1776
1777// \brief Add the associated classes and namespaces for
1778// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001779// (C++ [basic.lookup.koenig]p2).
1780static void
John McCallc7e04da2010-05-28 18:45:08 +00001781addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001782 // C++ [basic.lookup.koenig]p2:
1783 //
1784 // For each argument type T in the function call, there is a set
1785 // of zero or more associated namespaces and a set of zero or more
1786 // associated classes to be considered. The sets of namespaces and
1787 // classes is determined entirely by the types of the function
1788 // arguments (and the namespace of any template template
1789 // argument). Typedef names and using-declarations used to specify
1790 // the types do not contribute to this set. The sets of namespaces
1791 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001792
John McCallfa4edcf2010-05-28 06:08:54 +00001793 llvm::SmallVector<const Type *, 16> Queue;
1794 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1795
Douglas Gregorfa047642009-02-04 00:32:51 +00001796 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001797 switch (T->getTypeClass()) {
1798
1799#define TYPE(Class, Base)
1800#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1801#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1802#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1803#define ABSTRACT_TYPE(Class, Base)
1804#include "clang/AST/TypeNodes.def"
1805 // T is canonical. We can also ignore dependent types because
1806 // we don't need to do ADL at the definition point, but if we
1807 // wanted to implement template export (or if we find some other
1808 // use for associated classes and namespaces...) this would be
1809 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001810 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001811
John McCallfa4edcf2010-05-28 06:08:54 +00001812 // -- If T is a pointer to U or an array of U, its associated
1813 // namespaces and classes are those associated with U.
1814 case Type::Pointer:
1815 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1816 continue;
1817 case Type::ConstantArray:
1818 case Type::IncompleteArray:
1819 case Type::VariableArray:
1820 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1821 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001822
John McCallfa4edcf2010-05-28 06:08:54 +00001823 // -- If T is a fundamental type, its associated sets of
1824 // namespaces and classes are both empty.
1825 case Type::Builtin:
1826 break;
1827
1828 // -- If T is a class type (including unions), its associated
1829 // classes are: the class itself; the class of which it is a
1830 // member, if any; and its direct and indirect base
1831 // classes. Its associated namespaces are the namespaces in
1832 // which its associated classes are defined.
1833 case Type::Record: {
1834 CXXRecordDecl *Class
1835 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001836 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001837 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001838 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001839
John McCallfa4edcf2010-05-28 06:08:54 +00001840 // -- If T is an enumeration type, its associated namespace is
1841 // the namespace in which it is defined. If it is class
1842 // member, its associated class is the member’s class; else
1843 // it has no associated class.
1844 case Type::Enum: {
1845 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001846
John McCallfa4edcf2010-05-28 06:08:54 +00001847 DeclContext *Ctx = Enum->getDeclContext();
1848 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001849 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001850
John McCallfa4edcf2010-05-28 06:08:54 +00001851 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001852 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001853
John McCallfa4edcf2010-05-28 06:08:54 +00001854 break;
1855 }
1856
1857 // -- If T is a function type, its associated namespaces and
1858 // classes are those associated with the function parameter
1859 // types and those associated with the return type.
1860 case Type::FunctionProto: {
1861 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1862 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1863 ArgEnd = Proto->arg_type_end();
1864 Arg != ArgEnd; ++Arg)
1865 Queue.push_back(Arg->getTypePtr());
1866 // fallthrough
1867 }
1868 case Type::FunctionNoProto: {
1869 const FunctionType *FnType = cast<FunctionType>(T);
1870 T = FnType->getResultType().getTypePtr();
1871 continue;
1872 }
1873
1874 // -- If T is a pointer to a member function of a class X, its
1875 // associated namespaces and classes are those associated
1876 // with the function parameter types and return type,
1877 // together with those associated with X.
1878 //
1879 // -- If T is a pointer to a data member of class X, its
1880 // associated namespaces and classes are those associated
1881 // with the member type together with those associated with
1882 // X.
1883 case Type::MemberPointer: {
1884 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1885
1886 // Queue up the class type into which this points.
1887 Queue.push_back(MemberPtr->getClass());
1888
1889 // And directly continue with the pointee type.
1890 T = MemberPtr->getPointeeType().getTypePtr();
1891 continue;
1892 }
1893
1894 // As an extension, treat this like a normal pointer.
1895 case Type::BlockPointer:
1896 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1897 continue;
1898
1899 // References aren't covered by the standard, but that's such an
1900 // obvious defect that we cover them anyway.
1901 case Type::LValueReference:
1902 case Type::RValueReference:
1903 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1904 continue;
1905
1906 // These are fundamental types.
1907 case Type::Vector:
1908 case Type::ExtVector:
1909 case Type::Complex:
1910 break;
1911
1912 // These are ignored by ADL.
1913 case Type::ObjCObject:
1914 case Type::ObjCInterface:
1915 case Type::ObjCObjectPointer:
1916 break;
1917 }
1918
1919 if (Queue.empty()) break;
1920 T = Queue.back();
1921 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001922 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001923}
1924
1925/// \brief Find the associated classes and namespaces for
1926/// argument-dependent lookup for a call with the given set of
1927/// arguments.
1928///
1929/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001930/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001931/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001932void
Douglas Gregorfa047642009-02-04 00:32:51 +00001933Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1934 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001935 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001936 AssociatedNamespaces.clear();
1937 AssociatedClasses.clear();
1938
John McCallc7e04da2010-05-28 18:45:08 +00001939 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1940
Douglas Gregorfa047642009-02-04 00:32:51 +00001941 // C++ [basic.lookup.koenig]p2:
1942 // For each argument type T in the function call, there is a set
1943 // of zero or more associated namespaces and a set of zero or more
1944 // associated classes to be considered. The sets of namespaces and
1945 // classes is determined entirely by the types of the function
1946 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001947 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001948 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1949 Expr *Arg = Args[ArgIdx];
1950
1951 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00001952 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001953 continue;
1954 }
1955
1956 // [...] In addition, if the argument is the name or address of a
1957 // set of overloaded functions and/or function templates, its
1958 // associated classes and namespaces are the union of those
1959 // associated with each of the members of the set: the namespace
1960 // in which the function or function template is defined and the
1961 // classes and namespaces associated with its (non-dependent)
1962 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001963 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001964 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00001965 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00001966 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001967
John McCallc7e04da2010-05-28 18:45:08 +00001968 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1969 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00001970
John McCallc7e04da2010-05-28 18:45:08 +00001971 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1972 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001973 // Look through any using declarations to find the underlying function.
1974 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001975
Chandler Carruthbd647292009-12-29 06:17:27 +00001976 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1977 if (!FDecl)
1978 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001979
1980 // Add the classes and namespaces associated with the parameter
1981 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00001982 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001983 }
1984 }
1985}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001986
1987/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1988/// an acceptable non-member overloaded operator for a call whose
1989/// arguments have types T1 (and, if non-empty, T2). This routine
1990/// implements the check in C++ [over.match.oper]p3b2 concerning
1991/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001992static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001993IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1994 QualType T1, QualType T2,
1995 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001996 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1997 return true;
1998
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001999 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2000 return true;
2001
John McCall183700f2009-09-21 23:43:11 +00002002 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002003 if (Proto->getNumArgs() < 1)
2004 return false;
2005
2006 if (T1->isEnumeralType()) {
2007 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002008 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002009 return true;
2010 }
2011
2012 if (Proto->getNumArgs() < 2)
2013 return false;
2014
2015 if (!T2.isNull() && T2->isEnumeralType()) {
2016 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002017 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002018 return true;
2019 }
2020
2021 return false;
2022}
2023
John McCall7d384dd2009-11-18 07:57:50 +00002024NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002025 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002026 LookupNameKind NameKind,
2027 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002028 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002029 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002030 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002031}
2032
Douglas Gregor6e378de2009-04-23 23:18:26 +00002033/// \brief Find the protocol with the given name, if any.
Douglas Gregorc83c6872010-04-15 22:33:43 +00002034ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2035 SourceLocation IdLoc) {
2036 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2037 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002038 return cast_or_null<ObjCProtocolDecl>(D);
2039}
2040
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002041void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002042 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002043 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002044 // C++ [over.match.oper]p3:
2045 // -- The set of non-member candidates is the result of the
2046 // unqualified lookup of operator@ in the context of the
2047 // expression according to the usual rules for name lookup in
2048 // unqualified function calls (3.4.2) except that all member
2049 // functions are ignored. However, if no operand has a class
2050 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002051 // that have a first parameter of type T1 or "reference to
2052 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002053 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002054 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002055 // when T2 is an enumeration type, are candidate functions.
2056 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002057 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2058 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002060 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2061
John McCallf36e02d2009-10-09 21:13:30 +00002062 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002063 return;
2064
2065 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2066 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002067 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2068 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002069 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002070 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002071 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002072 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002073 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002074 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002075 // later?
2076 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002077 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002078 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002079 }
2080}
2081
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002082/// \brief Look up the constructors for the given class.
2083DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +00002084 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002085 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2086 if (!Class->hasDeclaredDefaultConstructor())
2087 DeclareImplicitDefaultConstructor(Class);
2088 if (!Class->hasDeclaredCopyConstructor())
2089 DeclareImplicitCopyConstructor(Class);
2090 }
Douglas Gregor22584312010-07-02 23:41:54 +00002091
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002092 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2093 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2094 return Class->lookup(Name);
2095}
2096
Douglas Gregordb89f282010-07-01 22:47:18 +00002097/// \brief Look for the destructor of the given class.
2098///
2099/// During semantic analysis, this routine should be used in lieu of
2100/// CXXRecordDecl::getDestructor().
2101///
2102/// \returns The destructor for this class.
2103CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +00002104 // If the destructor has not yet been declared, do so now.
2105 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2106 !Class->hasDeclaredDestructor())
2107 DeclareImplicitDestructor(Class);
2108
Douglas Gregordb89f282010-07-01 22:47:18 +00002109 return Class->getDestructor();
2110}
2111
John McCall7edb5fd2010-01-26 07:16:45 +00002112void ADLResult::insert(NamedDecl *New) {
2113 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2114
2115 // If we haven't yet seen a decl for this key, or the last decl
2116 // was exactly this one, we're done.
2117 if (Old == 0 || Old == New) {
2118 Old = New;
2119 return;
2120 }
2121
2122 // Otherwise, decide which is a more recent redeclaration.
2123 FunctionDecl *OldFD, *NewFD;
2124 if (isa<FunctionTemplateDecl>(New)) {
2125 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2126 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2127 } else {
2128 OldFD = cast<FunctionDecl>(Old);
2129 NewFD = cast<FunctionDecl>(New);
2130 }
2131
2132 FunctionDecl *Cursor = NewFD;
2133 while (true) {
2134 Cursor = Cursor->getPreviousDeclaration();
2135
2136 // If we got to the end without finding OldFD, OldFD is the newer
2137 // declaration; leave things as they are.
2138 if (!Cursor) return;
2139
2140 // If we do find OldFD, then NewFD is newer.
2141 if (Cursor == OldFD) break;
2142
2143 // Otherwise, keep looking.
2144 }
2145
2146 Old = New;
2147}
2148
Sebastian Redl644be852009-10-23 19:23:15 +00002149void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002150 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00002151 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002152 // Find all of the associated namespaces and classes based on the
2153 // arguments we have.
2154 AssociatedNamespaceSet AssociatedNamespaces;
2155 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002156 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002157 AssociatedNamespaces,
2158 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002159
Sebastian Redl644be852009-10-23 19:23:15 +00002160 QualType T1, T2;
2161 if (Operator) {
2162 T1 = Args[0]->getType();
2163 if (NumArgs >= 2)
2164 T2 = Args[1]->getType();
2165 }
2166
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002167 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002168 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2169 // and let Y be the lookup set produced by argument dependent
2170 // lookup (defined as follows). If X contains [...] then Y is
2171 // empty. Otherwise Y is the set of declarations found in the
2172 // namespaces associated with the argument types as described
2173 // below. The set of declarations found by the lookup of the name
2174 // is the union of X and Y.
2175 //
2176 // Here, we compute Y and add its members to the overloaded
2177 // candidate set.
2178 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002179 NSEnd = AssociatedNamespaces.end();
2180 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002181 // When considering an associated namespace, the lookup is the
2182 // same as the lookup performed when the associated namespace is
2183 // used as a qualifier (3.4.3.2) except that:
2184 //
2185 // -- Any using-directives in the associated namespace are
2186 // ignored.
2187 //
John McCall6ff07852009-08-07 22:18:02 +00002188 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002189 // associated classes are visible within their respective
2190 // namespaces even if they are not visible during an ordinary
2191 // lookup (11.4).
2192 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002193 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002194 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002195 // If the only declaration here is an ordinary friend, consider
2196 // it only if it was declared in an associated classes.
2197 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002198 DeclContext *LexDC = D->getLexicalDeclContext();
2199 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2200 continue;
2201 }
Mike Stump1eb44332009-09-09 15:08:12 +00002202
John McCalla113e722010-01-26 06:04:06 +00002203 if (isa<UsingShadowDecl>(D))
2204 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002205
John McCalla113e722010-01-26 06:04:06 +00002206 if (isa<FunctionDecl>(D)) {
2207 if (Operator &&
2208 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2209 T1, T2, Context))
2210 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002211 } else if (!isa<FunctionTemplateDecl>(D))
2212 continue;
2213
2214 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002215 }
2216 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002217}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002218
2219//----------------------------------------------------------------------------
2220// Search for all visible declarations.
2221//----------------------------------------------------------------------------
2222VisibleDeclConsumer::~VisibleDeclConsumer() { }
2223
2224namespace {
2225
2226class ShadowContextRAII;
2227
2228class VisibleDeclsRecord {
2229public:
2230 /// \brief An entry in the shadow map, which is optimized to store a
2231 /// single declaration (the common case) but can also store a list
2232 /// of declarations.
2233 class ShadowMapEntry {
2234 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2235
2236 /// \brief Contains either the solitary NamedDecl * or a vector
2237 /// of declarations.
2238 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2239
2240 public:
2241 ShadowMapEntry() : DeclOrVector() { }
2242
2243 void Add(NamedDecl *ND);
2244 void Destroy();
2245
2246 // Iteration.
2247 typedef NamedDecl **iterator;
2248 iterator begin();
2249 iterator end();
2250 };
2251
2252private:
2253 /// \brief A mapping from declaration names to the declarations that have
2254 /// this name within a particular scope.
2255 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2256
2257 /// \brief A list of shadow maps, which is used to model name hiding.
2258 std::list<ShadowMap> ShadowMaps;
2259
2260 /// \brief The declaration contexts we have already visited.
2261 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2262
2263 friend class ShadowContextRAII;
2264
2265public:
2266 /// \brief Determine whether we have already visited this context
2267 /// (and, if not, note that we are going to visit that context now).
2268 bool visitedContext(DeclContext *Ctx) {
2269 return !VisitedContexts.insert(Ctx);
2270 }
2271
Douglas Gregor8071e422010-08-15 06:18:01 +00002272 bool alreadyVisitedContext(DeclContext *Ctx) {
2273 return VisitedContexts.count(Ctx);
2274 }
2275
Douglas Gregor546be3c2009-12-30 17:04:44 +00002276 /// \brief Determine whether the given declaration is hidden in the
2277 /// current scope.
2278 ///
2279 /// \returns the declaration that hides the given declaration, or
2280 /// NULL if no such declaration exists.
2281 NamedDecl *checkHidden(NamedDecl *ND);
2282
2283 /// \brief Add a declaration to the current shadow map.
2284 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2285};
2286
2287/// \brief RAII object that records when we've entered a shadow context.
2288class ShadowContextRAII {
2289 VisibleDeclsRecord &Visible;
2290
2291 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2292
2293public:
2294 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2295 Visible.ShadowMaps.push_back(ShadowMap());
2296 }
2297
2298 ~ShadowContextRAII() {
2299 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2300 EEnd = Visible.ShadowMaps.back().end();
2301 E != EEnd;
2302 ++E)
2303 E->second.Destroy();
2304
2305 Visible.ShadowMaps.pop_back();
2306 }
2307};
2308
2309} // end anonymous namespace
2310
2311void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2312 if (DeclOrVector.isNull()) {
2313 // 0 - > 1 elements: just set the single element information.
2314 DeclOrVector = ND;
2315 return;
2316 }
2317
2318 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2319 // 1 -> 2 elements: create the vector of results and push in the
2320 // existing declaration.
2321 DeclVector *Vec = new DeclVector;
2322 Vec->push_back(PrevND);
2323 DeclOrVector = Vec;
2324 }
2325
2326 // Add the new element to the end of the vector.
2327 DeclOrVector.get<DeclVector*>()->push_back(ND);
2328}
2329
2330void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2331 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2332 delete Vec;
2333 DeclOrVector = ((NamedDecl *)0);
2334 }
2335}
2336
2337VisibleDeclsRecord::ShadowMapEntry::iterator
2338VisibleDeclsRecord::ShadowMapEntry::begin() {
2339 if (DeclOrVector.isNull())
2340 return 0;
2341
2342 if (DeclOrVector.dyn_cast<NamedDecl *>())
2343 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2344
2345 return DeclOrVector.get<DeclVector *>()->begin();
2346}
2347
2348VisibleDeclsRecord::ShadowMapEntry::iterator
2349VisibleDeclsRecord::ShadowMapEntry::end() {
2350 if (DeclOrVector.isNull())
2351 return 0;
2352
2353 if (DeclOrVector.dyn_cast<NamedDecl *>())
2354 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2355
2356 return DeclOrVector.get<DeclVector *>()->end();
2357}
2358
2359NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002360 // Look through using declarations.
2361 ND = ND->getUnderlyingDecl();
2362
Douglas Gregor546be3c2009-12-30 17:04:44 +00002363 unsigned IDNS = ND->getIdentifierNamespace();
2364 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2365 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2366 SM != SMEnd; ++SM) {
2367 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2368 if (Pos == SM->end())
2369 continue;
2370
2371 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2372 IEnd = Pos->second.end();
2373 I != IEnd; ++I) {
2374 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002375 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor546be3c2009-12-30 17:04:44 +00002376 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2377 Decl::IDNS_ObjCProtocol)))
2378 continue;
2379
2380 // Protocols are in distinct namespaces from everything else.
2381 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2382 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2383 (*I)->getIdentifierNamespace() != IDNS)
2384 continue;
2385
Douglas Gregor0cc84042010-01-14 15:47:35 +00002386 // Functions and function templates in the same scope overload
2387 // rather than hide. FIXME: Look for hiding based on function
2388 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002389 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002390 ND->isFunctionOrFunctionTemplate() &&
2391 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002392 continue;
2393
Douglas Gregor546be3c2009-12-30 17:04:44 +00002394 // We've found a declaration that hides this one.
2395 return *I;
2396 }
2397 }
2398
2399 return 0;
2400}
2401
2402static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2403 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002404 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002405 VisibleDeclConsumer &Consumer,
2406 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002407 if (!Ctx)
2408 return;
2409
Douglas Gregor546be3c2009-12-30 17:04:44 +00002410 // Make sure we don't visit the same context twice.
2411 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2412 return;
2413
Douglas Gregor4923aa22010-07-02 20:37:36 +00002414 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2415 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2416
Douglas Gregor546be3c2009-12-30 17:04:44 +00002417 // Enumerate all of the results in this context.
2418 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2419 CurCtx = CurCtx->getNextContext()) {
2420 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2421 DEnd = CurCtx->decls_end();
2422 D != DEnd; ++D) {
2423 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2424 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002425 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002426 Visited.add(ND);
2427 }
2428
Sebastian Redl410c4f22010-08-31 20:53:31 +00002429 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002430 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002431 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002432 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002433 Consumer, Visited);
2434 }
2435 }
2436 }
2437
2438 // Traverse using directives for qualified name lookup.
2439 if (QualifiedNameLookup) {
2440 ShadowContextRAII Shadow(Visited);
2441 DeclContext::udir_iterator I, E;
2442 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2443 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002444 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002445 }
2446 }
2447
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002448 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002449 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002450 if (!Record->hasDefinition())
2451 return;
2452
Douglas Gregor546be3c2009-12-30 17:04:44 +00002453 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2454 BEnd = Record->bases_end();
2455 B != BEnd; ++B) {
2456 QualType BaseType = B->getType();
2457
2458 // Don't look into dependent bases, because name lookup can't look
2459 // there anyway.
2460 if (BaseType->isDependentType())
2461 continue;
2462
2463 const RecordType *Record = BaseType->getAs<RecordType>();
2464 if (!Record)
2465 continue;
2466
2467 // FIXME: It would be nice to be able to determine whether referencing
2468 // a particular member would be ambiguous. For example, given
2469 //
2470 // struct A { int member; };
2471 // struct B { int member; };
2472 // struct C : A, B { };
2473 //
2474 // void f(C *c) { c->### }
2475 //
2476 // accessing 'member' would result in an ambiguity. However, we
2477 // could be smart enough to qualify the member with the base
2478 // class, e.g.,
2479 //
2480 // c->B::member
2481 //
2482 // or
2483 //
2484 // c->A::member
2485
2486 // Find results in this base class (and its bases).
2487 ShadowContextRAII Shadow(Visited);
2488 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002489 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002490 }
2491 }
2492
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002493 // Traverse the contexts of Objective-C classes.
2494 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2495 // Traverse categories.
2496 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2497 Category; Category = Category->getNextClassCategory()) {
2498 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002499 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2500 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002501 }
2502
2503 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002504 for (ObjCInterfaceDecl::all_protocol_iterator
2505 I = IFace->all_referenced_protocol_begin(),
2506 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002507 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002508 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2509 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002510 }
2511
2512 // Traverse the superclass.
2513 if (IFace->getSuperClass()) {
2514 ShadowContextRAII Shadow(Visited);
2515 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002516 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002517 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002518
2519 // If there is an implementation, traverse it. We do this to find
2520 // synthesized ivars.
2521 if (IFace->getImplementation()) {
2522 ShadowContextRAII Shadow(Visited);
2523 LookupVisibleDecls(IFace->getImplementation(), Result,
2524 QualifiedNameLookup, true, Consumer, Visited);
2525 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002526 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2527 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2528 E = Protocol->protocol_end(); I != E; ++I) {
2529 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002530 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2531 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002532 }
2533 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2534 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2535 E = Category->protocol_end(); I != E; ++I) {
2536 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002537 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2538 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002539 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002540
2541 // If there is an implementation, traverse it.
2542 if (Category->getImplementation()) {
2543 ShadowContextRAII Shadow(Visited);
2544 LookupVisibleDecls(Category->getImplementation(), Result,
2545 QualifiedNameLookup, true, Consumer, Visited);
2546 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002547 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002548}
2549
2550static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2551 UnqualUsingDirectiveSet &UDirs,
2552 VisibleDeclConsumer &Consumer,
2553 VisibleDeclsRecord &Visited) {
2554 if (!S)
2555 return;
2556
Douglas Gregor8071e422010-08-15 06:18:01 +00002557 if (!S->getEntity() ||
2558 (!S->getParent() &&
2559 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002560 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2561 // Walk through the declarations in this Scope.
2562 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2563 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002564 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor539c5c32010-01-07 00:31:29 +00002565 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002566 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002567 Visited.add(ND);
2568 }
2569 }
2570 }
2571
Douglas Gregor711be1e2010-03-15 14:33:29 +00002572 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002573 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002574 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002575 // Look into this scope's declaration context, along with any of its
2576 // parent lookup contexts (e.g., enclosing classes), up to the point
2577 // where we hit the context stored in the next outer scope.
2578 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002579 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor546be3c2009-12-30 17:04:44 +00002580
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002581 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002582 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002583 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2584 if (Method->isInstanceMethod()) {
2585 // For instance methods, look for ivars in the method's interface.
2586 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2587 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor62021192010-02-04 23:42:48 +00002588 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2589 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2590 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002591 }
2592
2593 // We've already performed all of the name lookup that we need
2594 // to for Objective-C methods; the next context will be the
2595 // outer scope.
2596 break;
2597 }
2598
Douglas Gregor546be3c2009-12-30 17:04:44 +00002599 if (Ctx->isFunctionOrMethod())
2600 continue;
2601
2602 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002603 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002604 }
2605 } else if (!S->getParent()) {
2606 // Look into the translation unit scope. We walk through the translation
2607 // unit's declaration context, because the Scope itself won't have all of
2608 // the declarations if we loaded a precompiled header.
2609 // FIXME: We would like the translation unit's Scope object to point to the
2610 // translation unit, so we don't need this special "if" branch. However,
2611 // doing so would force the normal C++ name-lookup code to look into the
2612 // translation unit decl when the IdentifierInfo chains would suffice.
2613 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002614 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002615 Entity = Result.getSema().Context.getTranslationUnitDecl();
2616 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002617 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002618 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002619
2620 if (Entity) {
2621 // Lookup visible declarations in any namespaces found by using
2622 // directives.
2623 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2624 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2625 for (; UI != UEnd; ++UI)
2626 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002627 Result, /*QualifiedNameLookup=*/false,
2628 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002629 }
2630
2631 // Lookup names in the parent scope.
2632 ShadowContextRAII Shadow(Visited);
2633 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2634}
2635
2636void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002637 VisibleDeclConsumer &Consumer,
2638 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002639 // Determine the set of using directives available during
2640 // unqualified name lookup.
2641 Scope *Initial = S;
2642 UnqualUsingDirectiveSet UDirs;
2643 if (getLangOptions().CPlusPlus) {
2644 // Find the first namespace or translation-unit scope.
2645 while (S && !isNamespaceOrTranslationUnitScope(S))
2646 S = S->getParent();
2647
2648 UDirs.visitScopeChain(Initial, S);
2649 }
2650 UDirs.done();
2651
2652 // Look for visible declarations.
2653 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2654 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002655 if (!IncludeGlobalScope)
2656 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002657 ShadowContextRAII Shadow(Visited);
2658 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2659}
2660
2661void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002662 VisibleDeclConsumer &Consumer,
2663 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002664 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2665 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002666 if (!IncludeGlobalScope)
2667 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002668 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002669 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2670 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002671}
2672
2673//----------------------------------------------------------------------------
2674// Typo correction
2675//----------------------------------------------------------------------------
2676
2677namespace {
2678class TypoCorrectionConsumer : public VisibleDeclConsumer {
2679 /// \brief The name written that is a typo in the source.
2680 llvm::StringRef Typo;
2681
2682 /// \brief The results found that have the smallest edit distance
2683 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00002684 ///
2685 /// The boolean value indicates whether there is a keyword with this name.
2686 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002687
2688 /// \brief The best edit distance found so far.
2689 unsigned BestEditDistance;
2690
2691public:
2692 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
Douglas Gregore24b5752010-10-14 20:34:08 +00002693 : Typo(Typo->getName()),
2694 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002695
Douglas Gregor0cc84042010-01-14 15:47:35 +00002696 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor95f42922010-10-14 22:11:03 +00002697 void FoundName(llvm::StringRef Name);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002698 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002699
Douglas Gregore24b5752010-10-14 20:34:08 +00002700 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2701 iterator begin() { return BestResults.begin(); }
2702 iterator end() { return BestResults.end(); }
2703 void erase(iterator I) { BestResults.erase(I); }
2704 unsigned size() const { return BestResults.size(); }
2705 bool empty() const { return BestResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002706
Douglas Gregor7b824e82010-10-15 13:35:25 +00002707 bool &operator[](llvm::StringRef Name) {
2708 return BestResults[Name];
2709 }
2710
Douglas Gregoraaf87162010-04-14 20:04:41 +00002711 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002712};
2713
2714}
2715
Douglas Gregor0cc84042010-01-14 15:47:35 +00002716void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2717 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002718 // Don't consider hidden names for typo correction.
2719 if (Hiding)
2720 return;
2721
2722 // Only consider entities with identifiers for names, ignoring
2723 // special names (constructors, overloaded operators, selectors,
2724 // etc.).
2725 IdentifierInfo *Name = ND->getIdentifier();
2726 if (!Name)
2727 return;
2728
Douglas Gregor95f42922010-10-14 22:11:03 +00002729 FoundName(Name->getName());
2730}
2731
2732void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002733 // Compute the edit distance between the typo and the name of this
2734 // entity. If this edit distance is not worse than the best edit
2735 // distance we've seen so far, add it to the list of results.
Douglas Gregor95f42922010-10-14 22:11:03 +00002736 unsigned ED = Typo.edit_distance(Name);
2737 if (ED == 0)
2738 return;
2739
Douglas Gregore24b5752010-10-14 20:34:08 +00002740 if (ED < BestEditDistance) {
2741 // This result is better than any we've seen before; clear out
2742 // the previous results.
2743 BestResults.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002744 BestEditDistance = ED;
Douglas Gregore24b5752010-10-14 20:34:08 +00002745 } else if (ED > BestEditDistance) {
2746 // This result is worse than the best results we've seen so far;
2747 // ignore it.
2748 return;
2749 }
Douglas Gregor95f42922010-10-14 22:11:03 +00002750
Douglas Gregore24b5752010-10-14 20:34:08 +00002751 // Add this name to the list of results. By not assigning a value, we
2752 // keep the current value if we've seen this name before (either as a
2753 // keyword or as a declaration), or get the default value (not a keyword)
2754 // if we haven't seen it before.
Douglas Gregor95f42922010-10-14 22:11:03 +00002755 (void)BestResults[Name];
Douglas Gregor546be3c2009-12-30 17:04:44 +00002756}
2757
Douglas Gregoraaf87162010-04-14 20:04:41 +00002758void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2759 llvm::StringRef Keyword) {
2760 // Compute the edit distance between the typo and this keyword.
2761 // If this edit distance is not worse than the best edit
2762 // distance we've seen so far, add it to the list of results.
2763 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregore24b5752010-10-14 20:34:08 +00002764 if (ED < BestEditDistance) {
2765 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002766 BestEditDistance = ED;
Douglas Gregore24b5752010-10-14 20:34:08 +00002767 } else if (ED > BestEditDistance) {
2768 // This result is worse than the best results we've seen so far;
2769 // ignore it.
2770 return;
2771 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00002772
Douglas Gregore24b5752010-10-14 20:34:08 +00002773 BestResults[Keyword] = true;
Douglas Gregoraaf87162010-04-14 20:04:41 +00002774}
2775
Douglas Gregor546be3c2009-12-30 17:04:44 +00002776/// \brief Try to "correct" a typo in the source code by finding
2777/// visible declarations whose names are similar to the name that was
2778/// present in the source code.
2779///
2780/// \param Res the \c LookupResult structure that contains the name
2781/// that was present in the source code along with the name-lookup
2782/// criteria used to search for the name. On success, this structure
2783/// will contain the results of name lookup.
2784///
2785/// \param S the scope in which name lookup occurs.
2786///
2787/// \param SS the nested-name-specifier that precedes the name we're
2788/// looking for, if present.
2789///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002790/// \param MemberContext if non-NULL, the context in which to look for
2791/// a member access expression.
2792///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002793/// \param EnteringContext whether we're entering the context described by
2794/// the nested-name-specifier SS.
2795///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002796/// \param CTC The context in which typo correction occurs, which impacts the
2797/// set of keywords permitted.
2798///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002799/// \param OPT when non-NULL, the search for visible declarations will
2800/// also walk the protocols in the qualified interfaces of \p OPT.
2801///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002802/// \returns the corrected name if the typo was corrected, otherwise returns an
2803/// empty \c DeclarationName. When a typo was corrected, the result structure
2804/// may contain the results of name lookup for the correct name or it may be
2805/// empty.
2806DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002807 DeclContext *MemberContext,
2808 bool EnteringContext,
2809 CorrectTypoContext CTC,
2810 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00002811 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002812 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002813
2814 // Provide a stop gap for files that are just seriously broken. Trying
2815 // to correct all typos can turn into a HUGE performance penalty, causing
2816 // some files to take minutes to get rejected by the parser.
2817 // FIXME: Is this the right solution?
2818 if (TyposCorrected == 20)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002819 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002820 ++TyposCorrected;
Ted Kremenek1dac3412010-01-06 00:23:04 +00002821
Douglas Gregor546be3c2009-12-30 17:04:44 +00002822 // We only attempt to correct typos for identifiers.
2823 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2824 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002825 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002826
2827 // If the scope specifier itself was invalid, don't try to correct
2828 // typos.
2829 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002830 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002831
2832 // Never try to correct typos during template deduction or
2833 // instantiation.
2834 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002835 return DeclarationName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002836
Douglas Gregor546be3c2009-12-30 17:04:44 +00002837 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002838
2839 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002840 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002841 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002842
2843 // Look in qualified interfaces.
2844 if (OPT) {
2845 for (ObjCObjectPointerType::qual_iterator
2846 I = OPT->qual_begin(), E = OPT->qual_end();
2847 I != E; ++I)
2848 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2849 }
2850 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002851 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2852 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002853 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002854
2855 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2856 } else {
Douglas Gregor95f42922010-10-14 22:11:03 +00002857 // For unqualified lookup, look through all of the names that we have
2858 // seen in this translation unit.
2859 for (IdentifierTable::iterator I = Context.Idents.begin(),
2860 IEnd = Context.Idents.end();
2861 I != IEnd; ++I)
2862 Consumer.FoundName(I->getKey());
2863
2864 // Walk through identifiers in external identifier sources.
2865 if (IdentifierInfoLookup *External
2866 = Context.Idents.getExternalIdentifierLookup()) {
2867 IdentifierIterator *Iter = External->getIdentifiers();
2868 do {
2869 llvm::StringRef Name = Iter->Next();
2870 if (Name.empty())
2871 break;
2872
2873 Consumer.FoundName(Name);
2874 } while (true);
2875 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002876 }
2877
Douglas Gregoraaf87162010-04-14 20:04:41 +00002878 // Add context-dependent keywords.
2879 bool WantTypeSpecifiers = false;
2880 bool WantExpressionKeywords = false;
2881 bool WantCXXNamedCasts = false;
2882 bool WantRemainingKeywords = false;
2883 switch (CTC) {
2884 case CTC_Unknown:
2885 WantTypeSpecifiers = true;
2886 WantExpressionKeywords = true;
2887 WantCXXNamedCasts = true;
2888 WantRemainingKeywords = true;
Douglas Gregor91f7ac72010-05-18 16:14:23 +00002889
2890 if (ObjCMethodDecl *Method = getCurMethodDecl())
2891 if (Method->getClassInterface() &&
2892 Method->getClassInterface()->getSuperClass())
2893 Consumer.addKeywordResult(Context, "super");
2894
Douglas Gregoraaf87162010-04-14 20:04:41 +00002895 break;
2896
2897 case CTC_NoKeywords:
2898 break;
2899
2900 case CTC_Type:
2901 WantTypeSpecifiers = true;
2902 break;
2903
2904 case CTC_ObjCMessageReceiver:
2905 Consumer.addKeywordResult(Context, "super");
2906 // Fall through to handle message receivers like expressions.
2907
2908 case CTC_Expression:
2909 if (getLangOptions().CPlusPlus)
2910 WantTypeSpecifiers = true;
2911 WantExpressionKeywords = true;
2912 // Fall through to get C++ named casts.
2913
2914 case CTC_CXXCasts:
2915 WantCXXNamedCasts = true;
2916 break;
2917
2918 case CTC_MemberLookup:
2919 if (getLangOptions().CPlusPlus)
2920 Consumer.addKeywordResult(Context, "template");
2921 break;
2922 }
2923
2924 if (WantTypeSpecifiers) {
2925 // Add type-specifier keywords to the set of results.
2926 const char *CTypeSpecs[] = {
2927 "char", "const", "double", "enum", "float", "int", "long", "short",
2928 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2929 "_Complex", "_Imaginary",
2930 // storage-specifiers as well
2931 "extern", "inline", "static", "typedef"
2932 };
2933
2934 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2935 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2936 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2937
2938 if (getLangOptions().C99)
2939 Consumer.addKeywordResult(Context, "restrict");
2940 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2941 Consumer.addKeywordResult(Context, "bool");
2942
2943 if (getLangOptions().CPlusPlus) {
2944 Consumer.addKeywordResult(Context, "class");
2945 Consumer.addKeywordResult(Context, "typename");
2946 Consumer.addKeywordResult(Context, "wchar_t");
2947
2948 if (getLangOptions().CPlusPlus0x) {
2949 Consumer.addKeywordResult(Context, "char16_t");
2950 Consumer.addKeywordResult(Context, "char32_t");
2951 Consumer.addKeywordResult(Context, "constexpr");
2952 Consumer.addKeywordResult(Context, "decltype");
2953 Consumer.addKeywordResult(Context, "thread_local");
2954 }
2955 }
2956
2957 if (getLangOptions().GNUMode)
2958 Consumer.addKeywordResult(Context, "typeof");
2959 }
2960
Douglas Gregord0785ea2010-05-18 16:30:22 +00002961 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00002962 Consumer.addKeywordResult(Context, "const_cast");
2963 Consumer.addKeywordResult(Context, "dynamic_cast");
2964 Consumer.addKeywordResult(Context, "reinterpret_cast");
2965 Consumer.addKeywordResult(Context, "static_cast");
2966 }
2967
2968 if (WantExpressionKeywords) {
2969 Consumer.addKeywordResult(Context, "sizeof");
2970 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2971 Consumer.addKeywordResult(Context, "false");
2972 Consumer.addKeywordResult(Context, "true");
2973 }
2974
2975 if (getLangOptions().CPlusPlus) {
2976 const char *CXXExprs[] = {
2977 "delete", "new", "operator", "throw", "typeid"
2978 };
2979 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2980 for (unsigned I = 0; I != NumCXXExprs; ++I)
2981 Consumer.addKeywordResult(Context, CXXExprs[I]);
2982
2983 if (isa<CXXMethodDecl>(CurContext) &&
2984 cast<CXXMethodDecl>(CurContext)->isInstance())
2985 Consumer.addKeywordResult(Context, "this");
2986
2987 if (getLangOptions().CPlusPlus0x) {
2988 Consumer.addKeywordResult(Context, "alignof");
2989 Consumer.addKeywordResult(Context, "nullptr");
2990 }
2991 }
2992 }
2993
2994 if (WantRemainingKeywords) {
2995 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2996 // Statements.
2997 const char *CStmts[] = {
2998 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2999 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3000 for (unsigned I = 0; I != NumCStmts; ++I)
3001 Consumer.addKeywordResult(Context, CStmts[I]);
3002
3003 if (getLangOptions().CPlusPlus) {
3004 Consumer.addKeywordResult(Context, "catch");
3005 Consumer.addKeywordResult(Context, "try");
3006 }
3007
3008 if (S && S->getBreakParent())
3009 Consumer.addKeywordResult(Context, "break");
3010
3011 if (S && S->getContinueParent())
3012 Consumer.addKeywordResult(Context, "continue");
3013
John McCall781472f2010-08-25 08:40:02 +00003014 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003015 Consumer.addKeywordResult(Context, "case");
3016 Consumer.addKeywordResult(Context, "default");
3017 }
3018 } else {
3019 if (getLangOptions().CPlusPlus) {
3020 Consumer.addKeywordResult(Context, "namespace");
3021 Consumer.addKeywordResult(Context, "template");
3022 }
3023
3024 if (S && S->isClassScope()) {
3025 Consumer.addKeywordResult(Context, "explicit");
3026 Consumer.addKeywordResult(Context, "friend");
3027 Consumer.addKeywordResult(Context, "mutable");
3028 Consumer.addKeywordResult(Context, "private");
3029 Consumer.addKeywordResult(Context, "protected");
3030 Consumer.addKeywordResult(Context, "public");
3031 Consumer.addKeywordResult(Context, "virtual");
3032 }
3033 }
3034
3035 if (getLangOptions().CPlusPlus) {
3036 Consumer.addKeywordResult(Context, "using");
3037
3038 if (getLangOptions().CPlusPlus0x)
3039 Consumer.addKeywordResult(Context, "static_assert");
3040 }
3041 }
3042
3043 // If we haven't found anything, we're done.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003044 if (Consumer.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003045 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003046
Douglas Gregore24b5752010-10-14 20:34:08 +00003047 // Make sure that the user typed at least 3 characters for each correction
3048 // made. Otherwise, we don't even both looking at the results.
3049 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor95f42922010-10-14 22:11:03 +00003050 if (ED > 0 && Typo->getName().size() / ED < 3)
Douglas Gregore24b5752010-10-14 20:34:08 +00003051 return DeclarationName();
3052
3053 // Weed out any names that could not be found by name lookup.
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003054 bool LastLookupWasAccepted = false;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003055 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3056 IEnd = Consumer.end();
Douglas Gregore24b5752010-10-14 20:34:08 +00003057 I != IEnd; /* Increment in loop. */) {
3058 // Keywords are always found.
3059 if (I->second) {
3060 ++I;
3061 continue;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003062 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003063
3064 // Perform name lookup on this name.
3065 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
3066 Res.suppressDiagnostics();
3067 Res.clear();
3068 Res.setLookupName(Name);
3069 if (MemberContext)
3070 LookupQualifiedName(Res, MemberContext);
3071 else {
3072 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3073 EnteringContext);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003074
Douglas Gregore24b5752010-10-14 20:34:08 +00003075 // Fake ivar lookup; this should really be part of
3076 // LookupParsedName.
3077 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
3078 if (Method->isInstanceMethod() && Method->getClassInterface() &&
3079 (Res.empty() ||
3080 (Res.isSingleResult() &&
3081 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
3082 ObjCInterfaceDecl *ClassDeclared = 0;
3083 if (ObjCIvarDecl *IV
3084 = Method->getClassInterface()->lookupInstanceVariable(Name,
3085 ClassDeclared)) {
3086 Res.clear();
3087 Res.addDecl(IV);
3088 Res.resolveKind();
Douglas Gregord0785ea2010-05-18 16:30:22 +00003089 }
3090 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003091 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003092 }
3093
3094 switch (Res.getResultKind()) {
3095 case LookupResult::NotFound:
3096 case LookupResult::NotFoundInCurrentInstantiation:
3097 case LookupResult::Ambiguous:
3098 // We didn't find this name in our scope, or didn't like what we found;
3099 // ignore it.
3100 Res.suppressDiagnostics();
3101 {
3102 TypoCorrectionConsumer::iterator Next = I;
3103 ++Next;
3104 Consumer.erase(I);
3105 I = Next;
3106 }
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003107 LastLookupWasAccepted = false;
Douglas Gregore24b5752010-10-14 20:34:08 +00003108 break;
3109
3110 case LookupResult::Found:
3111 case LookupResult::FoundOverloaded:
3112 case LookupResult::FoundUnresolvedValue:
3113 ++I;
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003114 LastLookupWasAccepted = false;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003115 break;
Douglas Gregore24b5752010-10-14 20:34:08 +00003116 }
3117
3118 if (Res.isAmbiguous()) {
3119 // We don't deal with ambiguities.
3120 Res.suppressDiagnostics();
3121 Res.clear();
3122 return DeclarationName();
3123 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003124 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003125
Douglas Gregore24b5752010-10-14 20:34:08 +00003126 // If only a single name remains, return that result.
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003127 if (Consumer.size() == 1) {
3128 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
3129 if (!LastLookupWasAccepted) {
3130 // Perform name lookup on this name.
3131 Res.suppressDiagnostics();
3132 Res.clear();
3133 Res.setLookupName(Name);
3134 if (MemberContext)
3135 LookupQualifiedName(Res, MemberContext);
3136 else {
3137 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3138 EnteringContext);
3139
3140 // Fake ivar lookup; this should really be part of
3141 // LookupParsedName.
3142 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
3143 if (Method->isInstanceMethod() && Method->getClassInterface() &&
3144 (Res.empty() ||
3145 (Res.isSingleResult() &&
3146 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
3147 ObjCInterfaceDecl *ClassDeclared = 0;
3148 if (ObjCIvarDecl *IV
3149 = Method->getClassInterface()->lookupInstanceVariable(Name,
3150 ClassDeclared)) {
3151 Res.clear();
3152 Res.addDecl(IV);
3153 Res.resolveKind();
3154 }
3155 }
3156 }
3157 }
3158 }
3159
Douglas Gregore24b5752010-10-14 20:34:08 +00003160 return &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003161 }
Douglas Gregor7b824e82010-10-15 13:35:25 +00003162 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
3163 && Consumer["super"]) {
3164 // Prefix 'super' when we're completing in a message-receiver
3165 // context.
3166 Res.suppressDiagnostics();
3167 Res.clear();
3168 return &Context.Idents.get("super");
3169 }
3170
Douglas Gregore24b5752010-10-14 20:34:08 +00003171 Res.suppressDiagnostics();
3172 Res.setLookupName(Typo);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003173 Res.clear();
Douglas Gregor931f98a2010-04-14 17:09:22 +00003174 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003175}