blob: 306e95a497e8baabcbc8eb6bbea3c8e8f8eee0c9 [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"
John McCall6e247262009-10-10 05:48:19 +000034#include "llvm/Support/ErrorHandling.h"
Douglas Gregor546be3c2009-12-30 17:04:44 +000035#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000036#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000037#include <vector>
38#include <iterator>
39#include <utility>
40#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000041
42using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000043using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000044
John McCalld7be78a2009-11-10 07:01:13 +000045namespace {
46 class UnqualUsingEntry {
47 const DeclContext *Nominated;
48 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000049
John McCalld7be78a2009-11-10 07:01:13 +000050 public:
51 UnqualUsingEntry(const DeclContext *Nominated,
52 const DeclContext *CommonAncestor)
53 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
54 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000055
John McCalld7be78a2009-11-10 07:01:13 +000056 const DeclContext *getCommonAncestor() const {
57 return CommonAncestor;
58 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000059
John McCalld7be78a2009-11-10 07:01:13 +000060 const DeclContext *getNominatedNamespace() const {
61 return Nominated;
62 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000063
John McCalld7be78a2009-11-10 07:01:13 +000064 // Sort by the pointer value of the common ancestor.
65 struct Comparator {
66 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
67 return L.getCommonAncestor() < R.getCommonAncestor();
68 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000069
John McCalld7be78a2009-11-10 07:01:13 +000070 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
71 return E.getCommonAncestor() < DC;
72 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000073
John McCalld7be78a2009-11-10 07:01:13 +000074 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
75 return DC < E.getCommonAncestor();
76 }
77 };
78 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000079
John McCalld7be78a2009-11-10 07:01:13 +000080 /// A collection of using directives, as used by C++ unqualified
81 /// lookup.
82 class UnqualUsingDirectiveSet {
83 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000084
John McCalld7be78a2009-11-10 07:01:13 +000085 ListTy list;
86 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000087
John McCalld7be78a2009-11-10 07:01:13 +000088 public:
89 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000090
John McCalld7be78a2009-11-10 07:01:13 +000091 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
92 // C++ [namespace.udir]p1:
93 // During unqualified name lookup, the names appear as if they
94 // were declared in the nearest enclosing namespace which contains
95 // both the using-directive and the nominated namespace.
96 DeclContext *InnermostFileDC
97 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
98 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +000099
John McCalld7be78a2009-11-10 07:01:13 +0000100 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +0000101 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
102 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
103 visit(Ctx, EffectiveDC);
104 } else {
105 Scope::udir_iterator I = S->using_directives_begin(),
106 End = S->using_directives_end();
107
108 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000109 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000110 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000111 }
112 }
John McCalld7be78a2009-11-10 07:01:13 +0000113
114 // Visits a context and collect all of its using directives
115 // recursively. Treats all using directives as if they were
116 // declared in the context.
117 //
118 // A given context is only every visited once, so it is important
119 // that contexts be visited from the inside out in order to get
120 // the effective DCs right.
121 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
122 if (!visited.insert(DC))
123 return;
124
125 addUsingDirectives(DC, EffectiveDC);
126 }
127
128 // Visits a using directive and collects all of its using
129 // directives recursively. Treats all using directives as if they
130 // were declared in the effective DC.
131 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
132 DeclContext *NS = UD->getNominatedNamespace();
133 if (!visited.insert(NS))
134 return;
135
136 addUsingDirective(UD, EffectiveDC);
137 addUsingDirectives(NS, EffectiveDC);
138 }
139
140 // Adds all the using directives in a context (and those nominated
141 // by its using directives, transitively) as if they appeared in
142 // the given effective context.
143 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
144 llvm::SmallVector<DeclContext*,4> queue;
145 while (true) {
146 DeclContext::udir_iterator I, End;
147 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
148 UsingDirectiveDecl *UD = *I;
149 DeclContext *NS = UD->getNominatedNamespace();
150 if (visited.insert(NS)) {
151 addUsingDirective(UD, EffectiveDC);
152 queue.push_back(NS);
153 }
154 }
155
156 if (queue.empty())
157 return;
158
159 DC = queue.back();
160 queue.pop_back();
161 }
162 }
163
164 // Add a using directive as if it had been declared in the given
165 // context. This helps implement C++ [namespace.udir]p3:
166 // The using-directive is transitive: if a scope contains a
167 // using-directive that nominates a second namespace that itself
168 // contains using-directives, the effect is as if the
169 // using-directives from the second namespace also appeared in
170 // the first.
171 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
172 // Find the common ancestor between the effective context and
173 // the nominated namespace.
174 DeclContext *Common = UD->getNominatedNamespace();
175 while (!Common->Encloses(EffectiveDC))
176 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000177 Common = Common->getPrimaryContext();
John McCalld7be78a2009-11-10 07:01:13 +0000178
179 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
180 }
181
182 void done() {
183 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
184 }
185
186 typedef ListTy::iterator iterator;
187 typedef ListTy::const_iterator const_iterator;
188
189 iterator begin() { return list.begin(); }
190 iterator end() { return list.end(); }
191 const_iterator begin() const { return list.begin(); }
192 const_iterator end() const { return list.end(); }
193
194 std::pair<const_iterator,const_iterator>
195 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000196 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000197 UnqualUsingEntry::Comparator());
198 }
199 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000200}
201
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000202// Retrieve the set of identifier namespaces that correspond to a
203// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000204static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
205 bool CPlusPlus,
206 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000207 unsigned IDNS = 0;
208 switch (NameKind) {
209 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000210 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000211 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000212 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000213 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCall1d7c5282009-12-18 10:40:03 +0000214 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
215 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000216 break;
217
John McCall76d32642010-04-24 01:30:58 +0000218 case Sema::LookupOperatorName:
219 // Operator lookup is its own crazy thing; it is not the same
220 // as (e.g.) looking up an operator name for redeclaration.
221 assert(!Redeclaration && "cannot do redeclaration operator lookup");
222 IDNS = Decl::IDNS_NonMemberOperator;
223 break;
224
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000225 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000226 if (CPlusPlus) {
227 IDNS = Decl::IDNS_Type;
228
229 // When looking for a redeclaration of a tag name, we add:
230 // 1) TagFriend to find undeclared friend decls
231 // 2) Namespace because they can't "overload" with tag decls.
232 // 3) Tag because it includes class templates, which can't
233 // "overload" with tag decls.
234 if (Redeclaration)
235 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
236 } else {
237 IDNS = Decl::IDNS_Tag;
238 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000239 break;
240
241 case Sema::LookupMemberName:
242 IDNS = Decl::IDNS_Member;
243 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000244 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000245 break;
246
247 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000248 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
249 break;
250
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000251 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000252 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000253 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000254
John McCall9f54ad42009-12-10 09:41:52 +0000255 case Sema::LookupUsingDeclName:
256 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
257 | Decl::IDNS_Member | Decl::IDNS_Using;
258 break;
259
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000260 case Sema::LookupObjCProtocolName:
261 IDNS = Decl::IDNS_ObjCProtocol;
262 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000263
264 case Sema::LookupAnyName:
265 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
266 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
267 | Decl::IDNS_Type;
268 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000269 }
270 return IDNS;
271}
272
John McCall1d7c5282009-12-18 10:40:03 +0000273void LookupResult::configure() {
274 IDNS = getIDNS(LookupKind,
275 SemaRef.getLangOptions().CPlusPlus,
276 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000277
278 // If we're looking for one of the allocation or deallocation
279 // operators, make sure that the implicitly-declared new and delete
280 // operators can be found.
281 if (!isForRedeclaration()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000282 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000283 case OO_New:
284 case OO_Delete:
285 case OO_Array_New:
286 case OO_Array_Delete:
287 SemaRef.DeclareGlobalNewDelete();
288 break;
289
290 default:
291 break;
292 }
293 }
John McCall1d7c5282009-12-18 10:40:03 +0000294}
295
John McCall2a7fb272010-08-25 05:32:35 +0000296#ifndef NDEBUG
297void LookupResult::sanity() const {
298 assert(ResultKind != NotFound || Decls.size() == 0);
299 assert(ResultKind != Found || Decls.size() == 1);
300 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
301 (Decls.size() == 1 &&
302 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
303 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
304 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
305 (Decls.size() == 1 && Ambiguity == AmbiguousBaseSubobjects));
306 assert((Paths != NULL) == (ResultKind == Ambiguous &&
307 (Ambiguity == AmbiguousBaseSubobjectTypes ||
308 Ambiguity == AmbiguousBaseSubobjects)));
309}
310#endif
311
John McCallf36e02d2009-10-09 21:13:30 +0000312// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000313void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000314 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000315}
316
John McCall7453ed42009-11-22 00:44:51 +0000317/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000318void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000319 unsigned N = Decls.size();
John McCall9f54ad42009-12-10 09:41:52 +0000320
John McCallf36e02d2009-10-09 21:13:30 +0000321 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000322 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000323 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000324 return;
325 }
326
John McCall7453ed42009-11-22 00:44:51 +0000327 // If there's a single decl, we need to examine it to decide what
328 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000329 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000330 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
331 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000332 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000333 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000334 ResultKind = FoundUnresolvedValue;
335 return;
336 }
John McCallf36e02d2009-10-09 21:13:30 +0000337
John McCall6e247262009-10-10 05:48:19 +0000338 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000339 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000340
John McCallf36e02d2009-10-09 21:13:30 +0000341 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000342 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
343
John McCallf36e02d2009-10-09 21:13:30 +0000344 bool Ambiguous = false;
345 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000346 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000347
348 unsigned UniqueTagIndex = 0;
349
350 unsigned I = 0;
351 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000352 NamedDecl *D = Decls[I]->getUnderlyingDecl();
353 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000354
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000355 // Redeclarations of types via typedef can occur both within a scope
356 // and, through using declarations and directives, across scopes. There is
357 // no ambiguity if they all refer to the same type, so unique based on the
358 // canonical type.
359 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
360 if (!TD->getDeclContext()->isRecord()) {
361 QualType T = SemaRef.Context.getTypeDeclType(TD);
362 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
363 // The type is not unique; pull something off the back and continue
364 // at this index.
365 Decls[I] = Decls[--N];
366 continue;
367 }
368 }
369 }
370
John McCall314be4e2009-11-17 07:50:12 +0000371 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000372 // If it's not unique, pull something off the back (and
373 // continue at this index).
374 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000375 continue;
376 }
377
378 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000379
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000380 if (isa<UnresolvedUsingValueDecl>(D)) {
381 HasUnresolved = true;
382 } else if (isa<TagDecl>(D)) {
383 if (HasTag)
384 Ambiguous = true;
385 UniqueTagIndex = I;
386 HasTag = true;
387 } else if (isa<FunctionTemplateDecl>(D)) {
388 HasFunction = true;
389 HasFunctionTemplate = true;
390 } else if (isa<FunctionDecl>(D)) {
391 HasFunction = true;
392 } else {
393 if (HasNonFunction)
394 Ambiguous = true;
395 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000396 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000397 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000398 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000399
John McCallf36e02d2009-10-09 21:13:30 +0000400 // C++ [basic.scope.hiding]p2:
401 // A class name or enumeration name can be hidden by the name of
402 // an object, function, or enumerator declared in the same
403 // scope. If a class or enumeration name and an object, function,
404 // or enumerator are declared in the same scope (in any order)
405 // with the same name, the class or enumeration name is hidden
406 // wherever the object, function, or enumerator name is visible.
407 // But it's still an error if there are distinct tag types found,
408 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000409 if (HideTags && HasTag && !Ambiguous &&
410 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000411 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000412
John McCallf36e02d2009-10-09 21:13:30 +0000413 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000414
John McCallfda8e122009-12-03 00:58:24 +0000415 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000416 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000417
John McCallf36e02d2009-10-09 21:13:30 +0000418 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000419 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000420 else if (HasUnresolved)
421 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000422 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000423 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000424 else
John McCalla24dc2e2009-11-17 02:14:36 +0000425 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000426}
427
John McCall7d384dd2009-11-18 07:57:50 +0000428void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000429 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000430 DeclContext::lookup_iterator DI, DE;
431 for (I = P.begin(), E = P.end(); I != E; ++I)
432 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
433 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000434}
435
John McCall7d384dd2009-11-18 07:57:50 +0000436void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000437 Paths = new CXXBasePaths;
438 Paths->swap(P);
439 addDeclsFromBasePaths(*Paths);
440 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000441 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000442}
443
John McCall7d384dd2009-11-18 07:57:50 +0000444void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000445 Paths = new CXXBasePaths;
446 Paths->swap(P);
447 addDeclsFromBasePaths(*Paths);
448 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000449 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000450}
451
John McCall7d384dd2009-11-18 07:57:50 +0000452void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000453 Out << Decls.size() << " result(s)";
454 if (isAmbiguous()) Out << ", ambiguous";
455 if (Paths) Out << ", base paths present";
456
457 for (iterator I = begin(), E = end(); I != E; ++I) {
458 Out << "\n";
459 (*I)->print(Out, 2);
460 }
461}
462
Douglas Gregor85910982010-02-12 05:48:04 +0000463/// \brief Lookup a builtin function, when name lookup would otherwise
464/// fail.
465static bool LookupBuiltin(Sema &S, LookupResult &R) {
466 Sema::LookupNameKind NameKind = R.getLookupKind();
467
468 // If we didn't find a use of this identifier, and if the identifier
469 // corresponds to a compiler builtin, create the decl object for the builtin
470 // now, injecting it into translation unit scope, and return it.
471 if (NameKind == Sema::LookupOrdinaryName ||
472 NameKind == Sema::LookupRedeclarationWithLinkage) {
473 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
474 if (II) {
475 // If this is a builtin on this (or all) targets, create the decl.
476 if (unsigned BuiltinID = II->getBuiltinID()) {
477 // In C++, we don't have any predefined library functions like
478 // 'malloc'. Instead, we'll just error.
479 if (S.getLangOptions().CPlusPlus &&
480 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
481 return false;
482
483 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
484 S.TUScope, R.isForRedeclaration(),
485 R.getNameLoc());
486 if (D)
487 R.addDecl(D);
488 return (D != NULL);
489 }
490 }
491 }
492
493 return false;
494}
495
Douglas Gregor4923aa22010-07-02 20:37:36 +0000496/// \brief Determine whether we can declare a special member function within
497/// the class at this point.
498static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
499 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000500 // Don't do it if the class is invalid.
501 if (Class->isInvalidDecl())
502 return false;
503
Douglas Gregor4923aa22010-07-02 20:37:36 +0000504 // We need to have a definition for the class.
505 if (!Class->getDefinition() || Class->isDependentContext())
506 return false;
507
508 // We can't be in the middle of defining the class.
509 if (const RecordType *RecordTy
510 = Context.getTypeDeclType(Class)->getAs<RecordType>())
511 return !RecordTy->isBeingDefined();
512
513 return false;
514}
515
516void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000517 if (!CanDeclareSpecialMemberFunction(Context, Class))
518 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000519
520 // If the default constructor has not yet been declared, do so now.
521 if (!Class->hasDeclaredDefaultConstructor())
522 DeclareImplicitDefaultConstructor(Class);
Douglas Gregor22584312010-07-02 23:41:54 +0000523
524 // If the copy constructor has not yet been declared, do so now.
525 if (!Class->hasDeclaredCopyConstructor())
526 DeclareImplicitCopyConstructor(Class);
527
Douglas Gregora376d102010-07-02 21:50:04 +0000528 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000529 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000530 DeclareImplicitCopyAssignment(Class);
531
Douglas Gregor4923aa22010-07-02 20:37:36 +0000532 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000533 if (!Class->hasDeclaredDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +0000534 DeclareImplicitDestructor(Class);
535}
536
Douglas Gregora376d102010-07-02 21:50:04 +0000537/// \brief Determine whether this is the name of an implicitly-declared
538/// special member function.
539static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
540 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000541 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000542 case DeclarationName::CXXDestructorName:
543 return true;
544
545 case DeclarationName::CXXOperatorName:
546 return Name.getCXXOverloadedOperator() == OO_Equal;
547
548 default:
549 break;
550 }
551
552 return false;
553}
554
555/// \brief If there are any implicit member functions with the given name
556/// that need to be declared in the given declaration context, do so.
557static void DeclareImplicitMemberFunctionsWithName(Sema &S,
558 DeclarationName Name,
559 const DeclContext *DC) {
560 if (!DC)
561 return;
562
563 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000564 case DeclarationName::CXXConstructorName:
565 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000566 if (Record->getDefinition() &&
567 CanDeclareSpecialMemberFunction(S.Context, Record)) {
568 if (!Record->hasDeclaredDefaultConstructor())
569 S.DeclareImplicitDefaultConstructor(
570 const_cast<CXXRecordDecl *>(Record));
571 if (!Record->hasDeclaredCopyConstructor())
572 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
573 }
Douglas Gregor22584312010-07-02 23:41:54 +0000574 break;
575
Douglas Gregora376d102010-07-02 21:50:04 +0000576 case DeclarationName::CXXDestructorName:
577 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
578 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
579 CanDeclareSpecialMemberFunction(S.Context, Record))
580 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000581 break;
582
583 case DeclarationName::CXXOperatorName:
584 if (Name.getCXXOverloadedOperator() != OO_Equal)
585 break;
586
587 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
588 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
589 CanDeclareSpecialMemberFunction(S.Context, Record))
590 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
591 break;
592
593 default:
594 break;
595 }
596}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000597
John McCallf36e02d2009-10-09 21:13:30 +0000598// Adds all qualifying matches for a name within a decl context to the
599// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000600static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000601 bool Found = false;
602
Douglas Gregor4923aa22010-07-02 20:37:36 +0000603 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000604 if (S.getLangOptions().CPlusPlus)
605 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000606
607 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000608 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000609 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000610 NamedDecl *D = *I;
611 if (R.isAcceptableDecl(D)) {
612 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000613 Found = true;
614 }
615 }
John McCallf36e02d2009-10-09 21:13:30 +0000616
Douglas Gregor85910982010-02-12 05:48:04 +0000617 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
618 return true;
619
Douglas Gregor48026d22010-01-11 18:40:55 +0000620 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000621 != DeclarationName::CXXConversionFunctionName ||
622 R.getLookupName().getCXXNameType()->isDependentType() ||
623 !isa<CXXRecordDecl>(DC))
624 return Found;
625
626 // C++ [temp.mem]p6:
627 // A specialization of a conversion function template is not found by
628 // name lookup. Instead, any conversion function templates visible in the
629 // context of the use are considered. [...]
630 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
631 if (!Record->isDefinition())
632 return Found;
633
634 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
635 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
636 UEnd = Unresolved->end(); U != UEnd; ++U) {
637 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
638 if (!ConvTemplate)
639 continue;
640
641 // When we're performing lookup for the purposes of redeclaration, just
642 // add the conversion function template. When we deduce template
643 // arguments for specializations, we'll end up unifying the return
644 // type of the new declaration with the type of the function template.
645 if (R.isForRedeclaration()) {
646 R.addDecl(ConvTemplate);
647 Found = true;
648 continue;
649 }
650
Douglas Gregor48026d22010-01-11 18:40:55 +0000651 // C++ [temp.mem]p6:
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000652 // [...] For each such operator, if argument deduction succeeds
653 // (14.9.2.3), the resulting specialization is used as if found by
654 // name lookup.
655 //
656 // When referencing a conversion function for any purpose other than
657 // a redeclaration (such that we'll be building an expression with the
658 // result), perform template argument deduction and place the
659 // specialization into the result set. We do this to avoid forcing all
660 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000661 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000662 FunctionDecl *Specialization = 0;
663
664 const FunctionProtoType *ConvProto
665 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
666 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000667
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000668 // Compute the type of the function that we would expect the conversion
669 // function to have, if it were to match the name given.
670 // FIXME: Calling convention!
Rafael Espindola264ba482010-03-30 20:24:48 +0000671 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000672 QualType ExpectedType
673 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
674 0, 0, ConvProto->isVariadic(),
675 ConvProto->getTypeQuals(),
676 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000677 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000678
679 // Perform template argument deduction against the type that we would
680 // expect the function to have.
681 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
682 Specialization, Info)
683 == Sema::TDK_Success) {
684 R.addDecl(Specialization);
685 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000686 }
687 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000688
John McCallf36e02d2009-10-09 21:13:30 +0000689 return Found;
690}
691
John McCalld7be78a2009-11-10 07:01:13 +0000692// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000693static bool
Douglas Gregor85910982010-02-12 05:48:04 +0000694CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
695 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000696
697 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
698
John McCalld7be78a2009-11-10 07:01:13 +0000699 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000700 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000701
John McCalld7be78a2009-11-10 07:01:13 +0000702 // Perform direct name lookup into the namespaces nominated by the
703 // using directives whose common ancestor is this namespace.
704 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
705 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000706
John McCalld7be78a2009-11-10 07:01:13 +0000707 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000708 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000709 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000710
711 R.resolveKind();
712
713 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000714}
715
716static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000717 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000718 return Ctx->isFileContext();
719 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000720}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000721
Douglas Gregor711be1e2010-03-15 14:33:29 +0000722// Find the next outer declaration context from this scope. This
723// routine actually returns the semantic outer context, which may
724// differ from the lexical context (encoded directly in the Scope
725// stack) when we are parsing a member of a class template. In this
726// case, the second element of the pair will be true, to indicate that
727// name lookup should continue searching in this semantic context when
728// it leaves the current template parameter scope.
729static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
730 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
731 DeclContext *Lexical = 0;
732 for (Scope *OuterS = S->getParent(); OuterS;
733 OuterS = OuterS->getParent()) {
734 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000735 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000736 break;
737 }
738 }
739
740 // C++ [temp.local]p8:
741 // In the definition of a member of a class template that appears
742 // outside of the namespace containing the class template
743 // definition, the name of a template-parameter hides the name of
744 // a member of this namespace.
745 //
746 // Example:
747 //
748 // namespace N {
749 // class C { };
750 //
751 // template<class T> class B {
752 // void f(T);
753 // };
754 // }
755 //
756 // template<class C> void N::B<C>::f(C) {
757 // C b; // C is the template parameter, not N::C
758 // }
759 //
760 // In this example, the lexical context we return is the
761 // TranslationUnit, while the semantic context is the namespace N.
762 if (!Lexical || !DC || !S->getParent() ||
763 !S->getParent()->isTemplateParamScope())
764 return std::make_pair(Lexical, false);
765
766 // Find the outermost template parameter scope.
767 // For the example, this is the scope for the template parameters of
768 // template<class C>.
769 Scope *OutermostTemplateScope = S->getParent();
770 while (OutermostTemplateScope->getParent() &&
771 OutermostTemplateScope->getParent()->isTemplateParamScope())
772 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregore942bbe2009-09-10 16:57:35 +0000773
Douglas Gregor711be1e2010-03-15 14:33:29 +0000774 // Find the namespace context in which the original scope occurs. In
775 // the example, this is namespace N.
776 DeclContext *Semantic = DC;
777 while (!Semantic->isFileContext())
778 Semantic = Semantic->getParent();
779
780 // Find the declaration context just outside of the template
781 // parameter scope. This is the context in which the template is
782 // being lexically declaration (a namespace context). In the
783 // example, this is the global scope.
784 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
785 Lexical->Encloses(Semantic))
786 return std::make_pair(Semantic, true);
787
788 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000789}
790
John McCalla24dc2e2009-11-17 02:14:36 +0000791bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000792 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000793
794 DeclarationName Name = R.getLookupName();
795
Douglas Gregora376d102010-07-02 21:50:04 +0000796 // If this is the name of an implicitly-declared special member function,
797 // go through the scope stack to implicitly declare
798 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
799 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
800 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
801 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
802 }
803
804 // Implicitly declare member functions with the name we're looking for, if in
805 // fact we are in a scope where it matters.
806
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000807 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000808 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000809 I = IdResolver.begin(Name),
810 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000811
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000812 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000813 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000814 // ...During unqualified name lookup (3.4.1), the names appear as if
815 // they were declared in the nearest enclosing namespace which contains
816 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000817 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000818 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000819 //
820 // For example:
821 // namespace A { int i; }
822 // void foo() {
823 // int i;
824 // {
825 // using namespace A;
826 // ++i; // finds local 'i', A::i appears at global scope
827 // }
828 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000829 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000830 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000831 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000832 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
833
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000834 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000835 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000836 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000837 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000838 Found = true;
839 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000840 }
841 }
John McCallf36e02d2009-10-09 21:13:30 +0000842 if (Found) {
843 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000844 if (S->isClassScope())
845 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
846 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000847 return true;
848 }
849
Douglas Gregor711be1e2010-03-15 14:33:29 +0000850 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
851 S->getParent() && !S->getParent()->isTemplateParamScope()) {
852 // We've just searched the last template parameter scope and
853 // found nothing, so look into the the contexts between the
854 // lexical and semantic declaration contexts returned by
855 // findOuterContext(). This implements the name lookup behavior
856 // of C++ [temp.local]p8.
857 Ctx = OutsideOfTemplateParamDC;
858 OutsideOfTemplateParamDC = 0;
859 }
860
861 if (Ctx) {
862 DeclContext *OuterCtx;
863 bool SearchAfterTemplateScope;
864 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
865 if (SearchAfterTemplateScope)
866 OutsideOfTemplateParamDC = OuterCtx;
867
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000868 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000869 // We do not directly look into transparent contexts, since
870 // those entities will be found in the nearest enclosing
871 // non-transparent context.
872 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000873 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000874
875 // We do not look directly into function or method contexts,
876 // since all of the local variables and parameters of the
877 // function/method are present within the Scope.
878 if (Ctx->isFunctionOrMethod()) {
879 // If we have an Objective-C instance method, look for ivars
880 // in the corresponding interface.
881 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
882 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
883 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
884 ObjCInterfaceDecl *ClassDeclared;
885 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
886 Name.getAsIdentifierInfo(),
887 ClassDeclared)) {
888 if (R.isAcceptableDecl(Ivar)) {
889 R.addDecl(Ivar);
890 R.resolveKind();
891 return true;
892 }
893 }
894 }
895 }
896
897 continue;
898 }
899
Douglas Gregore942bbe2009-09-10 16:57:35 +0000900 // Perform qualified name lookup into this context.
901 // FIXME: In some cases, we know that every name that could be found by
902 // this qualified name lookup will also be on the identifier chain. For
903 // example, inside a class without any base classes, we never need to
904 // perform qualified lookup because all of the members are on top of the
905 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000906 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000907 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000908 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000909 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000910 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000911
John McCalld7be78a2009-11-10 07:01:13 +0000912 // Stop if we ran out of scopes.
913 // FIXME: This really, really shouldn't be happening.
914 if (!S) return false;
915
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000916 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000917 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000918 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000919 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
920 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000921
John McCalld7be78a2009-11-10 07:01:13 +0000922 UnqualUsingDirectiveSet UDirs;
923 UDirs.visitScopeChain(Initial, S);
924 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000925
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000926 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000927 // Unqualified name lookup in C++ requires looking into scopes
928 // that aren't strictly lexical, and therefore we walk through the
929 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000930
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000931 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000932 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000933 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000934 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000935 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000936 // We found something. Look for anything else in our scope
937 // with this same name and in an acceptable identifier
938 // namespace, so that we can construct an overload set if we
939 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000940 Found = true;
941 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000942 }
943 }
944
Douglas Gregor00b4b032010-05-14 04:53:42 +0000945 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000946 R.resolveKind();
947 return true;
948 }
949
Douglas Gregor00b4b032010-05-14 04:53:42 +0000950 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
951 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
952 S->getParent() && !S->getParent()->isTemplateParamScope()) {
953 // We've just searched the last template parameter scope and
954 // found nothing, so look into the the contexts between the
955 // lexical and semantic declaration contexts returned by
956 // findOuterContext(). This implements the name lookup behavior
957 // of C++ [temp.local]p8.
958 Ctx = OutsideOfTemplateParamDC;
959 OutsideOfTemplateParamDC = 0;
960 }
961
962 if (Ctx) {
963 DeclContext *OuterCtx;
964 bool SearchAfterTemplateScope;
965 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
966 if (SearchAfterTemplateScope)
967 OutsideOfTemplateParamDC = OuterCtx;
968
969 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
970 // We do not directly look into transparent contexts, since
971 // those entities will be found in the nearest enclosing
972 // non-transparent context.
973 if (Ctx->isTransparentContext())
974 continue;
975
976 // If we have a context, and it's not a context stashed in the
977 // template parameter scope for an out-of-line definition, also
978 // look into that context.
979 if (!(Found && S && S->isTemplateParamScope())) {
980 assert(Ctx->isFileContext() &&
981 "We should have been looking only at file context here already.");
982
983 // Look into context considering using-directives.
984 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
985 Found = true;
986 }
987
988 if (Found) {
989 R.resolveKind();
990 return true;
991 }
992
993 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
994 return false;
995 }
996 }
997
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000998 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000999 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001000 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001001
John McCallf36e02d2009-10-09 21:13:30 +00001002 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001003}
1004
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001005/// @brief Perform unqualified name lookup starting from a given
1006/// scope.
1007///
1008/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1009/// used to find names within the current scope. For example, 'x' in
1010/// @code
1011/// int x;
1012/// int f() {
1013/// return x; // unqualified name look finds 'x' in the global scope
1014/// }
1015/// @endcode
1016///
1017/// Different lookup criteria can find different names. For example, a
1018/// particular scope can have both a struct and a function of the same
1019/// name, and each can be found by certain lookup criteria. For more
1020/// information about lookup criteria, see the documentation for the
1021/// class LookupCriteria.
1022///
1023/// @param S The scope from which unqualified name lookup will
1024/// begin. If the lookup criteria permits, name lookup may also search
1025/// in the parent scopes.
1026///
1027/// @param Name The name of the entity that we are searching for.
1028///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001029/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001030/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001031/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001032///
1033/// @returns The result of name lookup, which includes zero or more
1034/// declarations and possibly additional information used to diagnose
1035/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001036bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1037 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001038 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001039
John McCalla24dc2e2009-11-17 02:14:36 +00001040 LookupNameKind NameKind = R.getLookupKind();
1041
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001042 if (!getLangOptions().CPlusPlus) {
1043 // Unqualified name lookup in C/Objective-C is purely lexical, so
1044 // search in the declarations attached to the name.
1045
John McCall1d7c5282009-12-18 10:40:03 +00001046 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001047 // Find the nearest non-transparent declaration scope.
1048 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001049 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001050 static_cast<DeclContext *>(S->getEntity())
1051 ->isTransparentContext()))
1052 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001053 }
1054
John McCall1d7c5282009-12-18 10:40:03 +00001055 unsigned IDNS = R.getIdentifierNamespace();
1056
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001057 // Scan up the scope chain looking for a decl that matches this
1058 // identifier that is in the appropriate namespace. This search
1059 // should not take long, as shadowing of names is uncommon, and
1060 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001061 bool LeftStartingScope = false;
1062
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001063 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001064 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001065 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001066 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001067 if (NameKind == LookupRedeclarationWithLinkage) {
1068 // Determine whether this (or a previous) declaration is
1069 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001070 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001071 LeftStartingScope = true;
1072
1073 // If we found something outside of our starting scope that
1074 // does not have linkage, skip it.
1075 if (LeftStartingScope && !((*I)->hasLinkage()))
1076 continue;
1077 }
1078
John McCallf36e02d2009-10-09 21:13:30 +00001079 R.addDecl(*I);
1080
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001081 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001082 // If this declaration has the "overloadable" attribute, we
1083 // might have a set of overloaded functions.
1084
1085 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001086 while (!(S->getFlags() & Scope::DeclScope) ||
John McCalld226f652010-08-21 09:40:31 +00001087 !S->isDeclScope(*I))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001088 S = S->getParent();
1089
1090 // Find the last declaration in this scope (with the same
1091 // name, naturally).
1092 IdentifierResolver::iterator LastI = I;
1093 for (++LastI; LastI != IEnd; ++LastI) {
John McCalld226f652010-08-21 09:40:31 +00001094 if (!S->isDeclScope(*LastI))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001095 break;
John McCallf36e02d2009-10-09 21:13:30 +00001096 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001097 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001098 }
1099
John McCallf36e02d2009-10-09 21:13:30 +00001100 R.resolveKind();
1101
1102 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001103 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001104 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001105 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001106 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001107 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001108 }
1109
1110 // If we didn't find a use of this identifier, and if the identifier
1111 // corresponds to a compiler builtin, create the decl object for the builtin
1112 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +00001113 if (AllowBuiltinCreation)
1114 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001115
John McCallf36e02d2009-10-09 21:13:30 +00001116 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001117}
1118
John McCall6e247262009-10-10 05:48:19 +00001119/// @brief Perform qualified name lookup in the namespaces nominated by
1120/// using directives by the given context.
1121///
1122/// C++98 [namespace.qual]p2:
1123/// Given X::m (where X is a user-declared namespace), or given ::m
1124/// (where X is the global namespace), let S be the set of all
1125/// declarations of m in X and in the transitive closure of all
1126/// namespaces nominated by using-directives in X and its used
1127/// namespaces, except that using-directives are ignored in any
1128/// namespace, including X, directly containing one or more
1129/// declarations of m. No namespace is searched more than once in
1130/// the lookup of a name. If S is the empty set, the program is
1131/// ill-formed. Otherwise, if S has exactly one member, or if the
1132/// context of the reference is a using-declaration
1133/// (namespace.udecl), S is the required set of declarations of
1134/// m. Otherwise if the use of m is not one that allows a unique
1135/// declaration to be chosen from S, the program is ill-formed.
1136/// C++98 [namespace.qual]p5:
1137/// During the lookup of a qualified namespace member name, if the
1138/// lookup finds more than one declaration of the member, and if one
1139/// declaration introduces a class name or enumeration name and the
1140/// other declarations either introduce the same object, the same
1141/// enumerator or a set of functions, the non-type name hides the
1142/// class or enumeration name if and only if the declarations are
1143/// from the same namespace; otherwise (the declarations are from
1144/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001145static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001146 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001147 assert(StartDC->isFileContext() && "start context is not a file context");
1148
1149 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1150 DeclContext::udir_iterator E = StartDC->using_directives_end();
1151
1152 if (I == E) return false;
1153
1154 // We have at least added all these contexts to the queue.
1155 llvm::DenseSet<DeclContext*> Visited;
1156 Visited.insert(StartDC);
1157
1158 // We have not yet looked into these namespaces, much less added
1159 // their "using-children" to the queue.
1160 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1161
1162 // We have already looked into the initial namespace; seed the queue
1163 // with its using-children.
1164 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001165 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001166 if (Visited.insert(ND).second)
1167 Queue.push_back(ND);
1168 }
1169
1170 // The easiest way to implement the restriction in [namespace.qual]p5
1171 // is to check whether any of the individual results found a tag
1172 // and, if so, to declare an ambiguity if the final result is not
1173 // a tag.
1174 bool FoundTag = false;
1175 bool FoundNonTag = false;
1176
John McCall7d384dd2009-11-18 07:57:50 +00001177 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001178
1179 bool Found = false;
1180 while (!Queue.empty()) {
1181 NamespaceDecl *ND = Queue.back();
1182 Queue.pop_back();
1183
1184 // We go through some convolutions here to avoid copying results
1185 // between LookupResults.
1186 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001187 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001188 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001189
1190 if (FoundDirect) {
1191 // First do any local hiding.
1192 DirectR.resolveKind();
1193
1194 // If the local result is a tag, remember that.
1195 if (DirectR.isSingleTagDecl())
1196 FoundTag = true;
1197 else
1198 FoundNonTag = true;
1199
1200 // Append the local results to the total results if necessary.
1201 if (UseLocal) {
1202 R.addAllDecls(LocalR);
1203 LocalR.clear();
1204 }
1205 }
1206
1207 // If we find names in this namespace, ignore its using directives.
1208 if (FoundDirect) {
1209 Found = true;
1210 continue;
1211 }
1212
1213 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1214 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1215 if (Visited.insert(Nom).second)
1216 Queue.push_back(Nom);
1217 }
1218 }
1219
1220 if (Found) {
1221 if (FoundTag && FoundNonTag)
1222 R.setAmbiguousQualifiedTagHiding();
1223 else
1224 R.resolveKind();
1225 }
1226
1227 return Found;
1228}
1229
Douglas Gregor8071e422010-08-15 06:18:01 +00001230/// \brief Callback that looks for any member of a class with the given name.
1231static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1232 CXXBasePath &Path,
1233 void *Name) {
1234 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1235
1236 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1237 Path.Decls = BaseRecord->lookup(N);
1238 return Path.Decls.first != Path.Decls.second;
1239}
1240
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001241/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001242///
1243/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1244/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001245/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001246///
1247/// Different lookup criteria can find different names. For example, a
1248/// particular scope can have both a struct and a function of the same
1249/// name, and each can be found by certain lookup criteria. For more
1250/// information about lookup criteria, see the documentation for the
1251/// class LookupCriteria.
1252///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001253/// \param R captures both the lookup criteria and any lookup results found.
1254///
1255/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001256/// search. If the lookup criteria permits, name lookup may also search
1257/// in the parent contexts or (for C++ classes) base classes.
1258///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001259/// \param InUnqualifiedLookup true if this is qualified name lookup that
1260/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001261///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001262/// \returns true if lookup succeeded, false if it failed.
1263bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1264 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001265 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001266
John McCalla24dc2e2009-11-17 02:14:36 +00001267 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001268 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001270 // Make sure that the declaration context is complete.
1271 assert((!isa<TagDecl>(LookupCtx) ||
1272 LookupCtx->isDependentContext() ||
1273 cast<TagDecl>(LookupCtx)->isDefinition() ||
1274 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1275 ->isBeingDefined()) &&
1276 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001278 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001279 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001280 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001281 if (isa<CXXRecordDecl>(LookupCtx))
1282 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001283 return true;
1284 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001285
John McCall6e247262009-10-10 05:48:19 +00001286 // Don't descend into implied contexts for redeclarations.
1287 // C++98 [namespace.qual]p6:
1288 // In a declaration for a namespace member in which the
1289 // declarator-id is a qualified-id, given that the qualified-id
1290 // for the namespace member has the form
1291 // nested-name-specifier unqualified-id
1292 // the unqualified-id shall name a member of the namespace
1293 // designated by the nested-name-specifier.
1294 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001295 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001296 return false;
1297
John McCalla24dc2e2009-11-17 02:14:36 +00001298 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001299 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001300 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001301
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001302 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001303 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001304 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001305 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001306 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001307
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001308 // If we're performing qualified name lookup into a dependent class,
1309 // then we are actually looking into a current instantiation. If we have any
1310 // dependent base classes, then we either have to delay lookup until
1311 // template instantiation time (at which point all bases will be available)
1312 // or we have to fail.
1313 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1314 LookupRec->hasAnyDependentBases()) {
1315 R.setNotFoundInCurrentInstantiation();
1316 return false;
1317 }
1318
Douglas Gregor7176fff2009-01-15 00:26:24 +00001319 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001320 CXXBasePaths Paths;
1321 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001322
1323 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001324 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001325 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001326 case LookupOrdinaryName:
1327 case LookupMemberName:
1328 case LookupRedeclarationWithLinkage:
1329 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1330 break;
1331
1332 case LookupTagName:
1333 BaseCallback = &CXXRecordDecl::FindTagMember;
1334 break;
John McCall9f54ad42009-12-10 09:41:52 +00001335
Douglas Gregor8071e422010-08-15 06:18:01 +00001336 case LookupAnyName:
1337 BaseCallback = &LookupAnyMember;
1338 break;
1339
John McCall9f54ad42009-12-10 09:41:52 +00001340 case LookupUsingDeclName:
1341 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001342
1343 case LookupOperatorName:
1344 case LookupNamespaceName:
1345 case LookupObjCProtocolName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001346 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001347 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001348
1349 case LookupNestedNameSpecifierName:
1350 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1351 break;
1352 }
1353
John McCalla24dc2e2009-11-17 02:14:36 +00001354 if (!LookupRec->lookupInBases(BaseCallback,
1355 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001356 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001357
John McCall92f88312010-01-23 00:46:32 +00001358 R.setNamingClass(LookupRec);
1359
Douglas Gregor7176fff2009-01-15 00:26:24 +00001360 // C++ [class.member.lookup]p2:
1361 // [...] If the resulting set of declarations are not all from
1362 // sub-objects of the same type, or the set has a nonstatic member
1363 // and includes members from distinct sub-objects, there is an
1364 // ambiguity and the program is ill-formed. Otherwise that set is
1365 // the result of the lookup.
1366 // FIXME: support using declarations!
1367 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001368 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001369 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001370 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001371 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001372 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001373
John McCall46460a62010-01-20 21:53:11 +00001374 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1375 // across all paths.
1376 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1377
Douglas Gregor7176fff2009-01-15 00:26:24 +00001378 // Determine whether we're looking at a distinct sub-object or not.
1379 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001380 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001381 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1382 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00001383 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001384 != Context.getCanonicalType(PathElement.Base->getType())) {
1385 // We found members of the given name in two subobjects of
1386 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001387 R.setAmbiguousBaseSubobjectTypes(Paths);
1388 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001389 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1390 // We have a different subobject of the same type.
1391
1392 // C++ [class.member.lookup]p5:
1393 // A static member, a nested type or an enumerator defined in
1394 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001395 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001396 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001397 if (isa<VarDecl>(FirstDecl) ||
1398 isa<TypeDecl>(FirstDecl) ||
1399 isa<EnumConstantDecl>(FirstDecl))
1400 continue;
1401
1402 if (isa<CXXMethodDecl>(FirstDecl)) {
1403 // Determine whether all of the methods are static.
1404 bool AllMethodsAreStatic = true;
1405 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1406 Func != Path->Decls.second; ++Func) {
1407 if (!isa<CXXMethodDecl>(*Func)) {
1408 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1409 break;
1410 }
1411
1412 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1413 AllMethodsAreStatic = false;
1414 break;
1415 }
1416 }
1417
1418 if (AllMethodsAreStatic)
1419 continue;
1420 }
1421
1422 // We have found a nonstatic member name in multiple, distinct
1423 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001424 R.setAmbiguousBaseSubobjects(Paths);
1425 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001426 }
1427 }
1428
1429 // Lookup in a base class succeeded; return these results.
1430
John McCallf36e02d2009-10-09 21:13:30 +00001431 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001432 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1433 NamedDecl *D = *I;
1434 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1435 D->getAccess());
1436 R.addDecl(D, AS);
1437 }
John McCallf36e02d2009-10-09 21:13:30 +00001438 R.resolveKind();
1439 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001440}
1441
1442/// @brief Performs name lookup for a name that was parsed in the
1443/// source code, and may contain a C++ scope specifier.
1444///
1445/// This routine is a convenience routine meant to be called from
1446/// contexts that receive a name and an optional C++ scope specifier
1447/// (e.g., "N::M::x"). It will then perform either qualified or
1448/// unqualified name lookup (with LookupQualifiedName or LookupName,
1449/// respectively) on the given name and return those results.
1450///
1451/// @param S The scope from which unqualified name lookup will
1452/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001453///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001454/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001455///
1456/// @param Name The name of the entity that name lookup will
1457/// search for.
1458///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001459/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001460/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001461/// C library functions (like "malloc") are implicitly declared.
1462///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001463/// @param EnteringContext Indicates whether we are going to enter the
1464/// context of the scope-specifier SS (if present).
1465///
John McCallf36e02d2009-10-09 21:13:30 +00001466/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001467bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001468 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001469 if (SS && SS->isInvalid()) {
1470 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001471 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001472 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001473 }
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Douglas Gregor495c35d2009-08-25 22:51:20 +00001475 if (SS && SS->isSet()) {
1476 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001477 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001478 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001479 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001480 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001481
John McCalla24dc2e2009-11-17 02:14:36 +00001482 R.setContextRange(SS->getRange());
1483
1484 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001485 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001486
Douglas Gregor495c35d2009-08-25 22:51:20 +00001487 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001488 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001489 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001490 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001491 }
1492
Mike Stump1eb44332009-09-09 15:08:12 +00001493 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001494 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001495}
1496
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001497
Douglas Gregor7176fff2009-01-15 00:26:24 +00001498/// @brief Produce a diagnostic describing the ambiguity that resulted
1499/// from name lookup.
1500///
1501/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001502///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001503/// @param Name The name of the entity that name lookup was
1504/// searching for.
1505///
1506/// @param NameLoc The location of the name within the source code.
1507///
1508/// @param LookupRange A source range that provides more
1509/// source-location information concerning the lookup itself. For
1510/// example, this range might highlight a nested-name-specifier that
1511/// precedes the name.
1512///
1513/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001514bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001515 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1516
John McCalla24dc2e2009-11-17 02:14:36 +00001517 DeclarationName Name = Result.getLookupName();
1518 SourceLocation NameLoc = Result.getNameLoc();
1519 SourceRange LookupRange = Result.getContextRange();
1520
John McCall6e247262009-10-10 05:48:19 +00001521 switch (Result.getAmbiguityKind()) {
1522 case LookupResult::AmbiguousBaseSubobjects: {
1523 CXXBasePaths *Paths = Result.getBasePaths();
1524 QualType SubobjectType = Paths->front().back().Base->getType();
1525 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1526 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1527 << LookupRange;
1528
1529 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1530 while (isa<CXXMethodDecl>(*Found) &&
1531 cast<CXXMethodDecl>(*Found)->isStatic())
1532 ++Found;
1533
1534 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1535
1536 return true;
1537 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001538
John McCall6e247262009-10-10 05:48:19 +00001539 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001540 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1541 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001542
1543 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001544 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001545 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1546 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001547 Path != PathEnd; ++Path) {
1548 Decl *D = *Path->Decls.first;
1549 if (DeclsPrinted.insert(D).second)
1550 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1551 }
1552
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001553 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001554 }
1555
John McCall6e247262009-10-10 05:48:19 +00001556 case LookupResult::AmbiguousTagHiding: {
1557 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001558
John McCall6e247262009-10-10 05:48:19 +00001559 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1560
1561 LookupResult::iterator DI, DE = Result.end();
1562 for (DI = Result.begin(); DI != DE; ++DI)
1563 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1564 TagDecls.insert(TD);
1565 Diag(TD->getLocation(), diag::note_hidden_tag);
1566 }
1567
1568 for (DI = Result.begin(); DI != DE; ++DI)
1569 if (!isa<TagDecl>(*DI))
1570 Diag((*DI)->getLocation(), diag::note_hiding_object);
1571
1572 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001573 LookupResult::Filter F = Result.makeFilter();
1574 while (F.hasNext()) {
1575 if (TagDecls.count(F.next()))
1576 F.erase();
1577 }
1578 F.done();
John McCall6e247262009-10-10 05:48:19 +00001579
1580 return true;
1581 }
1582
1583 case LookupResult::AmbiguousReference: {
1584 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001585
John McCall6e247262009-10-10 05:48:19 +00001586 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1587 for (; DI != DE; ++DI)
1588 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001589
John McCall6e247262009-10-10 05:48:19 +00001590 return true;
1591 }
1592 }
1593
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001594 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001595 return true;
1596}
Douglas Gregorfa047642009-02-04 00:32:51 +00001597
John McCallc7e04da2010-05-28 18:45:08 +00001598namespace {
1599 struct AssociatedLookup {
1600 AssociatedLookup(Sema &S,
1601 Sema::AssociatedNamespaceSet &Namespaces,
1602 Sema::AssociatedClassSet &Classes)
1603 : S(S), Namespaces(Namespaces), Classes(Classes) {
1604 }
1605
1606 Sema &S;
1607 Sema::AssociatedNamespaceSet &Namespaces;
1608 Sema::AssociatedClassSet &Classes;
1609 };
1610}
1611
Mike Stump1eb44332009-09-09 15:08:12 +00001612static void
John McCallc7e04da2010-05-28 18:45:08 +00001613addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001614
Douglas Gregor54022952010-04-30 07:08:38 +00001615static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1616 DeclContext *Ctx) {
1617 // Add the associated namespace for this class.
1618
1619 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1620 // be a locally scoped record.
1621
Sebastian Redl410c4f22010-08-31 20:53:31 +00001622 // We skip out of inline namespaces. The innermost non-inline namespace
1623 // contains all names of all its nested inline namespaces anyway, so we can
1624 // replace the entire inline namespace tree with its root.
1625 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1626 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001627 Ctx = Ctx->getParent();
1628
John McCall6ff07852009-08-07 22:18:02 +00001629 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001630 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001631}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001632
Mike Stump1eb44332009-09-09 15:08:12 +00001633// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001634// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001635static void
John McCallc7e04da2010-05-28 18:45:08 +00001636addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1637 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001638 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001639 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001640 switch (Arg.getKind()) {
1641 case TemplateArgument::Null:
1642 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Douglas Gregor69be8d62009-07-08 07:51:57 +00001644 case TemplateArgument::Type:
1645 // [...] the namespaces and classes associated with the types of the
1646 // template arguments provided for template type parameters (excluding
1647 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001648 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001649 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Douglas Gregor788cd062009-11-11 01:00:40 +00001651 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001652 // [...] the namespaces in which any template template arguments are
1653 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001654 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001655 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001656 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001657 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001658 DeclContext *Ctx = ClassTemplate->getDeclContext();
1659 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001660 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001661 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001662 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001663 }
1664 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001665 }
1666
1667 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001668 case TemplateArgument::Integral:
1669 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001670 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001671 // associated namespaces. ]
1672 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Douglas Gregor69be8d62009-07-08 07:51:57 +00001674 case TemplateArgument::Pack:
1675 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1676 PEnd = Arg.pack_end();
1677 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001678 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001679 break;
1680 }
1681}
1682
Douglas Gregorfa047642009-02-04 00:32:51 +00001683// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001684// argument-dependent lookup with an argument of class type
1685// (C++ [basic.lookup.koenig]p2).
1686static void
John McCallc7e04da2010-05-28 18:45:08 +00001687addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1688 CXXRecordDecl *Class) {
1689
1690 // Just silently ignore anything whose name is __va_list_tag.
1691 if (Class->getDeclName() == Result.S.VAListTagName)
1692 return;
1693
Douglas Gregorfa047642009-02-04 00:32:51 +00001694 // C++ [basic.lookup.koenig]p2:
1695 // [...]
1696 // -- If T is a class type (including unions), its associated
1697 // classes are: the class itself; the class of which it is a
1698 // member, if any; and its direct and indirect base
1699 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001700 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001701
1702 // Add the class of which it is a member, if any.
1703 DeclContext *Ctx = Class->getDeclContext();
1704 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001705 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001706 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001707 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Douglas Gregorfa047642009-02-04 00:32:51 +00001709 // Add the class itself. If we've already seen this class, we don't
1710 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001711 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001712 return;
1713
Mike Stump1eb44332009-09-09 15:08:12 +00001714 // -- If T is a template-id, its associated namespaces and classes are
1715 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001716 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001717 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001718 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001719 // namespaces in which any template template arguments are defined; and
1720 // the classes in which any member templates used as template template
1721 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001722 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001723 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001724 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1725 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1726 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001727 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001728 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001729 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Douglas Gregor69be8d62009-07-08 07:51:57 +00001731 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1732 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001733 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001734 }
Mike Stump1eb44332009-09-09 15:08:12 +00001735
John McCall86ff3082010-02-04 22:26:26 +00001736 // Only recurse into base classes for complete types.
1737 if (!Class->hasDefinition()) {
1738 // FIXME: we might need to instantiate templates here
1739 return;
1740 }
1741
Douglas Gregorfa047642009-02-04 00:32:51 +00001742 // Add direct and indirect base classes along with their associated
1743 // namespaces.
1744 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1745 Bases.push_back(Class);
1746 while (!Bases.empty()) {
1747 // Pop this class off the stack.
1748 Class = Bases.back();
1749 Bases.pop_back();
1750
1751 // Visit the base classes.
1752 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1753 BaseEnd = Class->bases_end();
1754 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001755 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001756 // In dependent contexts, we do ADL twice, and the first time around,
1757 // the base type might be a dependent TemplateSpecializationType, or a
1758 // TemplateTypeParmType. If that happens, simply ignore it.
1759 // FIXME: If we want to support export, we probably need to add the
1760 // namespace of the template in a TemplateSpecializationType, or even
1761 // the classes and namespaces of known non-dependent arguments.
1762 if (!BaseType)
1763 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001764 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001765 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001766 // Find the associated namespace for this base class.
1767 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001768 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001769
1770 // Make sure we visit the bases of this base class.
1771 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1772 Bases.push_back(BaseDecl);
1773 }
1774 }
1775 }
1776}
1777
1778// \brief Add the associated classes and namespaces for
1779// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001780// (C++ [basic.lookup.koenig]p2).
1781static void
John McCallc7e04da2010-05-28 18:45:08 +00001782addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001783 // C++ [basic.lookup.koenig]p2:
1784 //
1785 // For each argument type T in the function call, there is a set
1786 // of zero or more associated namespaces and a set of zero or more
1787 // associated classes to be considered. The sets of namespaces and
1788 // classes is determined entirely by the types of the function
1789 // arguments (and the namespace of any template template
1790 // argument). Typedef names and using-declarations used to specify
1791 // the types do not contribute to this set. The sets of namespaces
1792 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001793
John McCallfa4edcf2010-05-28 06:08:54 +00001794 llvm::SmallVector<const Type *, 16> Queue;
1795 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1796
Douglas Gregorfa047642009-02-04 00:32:51 +00001797 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001798 switch (T->getTypeClass()) {
1799
1800#define TYPE(Class, Base)
1801#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1802#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1803#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1804#define ABSTRACT_TYPE(Class, Base)
1805#include "clang/AST/TypeNodes.def"
1806 // T is canonical. We can also ignore dependent types because
1807 // we don't need to do ADL at the definition point, but if we
1808 // wanted to implement template export (or if we find some other
1809 // use for associated classes and namespaces...) this would be
1810 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001811 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001812
John McCallfa4edcf2010-05-28 06:08:54 +00001813 // -- If T is a pointer to U or an array of U, its associated
1814 // namespaces and classes are those associated with U.
1815 case Type::Pointer:
1816 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1817 continue;
1818 case Type::ConstantArray:
1819 case Type::IncompleteArray:
1820 case Type::VariableArray:
1821 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1822 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001823
John McCallfa4edcf2010-05-28 06:08:54 +00001824 // -- If T is a fundamental type, its associated sets of
1825 // namespaces and classes are both empty.
1826 case Type::Builtin:
1827 break;
1828
1829 // -- If T is a class type (including unions), its associated
1830 // classes are: the class itself; the class of which it is a
1831 // member, if any; and its direct and indirect base
1832 // classes. Its associated namespaces are the namespaces in
1833 // which its associated classes are defined.
1834 case Type::Record: {
1835 CXXRecordDecl *Class
1836 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001837 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001838 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001839 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001840
John McCallfa4edcf2010-05-28 06:08:54 +00001841 // -- If T is an enumeration type, its associated namespace is
1842 // the namespace in which it is defined. If it is class
1843 // member, its associated class is the member’s class; else
1844 // it has no associated class.
1845 case Type::Enum: {
1846 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001847
John McCallfa4edcf2010-05-28 06:08:54 +00001848 DeclContext *Ctx = Enum->getDeclContext();
1849 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001850 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001851
John McCallfa4edcf2010-05-28 06:08:54 +00001852 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001853 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001854
John McCallfa4edcf2010-05-28 06:08:54 +00001855 break;
1856 }
1857
1858 // -- If T is a function type, its associated namespaces and
1859 // classes are those associated with the function parameter
1860 // types and those associated with the return type.
1861 case Type::FunctionProto: {
1862 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1863 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1864 ArgEnd = Proto->arg_type_end();
1865 Arg != ArgEnd; ++Arg)
1866 Queue.push_back(Arg->getTypePtr());
1867 // fallthrough
1868 }
1869 case Type::FunctionNoProto: {
1870 const FunctionType *FnType = cast<FunctionType>(T);
1871 T = FnType->getResultType().getTypePtr();
1872 continue;
1873 }
1874
1875 // -- If T is a pointer to a member function of a class X, its
1876 // associated namespaces and classes are those associated
1877 // with the function parameter types and return type,
1878 // together with those associated with X.
1879 //
1880 // -- If T is a pointer to a data member of class X, its
1881 // associated namespaces and classes are those associated
1882 // with the member type together with those associated with
1883 // X.
1884 case Type::MemberPointer: {
1885 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1886
1887 // Queue up the class type into which this points.
1888 Queue.push_back(MemberPtr->getClass());
1889
1890 // And directly continue with the pointee type.
1891 T = MemberPtr->getPointeeType().getTypePtr();
1892 continue;
1893 }
1894
1895 // As an extension, treat this like a normal pointer.
1896 case Type::BlockPointer:
1897 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1898 continue;
1899
1900 // References aren't covered by the standard, but that's such an
1901 // obvious defect that we cover them anyway.
1902 case Type::LValueReference:
1903 case Type::RValueReference:
1904 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1905 continue;
1906
1907 // These are fundamental types.
1908 case Type::Vector:
1909 case Type::ExtVector:
1910 case Type::Complex:
1911 break;
1912
1913 // These are ignored by ADL.
1914 case Type::ObjCObject:
1915 case Type::ObjCInterface:
1916 case Type::ObjCObjectPointer:
1917 break;
1918 }
1919
1920 if (Queue.empty()) break;
1921 T = Queue.back();
1922 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001923 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001924}
1925
1926/// \brief Find the associated classes and namespaces for
1927/// argument-dependent lookup for a call with the given set of
1928/// arguments.
1929///
1930/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001931/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001932/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001933void
Douglas Gregorfa047642009-02-04 00:32:51 +00001934Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1935 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001936 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001937 AssociatedNamespaces.clear();
1938 AssociatedClasses.clear();
1939
John McCallc7e04da2010-05-28 18:45:08 +00001940 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1941
Douglas Gregorfa047642009-02-04 00:32:51 +00001942 // C++ [basic.lookup.koenig]p2:
1943 // For each argument type T in the function call, there is a set
1944 // of zero or more associated namespaces and a set of zero or more
1945 // associated classes to be considered. The sets of namespaces and
1946 // classes is determined entirely by the types of the function
1947 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001948 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001949 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1950 Expr *Arg = Args[ArgIdx];
1951
1952 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00001953 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001954 continue;
1955 }
1956
1957 // [...] In addition, if the argument is the name or address of a
1958 // set of overloaded functions and/or function templates, its
1959 // associated classes and namespaces are the union of those
1960 // associated with each of the members of the set: the namespace
1961 // in which the function or function template is defined and the
1962 // classes and namespaces associated with its (non-dependent)
1963 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001964 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001965 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00001966 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00001967 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001968
John McCallc7e04da2010-05-28 18:45:08 +00001969 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1970 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00001971
John McCallc7e04da2010-05-28 18:45:08 +00001972 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1973 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001974 // Look through any using declarations to find the underlying function.
1975 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001976
Chandler Carruthbd647292009-12-29 06:17:27 +00001977 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1978 if (!FDecl)
1979 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001980
1981 // Add the classes and namespaces associated with the parameter
1982 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00001983 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001984 }
1985 }
1986}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001987
1988/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1989/// an acceptable non-member overloaded operator for a call whose
1990/// arguments have types T1 (and, if non-empty, T2). This routine
1991/// implements the check in C++ [over.match.oper]p3b2 concerning
1992/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001993static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001994IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1995 QualType T1, QualType T2,
1996 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001997 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1998 return true;
1999
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002000 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2001 return true;
2002
John McCall183700f2009-09-21 23:43:11 +00002003 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002004 if (Proto->getNumArgs() < 1)
2005 return false;
2006
2007 if (T1->isEnumeralType()) {
2008 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002009 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002010 return true;
2011 }
2012
2013 if (Proto->getNumArgs() < 2)
2014 return false;
2015
2016 if (!T2.isNull() && T2->isEnumeralType()) {
2017 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002018 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002019 return true;
2020 }
2021
2022 return false;
2023}
2024
John McCall7d384dd2009-11-18 07:57:50 +00002025NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002026 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002027 LookupNameKind NameKind,
2028 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002029 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002030 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002031 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002032}
2033
Douglas Gregor6e378de2009-04-23 23:18:26 +00002034/// \brief Find the protocol with the given name, if any.
Douglas Gregorc83c6872010-04-15 22:33:43 +00002035ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2036 SourceLocation IdLoc) {
2037 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2038 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002039 return cast_or_null<ObjCProtocolDecl>(D);
2040}
2041
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002042void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002043 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002044 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002045 // C++ [over.match.oper]p3:
2046 // -- The set of non-member candidates is the result of the
2047 // unqualified lookup of operator@ in the context of the
2048 // expression according to the usual rules for name lookup in
2049 // unqualified function calls (3.4.2) except that all member
2050 // functions are ignored. However, if no operand has a class
2051 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002052 // that have a first parameter of type T1 or "reference to
2053 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002054 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002055 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002056 // when T2 is an enumeration type, are candidate functions.
2057 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002058 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2059 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002061 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2062
John McCallf36e02d2009-10-09 21:13:30 +00002063 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002064 return;
2065
2066 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2067 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002068 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2069 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002070 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002071 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002072 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002073 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002074 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002075 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002076 // later?
2077 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002078 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002079 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002080 }
2081}
2082
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002083/// \brief Look up the constructors for the given class.
2084DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +00002085 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002086 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2087 if (!Class->hasDeclaredDefaultConstructor())
2088 DeclareImplicitDefaultConstructor(Class);
2089 if (!Class->hasDeclaredCopyConstructor())
2090 DeclareImplicitCopyConstructor(Class);
2091 }
Douglas Gregor22584312010-07-02 23:41:54 +00002092
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002093 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2094 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2095 return Class->lookup(Name);
2096}
2097
Douglas Gregordb89f282010-07-01 22:47:18 +00002098/// \brief Look for the destructor of the given class.
2099///
2100/// During semantic analysis, this routine should be used in lieu of
2101/// CXXRecordDecl::getDestructor().
2102///
2103/// \returns The destructor for this class.
2104CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +00002105 // If the destructor has not yet been declared, do so now.
2106 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2107 !Class->hasDeclaredDestructor())
2108 DeclareImplicitDestructor(Class);
2109
Douglas Gregordb89f282010-07-01 22:47:18 +00002110 return Class->getDestructor();
2111}
2112
John McCall7edb5fd2010-01-26 07:16:45 +00002113void ADLResult::insert(NamedDecl *New) {
2114 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2115
2116 // If we haven't yet seen a decl for this key, or the last decl
2117 // was exactly this one, we're done.
2118 if (Old == 0 || Old == New) {
2119 Old = New;
2120 return;
2121 }
2122
2123 // Otherwise, decide which is a more recent redeclaration.
2124 FunctionDecl *OldFD, *NewFD;
2125 if (isa<FunctionTemplateDecl>(New)) {
2126 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2127 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2128 } else {
2129 OldFD = cast<FunctionDecl>(Old);
2130 NewFD = cast<FunctionDecl>(New);
2131 }
2132
2133 FunctionDecl *Cursor = NewFD;
2134 while (true) {
2135 Cursor = Cursor->getPreviousDeclaration();
2136
2137 // If we got to the end without finding OldFD, OldFD is the newer
2138 // declaration; leave things as they are.
2139 if (!Cursor) return;
2140
2141 // If we do find OldFD, then NewFD is newer.
2142 if (Cursor == OldFD) break;
2143
2144 // Otherwise, keep looking.
2145 }
2146
2147 Old = New;
2148}
2149
Sebastian Redl644be852009-10-23 19:23:15 +00002150void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002151 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00002152 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002153 // Find all of the associated namespaces and classes based on the
2154 // arguments we have.
2155 AssociatedNamespaceSet AssociatedNamespaces;
2156 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002157 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002158 AssociatedNamespaces,
2159 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002160
Sebastian Redl644be852009-10-23 19:23:15 +00002161 QualType T1, T2;
2162 if (Operator) {
2163 T1 = Args[0]->getType();
2164 if (NumArgs >= 2)
2165 T2 = Args[1]->getType();
2166 }
2167
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002168 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002169 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2170 // and let Y be the lookup set produced by argument dependent
2171 // lookup (defined as follows). If X contains [...] then Y is
2172 // empty. Otherwise Y is the set of declarations found in the
2173 // namespaces associated with the argument types as described
2174 // below. The set of declarations found by the lookup of the name
2175 // is the union of X and Y.
2176 //
2177 // Here, we compute Y and add its members to the overloaded
2178 // candidate set.
2179 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002180 NSEnd = AssociatedNamespaces.end();
2181 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002182 // When considering an associated namespace, the lookup is the
2183 // same as the lookup performed when the associated namespace is
2184 // used as a qualifier (3.4.3.2) except that:
2185 //
2186 // -- Any using-directives in the associated namespace are
2187 // ignored.
2188 //
John McCall6ff07852009-08-07 22:18:02 +00002189 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002190 // associated classes are visible within their respective
2191 // namespaces even if they are not visible during an ordinary
2192 // lookup (11.4).
2193 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002194 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002195 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002196 // If the only declaration here is an ordinary friend, consider
2197 // it only if it was declared in an associated classes.
2198 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002199 DeclContext *LexDC = D->getLexicalDeclContext();
2200 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2201 continue;
2202 }
Mike Stump1eb44332009-09-09 15:08:12 +00002203
John McCalla113e722010-01-26 06:04:06 +00002204 if (isa<UsingShadowDecl>(D))
2205 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002206
John McCalla113e722010-01-26 06:04:06 +00002207 if (isa<FunctionDecl>(D)) {
2208 if (Operator &&
2209 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2210 T1, T2, Context))
2211 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002212 } else if (!isa<FunctionTemplateDecl>(D))
2213 continue;
2214
2215 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002216 }
2217 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002218}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002219
2220//----------------------------------------------------------------------------
2221// Search for all visible declarations.
2222//----------------------------------------------------------------------------
2223VisibleDeclConsumer::~VisibleDeclConsumer() { }
2224
2225namespace {
2226
2227class ShadowContextRAII;
2228
2229class VisibleDeclsRecord {
2230public:
2231 /// \brief An entry in the shadow map, which is optimized to store a
2232 /// single declaration (the common case) but can also store a list
2233 /// of declarations.
2234 class ShadowMapEntry {
2235 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2236
2237 /// \brief Contains either the solitary NamedDecl * or a vector
2238 /// of declarations.
2239 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2240
2241 public:
2242 ShadowMapEntry() : DeclOrVector() { }
2243
2244 void Add(NamedDecl *ND);
2245 void Destroy();
2246
2247 // Iteration.
2248 typedef NamedDecl **iterator;
2249 iterator begin();
2250 iterator end();
2251 };
2252
2253private:
2254 /// \brief A mapping from declaration names to the declarations that have
2255 /// this name within a particular scope.
2256 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2257
2258 /// \brief A list of shadow maps, which is used to model name hiding.
2259 std::list<ShadowMap> ShadowMaps;
2260
2261 /// \brief The declaration contexts we have already visited.
2262 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2263
2264 friend class ShadowContextRAII;
2265
2266public:
2267 /// \brief Determine whether we have already visited this context
2268 /// (and, if not, note that we are going to visit that context now).
2269 bool visitedContext(DeclContext *Ctx) {
2270 return !VisitedContexts.insert(Ctx);
2271 }
2272
Douglas Gregor8071e422010-08-15 06:18:01 +00002273 bool alreadyVisitedContext(DeclContext *Ctx) {
2274 return VisitedContexts.count(Ctx);
2275 }
2276
Douglas Gregor546be3c2009-12-30 17:04:44 +00002277 /// \brief Determine whether the given declaration is hidden in the
2278 /// current scope.
2279 ///
2280 /// \returns the declaration that hides the given declaration, or
2281 /// NULL if no such declaration exists.
2282 NamedDecl *checkHidden(NamedDecl *ND);
2283
2284 /// \brief Add a declaration to the current shadow map.
2285 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2286};
2287
2288/// \brief RAII object that records when we've entered a shadow context.
2289class ShadowContextRAII {
2290 VisibleDeclsRecord &Visible;
2291
2292 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2293
2294public:
2295 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2296 Visible.ShadowMaps.push_back(ShadowMap());
2297 }
2298
2299 ~ShadowContextRAII() {
2300 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2301 EEnd = Visible.ShadowMaps.back().end();
2302 E != EEnd;
2303 ++E)
2304 E->second.Destroy();
2305
2306 Visible.ShadowMaps.pop_back();
2307 }
2308};
2309
2310} // end anonymous namespace
2311
2312void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2313 if (DeclOrVector.isNull()) {
2314 // 0 - > 1 elements: just set the single element information.
2315 DeclOrVector = ND;
2316 return;
2317 }
2318
2319 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2320 // 1 -> 2 elements: create the vector of results and push in the
2321 // existing declaration.
2322 DeclVector *Vec = new DeclVector;
2323 Vec->push_back(PrevND);
2324 DeclOrVector = Vec;
2325 }
2326
2327 // Add the new element to the end of the vector.
2328 DeclOrVector.get<DeclVector*>()->push_back(ND);
2329}
2330
2331void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2332 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2333 delete Vec;
2334 DeclOrVector = ((NamedDecl *)0);
2335 }
2336}
2337
2338VisibleDeclsRecord::ShadowMapEntry::iterator
2339VisibleDeclsRecord::ShadowMapEntry::begin() {
2340 if (DeclOrVector.isNull())
2341 return 0;
2342
2343 if (DeclOrVector.dyn_cast<NamedDecl *>())
2344 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2345
2346 return DeclOrVector.get<DeclVector *>()->begin();
2347}
2348
2349VisibleDeclsRecord::ShadowMapEntry::iterator
2350VisibleDeclsRecord::ShadowMapEntry::end() {
2351 if (DeclOrVector.isNull())
2352 return 0;
2353
2354 if (DeclOrVector.dyn_cast<NamedDecl *>())
2355 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2356
2357 return DeclOrVector.get<DeclVector *>()->end();
2358}
2359
2360NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002361 // Look through using declarations.
2362 ND = ND->getUnderlyingDecl();
2363
Douglas Gregor546be3c2009-12-30 17:04:44 +00002364 unsigned IDNS = ND->getIdentifierNamespace();
2365 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2366 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2367 SM != SMEnd; ++SM) {
2368 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2369 if (Pos == SM->end())
2370 continue;
2371
2372 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2373 IEnd = Pos->second.end();
2374 I != IEnd; ++I) {
2375 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002376 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor546be3c2009-12-30 17:04:44 +00002377 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2378 Decl::IDNS_ObjCProtocol)))
2379 continue;
2380
2381 // Protocols are in distinct namespaces from everything else.
2382 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2383 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2384 (*I)->getIdentifierNamespace() != IDNS)
2385 continue;
2386
Douglas Gregor0cc84042010-01-14 15:47:35 +00002387 // Functions and function templates in the same scope overload
2388 // rather than hide. FIXME: Look for hiding based on function
2389 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002390 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002391 ND->isFunctionOrFunctionTemplate() &&
2392 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002393 continue;
2394
Douglas Gregor546be3c2009-12-30 17:04:44 +00002395 // We've found a declaration that hides this one.
2396 return *I;
2397 }
2398 }
2399
2400 return 0;
2401}
2402
2403static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2404 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002405 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002406 VisibleDeclConsumer &Consumer,
2407 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002408 if (!Ctx)
2409 return;
2410
Douglas Gregor546be3c2009-12-30 17:04:44 +00002411 // Make sure we don't visit the same context twice.
2412 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2413 return;
2414
Douglas Gregor4923aa22010-07-02 20:37:36 +00002415 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2416 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2417
Douglas Gregor546be3c2009-12-30 17:04:44 +00002418 // Enumerate all of the results in this context.
2419 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2420 CurCtx = CurCtx->getNextContext()) {
2421 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2422 DEnd = CurCtx->decls_end();
2423 D != DEnd; ++D) {
2424 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2425 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002426 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002427 Visited.add(ND);
2428 }
2429
Sebastian Redl410c4f22010-08-31 20:53:31 +00002430 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002431 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002432 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002433 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002434 Consumer, Visited);
2435 }
2436 }
2437 }
2438
2439 // Traverse using directives for qualified name lookup.
2440 if (QualifiedNameLookup) {
2441 ShadowContextRAII Shadow(Visited);
2442 DeclContext::udir_iterator I, E;
2443 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2444 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002445 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002446 }
2447 }
2448
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002449 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002450 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002451 if (!Record->hasDefinition())
2452 return;
2453
Douglas Gregor546be3c2009-12-30 17:04:44 +00002454 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2455 BEnd = Record->bases_end();
2456 B != BEnd; ++B) {
2457 QualType BaseType = B->getType();
2458
2459 // Don't look into dependent bases, because name lookup can't look
2460 // there anyway.
2461 if (BaseType->isDependentType())
2462 continue;
2463
2464 const RecordType *Record = BaseType->getAs<RecordType>();
2465 if (!Record)
2466 continue;
2467
2468 // FIXME: It would be nice to be able to determine whether referencing
2469 // a particular member would be ambiguous. For example, given
2470 //
2471 // struct A { int member; };
2472 // struct B { int member; };
2473 // struct C : A, B { };
2474 //
2475 // void f(C *c) { c->### }
2476 //
2477 // accessing 'member' would result in an ambiguity. However, we
2478 // could be smart enough to qualify the member with the base
2479 // class, e.g.,
2480 //
2481 // c->B::member
2482 //
2483 // or
2484 //
2485 // c->A::member
2486
2487 // Find results in this base class (and its bases).
2488 ShadowContextRAII Shadow(Visited);
2489 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002490 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002491 }
2492 }
2493
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002494 // Traverse the contexts of Objective-C classes.
2495 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2496 // Traverse categories.
2497 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2498 Category; Category = Category->getNextClassCategory()) {
2499 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002500 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2501 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002502 }
2503
2504 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002505 for (ObjCInterfaceDecl::all_protocol_iterator
2506 I = IFace->all_referenced_protocol_begin(),
2507 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002508 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002509 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2510 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002511 }
2512
2513 // Traverse the superclass.
2514 if (IFace->getSuperClass()) {
2515 ShadowContextRAII Shadow(Visited);
2516 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002517 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002518 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002519
2520 // If there is an implementation, traverse it. We do this to find
2521 // synthesized ivars.
2522 if (IFace->getImplementation()) {
2523 ShadowContextRAII Shadow(Visited);
2524 LookupVisibleDecls(IFace->getImplementation(), Result,
2525 QualifiedNameLookup, true, Consumer, Visited);
2526 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002527 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2528 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2529 E = Protocol->protocol_end(); I != E; ++I) {
2530 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002531 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2532 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002533 }
2534 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2535 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2536 E = Category->protocol_end(); I != E; ++I) {
2537 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002538 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2539 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002540 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002541
2542 // If there is an implementation, traverse it.
2543 if (Category->getImplementation()) {
2544 ShadowContextRAII Shadow(Visited);
2545 LookupVisibleDecls(Category->getImplementation(), Result,
2546 QualifiedNameLookup, true, Consumer, Visited);
2547 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002548 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002549}
2550
2551static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2552 UnqualUsingDirectiveSet &UDirs,
2553 VisibleDeclConsumer &Consumer,
2554 VisibleDeclsRecord &Visited) {
2555 if (!S)
2556 return;
2557
Douglas Gregor8071e422010-08-15 06:18:01 +00002558 if (!S->getEntity() ||
2559 (!S->getParent() &&
2560 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002561 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2562 // Walk through the declarations in this Scope.
2563 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2564 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002565 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor539c5c32010-01-07 00:31:29 +00002566 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002567 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002568 Visited.add(ND);
2569 }
2570 }
2571 }
2572
Douglas Gregor711be1e2010-03-15 14:33:29 +00002573 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002574 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002575 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002576 // Look into this scope's declaration context, along with any of its
2577 // parent lookup contexts (e.g., enclosing classes), up to the point
2578 // where we hit the context stored in the next outer scope.
2579 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002580 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor546be3c2009-12-30 17:04:44 +00002581
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002582 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002583 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002584 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2585 if (Method->isInstanceMethod()) {
2586 // For instance methods, look for ivars in the method's interface.
2587 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2588 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor62021192010-02-04 23:42:48 +00002589 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2590 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2591 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002592 }
2593
2594 // We've already performed all of the name lookup that we need
2595 // to for Objective-C methods; the next context will be the
2596 // outer scope.
2597 break;
2598 }
2599
Douglas Gregor546be3c2009-12-30 17:04:44 +00002600 if (Ctx->isFunctionOrMethod())
2601 continue;
2602
2603 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002604 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002605 }
2606 } else if (!S->getParent()) {
2607 // Look into the translation unit scope. We walk through the translation
2608 // unit's declaration context, because the Scope itself won't have all of
2609 // the declarations if we loaded a precompiled header.
2610 // FIXME: We would like the translation unit's Scope object to point to the
2611 // translation unit, so we don't need this special "if" branch. However,
2612 // doing so would force the normal C++ name-lookup code to look into the
2613 // translation unit decl when the IdentifierInfo chains would suffice.
2614 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002615 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002616 Entity = Result.getSema().Context.getTranslationUnitDecl();
2617 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002618 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002619 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002620
2621 if (Entity) {
2622 // Lookup visible declarations in any namespaces found by using
2623 // directives.
2624 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2625 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2626 for (; UI != UEnd; ++UI)
2627 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002628 Result, /*QualifiedNameLookup=*/false,
2629 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002630 }
2631
2632 // Lookup names in the parent scope.
2633 ShadowContextRAII Shadow(Visited);
2634 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2635}
2636
2637void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002638 VisibleDeclConsumer &Consumer,
2639 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002640 // Determine the set of using directives available during
2641 // unqualified name lookup.
2642 Scope *Initial = S;
2643 UnqualUsingDirectiveSet UDirs;
2644 if (getLangOptions().CPlusPlus) {
2645 // Find the first namespace or translation-unit scope.
2646 while (S && !isNamespaceOrTranslationUnitScope(S))
2647 S = S->getParent();
2648
2649 UDirs.visitScopeChain(Initial, S);
2650 }
2651 UDirs.done();
2652
2653 // Look for visible declarations.
2654 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2655 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002656 if (!IncludeGlobalScope)
2657 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002658 ShadowContextRAII Shadow(Visited);
2659 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2660}
2661
2662void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002663 VisibleDeclConsumer &Consumer,
2664 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002665 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2666 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002667 if (!IncludeGlobalScope)
2668 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002669 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002670 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2671 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002672}
2673
2674//----------------------------------------------------------------------------
2675// Typo correction
2676//----------------------------------------------------------------------------
2677
2678namespace {
2679class TypoCorrectionConsumer : public VisibleDeclConsumer {
2680 /// \brief The name written that is a typo in the source.
2681 llvm::StringRef Typo;
2682
2683 /// \brief The results found that have the smallest edit distance
2684 /// found (so far) with the typo name.
2685 llvm::SmallVector<NamedDecl *, 4> BestResults;
2686
Douglas Gregoraaf87162010-04-14 20:04:41 +00002687 /// \brief The keywords that have the smallest edit distance.
2688 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2689
Douglas Gregor546be3c2009-12-30 17:04:44 +00002690 /// \brief The best edit distance found so far.
2691 unsigned BestEditDistance;
2692
2693public:
2694 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2695 : Typo(Typo->getName()) { }
2696
Douglas Gregor0cc84042010-01-14 15:47:35 +00002697 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002698 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002699
2700 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2701 iterator begin() const { return BestResults.begin(); }
2702 iterator end() const { return BestResults.end(); }
Douglas Gregoraaf87162010-04-14 20:04:41 +00002703 void clear_decls() { BestResults.clear(); }
2704
2705 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002706
Douglas Gregoraaf87162010-04-14 20:04:41 +00002707 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2708 keyword_iterator;
2709 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2710 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2711 bool keyword_empty() const { return BestKeywords.empty(); }
2712 unsigned keyword_size() const { return BestKeywords.size(); }
2713
2714 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002715};
2716
2717}
2718
Douglas Gregor0cc84042010-01-14 15:47:35 +00002719void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2720 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002721 // Don't consider hidden names for typo correction.
2722 if (Hiding)
2723 return;
2724
2725 // Only consider entities with identifiers for names, ignoring
2726 // special names (constructors, overloaded operators, selectors,
2727 // etc.).
2728 IdentifierInfo *Name = ND->getIdentifier();
2729 if (!Name)
2730 return;
2731
2732 // Compute the edit distance between the typo and the name of this
2733 // entity. If this edit distance is not worse than the best edit
2734 // distance we've seen so far, add it to the list of results.
2735 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregoraaf87162010-04-14 20:04:41 +00002736 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002737 if (ED < BestEditDistance) {
2738 // This result is better than any we've seen before; clear out
2739 // the previous results.
2740 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002741 BestKeywords.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002742 BestEditDistance = ED;
2743 } else if (ED > BestEditDistance) {
2744 // This result is worse than the best results we've seen so far;
2745 // ignore it.
2746 return;
2747 }
2748 } else
2749 BestEditDistance = ED;
2750
2751 BestResults.push_back(ND);
2752}
2753
Douglas Gregoraaf87162010-04-14 20:04:41 +00002754void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2755 llvm::StringRef Keyword) {
2756 // Compute the edit distance between the typo and this keyword.
2757 // If this edit distance is not worse than the best edit
2758 // distance we've seen so far, add it to the list of results.
2759 unsigned ED = Typo.edit_distance(Keyword);
2760 if (!BestResults.empty() || !BestKeywords.empty()) {
2761 if (ED < BestEditDistance) {
2762 BestResults.clear();
2763 BestKeywords.clear();
2764 BestEditDistance = ED;
2765 } else if (ED > BestEditDistance) {
2766 // This result is worse than the best results we've seen so far;
2767 // ignore it.
2768 return;
2769 }
2770 } else
2771 BestEditDistance = ED;
2772
2773 BestKeywords.push_back(&Context.Idents.get(Keyword));
2774}
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 {
2857 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2858 }
2859
Douglas Gregoraaf87162010-04-14 20:04:41 +00002860 // Add context-dependent keywords.
2861 bool WantTypeSpecifiers = false;
2862 bool WantExpressionKeywords = false;
2863 bool WantCXXNamedCasts = false;
2864 bool WantRemainingKeywords = false;
2865 switch (CTC) {
2866 case CTC_Unknown:
2867 WantTypeSpecifiers = true;
2868 WantExpressionKeywords = true;
2869 WantCXXNamedCasts = true;
2870 WantRemainingKeywords = true;
Douglas Gregor91f7ac72010-05-18 16:14:23 +00002871
2872 if (ObjCMethodDecl *Method = getCurMethodDecl())
2873 if (Method->getClassInterface() &&
2874 Method->getClassInterface()->getSuperClass())
2875 Consumer.addKeywordResult(Context, "super");
2876
Douglas Gregoraaf87162010-04-14 20:04:41 +00002877 break;
2878
2879 case CTC_NoKeywords:
2880 break;
2881
2882 case CTC_Type:
2883 WantTypeSpecifiers = true;
2884 break;
2885
2886 case CTC_ObjCMessageReceiver:
2887 Consumer.addKeywordResult(Context, "super");
2888 // Fall through to handle message receivers like expressions.
2889
2890 case CTC_Expression:
2891 if (getLangOptions().CPlusPlus)
2892 WantTypeSpecifiers = true;
2893 WantExpressionKeywords = true;
2894 // Fall through to get C++ named casts.
2895
2896 case CTC_CXXCasts:
2897 WantCXXNamedCasts = true;
2898 break;
2899
2900 case CTC_MemberLookup:
2901 if (getLangOptions().CPlusPlus)
2902 Consumer.addKeywordResult(Context, "template");
2903 break;
2904 }
2905
2906 if (WantTypeSpecifiers) {
2907 // Add type-specifier keywords to the set of results.
2908 const char *CTypeSpecs[] = {
2909 "char", "const", "double", "enum", "float", "int", "long", "short",
2910 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2911 "_Complex", "_Imaginary",
2912 // storage-specifiers as well
2913 "extern", "inline", "static", "typedef"
2914 };
2915
2916 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2917 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2918 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2919
2920 if (getLangOptions().C99)
2921 Consumer.addKeywordResult(Context, "restrict");
2922 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2923 Consumer.addKeywordResult(Context, "bool");
2924
2925 if (getLangOptions().CPlusPlus) {
2926 Consumer.addKeywordResult(Context, "class");
2927 Consumer.addKeywordResult(Context, "typename");
2928 Consumer.addKeywordResult(Context, "wchar_t");
2929
2930 if (getLangOptions().CPlusPlus0x) {
2931 Consumer.addKeywordResult(Context, "char16_t");
2932 Consumer.addKeywordResult(Context, "char32_t");
2933 Consumer.addKeywordResult(Context, "constexpr");
2934 Consumer.addKeywordResult(Context, "decltype");
2935 Consumer.addKeywordResult(Context, "thread_local");
2936 }
2937 }
2938
2939 if (getLangOptions().GNUMode)
2940 Consumer.addKeywordResult(Context, "typeof");
2941 }
2942
Douglas Gregord0785ea2010-05-18 16:30:22 +00002943 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00002944 Consumer.addKeywordResult(Context, "const_cast");
2945 Consumer.addKeywordResult(Context, "dynamic_cast");
2946 Consumer.addKeywordResult(Context, "reinterpret_cast");
2947 Consumer.addKeywordResult(Context, "static_cast");
2948 }
2949
2950 if (WantExpressionKeywords) {
2951 Consumer.addKeywordResult(Context, "sizeof");
2952 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2953 Consumer.addKeywordResult(Context, "false");
2954 Consumer.addKeywordResult(Context, "true");
2955 }
2956
2957 if (getLangOptions().CPlusPlus) {
2958 const char *CXXExprs[] = {
2959 "delete", "new", "operator", "throw", "typeid"
2960 };
2961 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2962 for (unsigned I = 0; I != NumCXXExprs; ++I)
2963 Consumer.addKeywordResult(Context, CXXExprs[I]);
2964
2965 if (isa<CXXMethodDecl>(CurContext) &&
2966 cast<CXXMethodDecl>(CurContext)->isInstance())
2967 Consumer.addKeywordResult(Context, "this");
2968
2969 if (getLangOptions().CPlusPlus0x) {
2970 Consumer.addKeywordResult(Context, "alignof");
2971 Consumer.addKeywordResult(Context, "nullptr");
2972 }
2973 }
2974 }
2975
2976 if (WantRemainingKeywords) {
2977 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2978 // Statements.
2979 const char *CStmts[] = {
2980 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2981 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2982 for (unsigned I = 0; I != NumCStmts; ++I)
2983 Consumer.addKeywordResult(Context, CStmts[I]);
2984
2985 if (getLangOptions().CPlusPlus) {
2986 Consumer.addKeywordResult(Context, "catch");
2987 Consumer.addKeywordResult(Context, "try");
2988 }
2989
2990 if (S && S->getBreakParent())
2991 Consumer.addKeywordResult(Context, "break");
2992
2993 if (S && S->getContinueParent())
2994 Consumer.addKeywordResult(Context, "continue");
2995
John McCall781472f2010-08-25 08:40:02 +00002996 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00002997 Consumer.addKeywordResult(Context, "case");
2998 Consumer.addKeywordResult(Context, "default");
2999 }
3000 } else {
3001 if (getLangOptions().CPlusPlus) {
3002 Consumer.addKeywordResult(Context, "namespace");
3003 Consumer.addKeywordResult(Context, "template");
3004 }
3005
3006 if (S && S->isClassScope()) {
3007 Consumer.addKeywordResult(Context, "explicit");
3008 Consumer.addKeywordResult(Context, "friend");
3009 Consumer.addKeywordResult(Context, "mutable");
3010 Consumer.addKeywordResult(Context, "private");
3011 Consumer.addKeywordResult(Context, "protected");
3012 Consumer.addKeywordResult(Context, "public");
3013 Consumer.addKeywordResult(Context, "virtual");
3014 }
3015 }
3016
3017 if (getLangOptions().CPlusPlus) {
3018 Consumer.addKeywordResult(Context, "using");
3019
3020 if (getLangOptions().CPlusPlus0x)
3021 Consumer.addKeywordResult(Context, "static_assert");
3022 }
3023 }
3024
3025 // If we haven't found anything, we're done.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003026 if (Consumer.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003027 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003028
3029 // Only allow a single, closest name in the result set (it's okay to
3030 // have overloads of that name, though).
Douglas Gregoraaf87162010-04-14 20:04:41 +00003031 DeclarationName BestName;
3032 NamedDecl *BestIvarOrPropertyDecl = 0;
3033 bool FoundIvarOrPropertyDecl = false;
3034
3035 // Check all of the declaration results to find the best name so far.
3036 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3037 IEnd = Consumer.end();
3038 I != IEnd; ++I) {
3039 if (!BestName)
3040 BestName = (*I)->getDeclName();
3041 else if (BestName != (*I)->getDeclName())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003042 return DeclarationName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003043
Douglas Gregoraaf87162010-04-14 20:04:41 +00003044 // \brief Keep track of either an Objective-C ivar or a property, but not
3045 // both.
3046 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
3047 if (FoundIvarOrPropertyDecl)
3048 BestIvarOrPropertyDecl = 0;
3049 else {
3050 BestIvarOrPropertyDecl = *I;
3051 FoundIvarOrPropertyDecl = true;
3052 }
3053 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003054 }
3055
Douglas Gregoraaf87162010-04-14 20:04:41 +00003056 // Now check all of the keyword results to find the best name.
3057 switch (Consumer.keyword_size()) {
3058 case 0:
3059 // No keywords matched.
3060 break;
3061
3062 case 1:
3063 // If we already have a name
3064 if (!BestName) {
3065 // We did not have anything previously,
3066 BestName = *Consumer.keyword_begin();
3067 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
3068 // We have a declaration with the same name as a context-sensitive
3069 // keyword. The keyword takes precedence.
3070 BestIvarOrPropertyDecl = 0;
3071 FoundIvarOrPropertyDecl = false;
3072 Consumer.clear_decls();
Douglas Gregord0785ea2010-05-18 16:30:22 +00003073 } else if (CTC == CTC_ObjCMessageReceiver &&
3074 (*Consumer.keyword_begin())->isStr("super")) {
3075 // In an Objective-C message send, give the "super" keyword a slight
3076 // edge over entities not in function or method scope.
3077 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3078 IEnd = Consumer.end();
3079 I != IEnd; ++I) {
3080 if ((*I)->getDeclName() == BestName) {
3081 if ((*I)->getDeclContext()->isFunctionOrMethod())
3082 return DeclarationName();
3083 }
3084 }
3085
3086 // Everything found was outside a function or method; the 'super'
3087 // keyword takes precedence.
3088 BestIvarOrPropertyDecl = 0;
3089 FoundIvarOrPropertyDecl = false;
3090 Consumer.clear_decls();
3091 BestName = *Consumer.keyword_begin();
Douglas Gregoraaf87162010-04-14 20:04:41 +00003092 } else {
3093 // Name collision; we will not correct typos.
3094 return DeclarationName();
3095 }
3096 break;
3097
3098 default:
3099 // Name collision; we will not correct typos.
3100 return DeclarationName();
3101 }
3102
Douglas Gregor546be3c2009-12-30 17:04:44 +00003103 // BestName is the closest viable name to what the user
3104 // typed. However, to make sure that we don't pick something that's
3105 // way off, make sure that the user typed at least 3 characters for
3106 // each correction.
3107 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregoraaf87162010-04-14 20:04:41 +00003108 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
3109 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregor931f98a2010-04-14 17:09:22 +00003110 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003111
3112 // Perform name lookup again with the name we chose, and declare
3113 // success if we found something that was not ambiguous.
3114 Res.clear();
3115 Res.setLookupName(BestName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003116
3117 // If we found an ivar or property, add that result; no further
3118 // lookup is required.
Douglas Gregoraaf87162010-04-14 20:04:41 +00003119 if (BestIvarOrPropertyDecl)
3120 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003121 // If we're looking into the context of a member, perform qualified
3122 // name lookup on the best name.
Douglas Gregoraaf87162010-04-14 20:04:41 +00003123 else if (!Consumer.keyword_empty()) {
3124 // The best match was a keyword. Return it.
3125 return BestName;
3126 } else if (MemberContext)
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003127 LookupQualifiedName(Res, MemberContext);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003128 // Perform lookup as if we had just parsed the best name.
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003129 else
3130 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3131 EnteringContext);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003132
3133 if (Res.isAmbiguous()) {
3134 Res.suppressDiagnostics();
Douglas Gregor931f98a2010-04-14 17:09:22 +00003135 return DeclarationName();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003136 }
3137
Douglas Gregor931f98a2010-04-14 17:09:22 +00003138 if (Res.getResultKind() != LookupResult::NotFound)
3139 return BestName;
3140
3141 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003142}