blob: 0e6a6a4f400ab7c34c278bb00ec1c4288acdd8ce [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/DeclSpec.h"
John McCall5f1e0942010-08-24 08:50:51 +000017#include "clang/Sema/Scope.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000021#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000024#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000025#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000026#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000028#include "clang/Basic/LangOptions.h"
29#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000030#include "llvm/ADT/SmallPtrSet.h"
John McCall6e247262009-10-10 05:48:19 +000031#include "llvm/Support/ErrorHandling.h"
Douglas Gregor546be3c2009-12-30 17:04:44 +000032#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000033#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000034#include <vector>
35#include <iterator>
36#include <utility>
37#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000038
39using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000040using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000041
John McCalld7be78a2009-11-10 07:01:13 +000042namespace {
43 class UnqualUsingEntry {
44 const DeclContext *Nominated;
45 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000046
John McCalld7be78a2009-11-10 07:01:13 +000047 public:
48 UnqualUsingEntry(const DeclContext *Nominated,
49 const DeclContext *CommonAncestor)
50 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
51 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000052
John McCalld7be78a2009-11-10 07:01:13 +000053 const DeclContext *getCommonAncestor() const {
54 return CommonAncestor;
55 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000056
John McCalld7be78a2009-11-10 07:01:13 +000057 const DeclContext *getNominatedNamespace() const {
58 return Nominated;
59 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000060
John McCalld7be78a2009-11-10 07:01:13 +000061 // Sort by the pointer value of the common ancestor.
62 struct Comparator {
63 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
64 return L.getCommonAncestor() < R.getCommonAncestor();
65 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000066
John McCalld7be78a2009-11-10 07:01:13 +000067 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
68 return E.getCommonAncestor() < DC;
69 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000070
John McCalld7be78a2009-11-10 07:01:13 +000071 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
72 return DC < E.getCommonAncestor();
73 }
74 };
75 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000076
John McCalld7be78a2009-11-10 07:01:13 +000077 /// A collection of using directives, as used by C++ unqualified
78 /// lookup.
79 class UnqualUsingDirectiveSet {
80 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000081
John McCalld7be78a2009-11-10 07:01:13 +000082 ListTy list;
83 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000084
John McCalld7be78a2009-11-10 07:01:13 +000085 public:
86 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000087
John McCalld7be78a2009-11-10 07:01:13 +000088 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
89 // C++ [namespace.udir]p1:
90 // During unqualified name lookup, the names appear as if they
91 // were declared in the nearest enclosing namespace which contains
92 // both the using-directive and the nominated namespace.
93 DeclContext *InnermostFileDC
94 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
95 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +000096
John McCalld7be78a2009-11-10 07:01:13 +000097 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +000098 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
99 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
100 visit(Ctx, EffectiveDC);
101 } else {
102 Scope::udir_iterator I = S->using_directives_begin(),
103 End = S->using_directives_end();
104
105 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000106 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000107 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000108 }
109 }
John McCalld7be78a2009-11-10 07:01:13 +0000110
111 // Visits a context and collect all of its using directives
112 // recursively. Treats all using directives as if they were
113 // declared in the context.
114 //
115 // A given context is only every visited once, so it is important
116 // that contexts be visited from the inside out in order to get
117 // the effective DCs right.
118 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
119 if (!visited.insert(DC))
120 return;
121
122 addUsingDirectives(DC, EffectiveDC);
123 }
124
125 // Visits a using directive and collects all of its using
126 // directives recursively. Treats all using directives as if they
127 // were declared in the effective DC.
128 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
129 DeclContext *NS = UD->getNominatedNamespace();
130 if (!visited.insert(NS))
131 return;
132
133 addUsingDirective(UD, EffectiveDC);
134 addUsingDirectives(NS, EffectiveDC);
135 }
136
137 // Adds all the using directives in a context (and those nominated
138 // by its using directives, transitively) as if they appeared in
139 // the given effective context.
140 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
141 llvm::SmallVector<DeclContext*,4> queue;
142 while (true) {
143 DeclContext::udir_iterator I, End;
144 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
145 UsingDirectiveDecl *UD = *I;
146 DeclContext *NS = UD->getNominatedNamespace();
147 if (visited.insert(NS)) {
148 addUsingDirective(UD, EffectiveDC);
149 queue.push_back(NS);
150 }
151 }
152
153 if (queue.empty())
154 return;
155
156 DC = queue.back();
157 queue.pop_back();
158 }
159 }
160
161 // Add a using directive as if it had been declared in the given
162 // context. This helps implement C++ [namespace.udir]p3:
163 // The using-directive is transitive: if a scope contains a
164 // using-directive that nominates a second namespace that itself
165 // contains using-directives, the effect is as if the
166 // using-directives from the second namespace also appeared in
167 // the first.
168 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
169 // Find the common ancestor between the effective context and
170 // the nominated namespace.
171 DeclContext *Common = UD->getNominatedNamespace();
172 while (!Common->Encloses(EffectiveDC))
173 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000174 Common = Common->getPrimaryContext();
John McCalld7be78a2009-11-10 07:01:13 +0000175
176 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
177 }
178
179 void done() {
180 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
181 }
182
183 typedef ListTy::iterator iterator;
184 typedef ListTy::const_iterator const_iterator;
185
186 iterator begin() { return list.begin(); }
187 iterator end() { return list.end(); }
188 const_iterator begin() const { return list.begin(); }
189 const_iterator end() const { return list.end(); }
190
191 std::pair<const_iterator,const_iterator>
192 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000193 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000194 UnqualUsingEntry::Comparator());
195 }
196 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000197}
198
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000199// Retrieve the set of identifier namespaces that correspond to a
200// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000201static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
202 bool CPlusPlus,
203 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000204 unsigned IDNS = 0;
205 switch (NameKind) {
206 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000207 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000208 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000209 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000210 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCall1d7c5282009-12-18 10:40:03 +0000211 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
212 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000213 break;
214
John McCall76d32642010-04-24 01:30:58 +0000215 case Sema::LookupOperatorName:
216 // Operator lookup is its own crazy thing; it is not the same
217 // as (e.g.) looking up an operator name for redeclaration.
218 assert(!Redeclaration && "cannot do redeclaration operator lookup");
219 IDNS = Decl::IDNS_NonMemberOperator;
220 break;
221
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000222 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000223 if (CPlusPlus) {
224 IDNS = Decl::IDNS_Type;
225
226 // When looking for a redeclaration of a tag name, we add:
227 // 1) TagFriend to find undeclared friend decls
228 // 2) Namespace because they can't "overload" with tag decls.
229 // 3) Tag because it includes class templates, which can't
230 // "overload" with tag decls.
231 if (Redeclaration)
232 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
233 } else {
234 IDNS = Decl::IDNS_Tag;
235 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000236 break;
237
238 case Sema::LookupMemberName:
239 IDNS = Decl::IDNS_Member;
240 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000241 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000242 break;
243
244 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000245 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
246 break;
247
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000248 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000249 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000250 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000251
John McCall9f54ad42009-12-10 09:41:52 +0000252 case Sema::LookupUsingDeclName:
253 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
254 | Decl::IDNS_Member | Decl::IDNS_Using;
255 break;
256
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000257 case Sema::LookupObjCProtocolName:
258 IDNS = Decl::IDNS_ObjCProtocol;
259 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000260
261 case Sema::LookupAnyName:
262 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
263 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
264 | Decl::IDNS_Type;
265 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000266 }
267 return IDNS;
268}
269
John McCall1d7c5282009-12-18 10:40:03 +0000270void LookupResult::configure() {
271 IDNS = getIDNS(LookupKind,
272 SemaRef.getLangOptions().CPlusPlus,
273 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000274
275 // If we're looking for one of the allocation or deallocation
276 // operators, make sure that the implicitly-declared new and delete
277 // operators can be found.
278 if (!isForRedeclaration()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000279 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000280 case OO_New:
281 case OO_Delete:
282 case OO_Array_New:
283 case OO_Array_Delete:
284 SemaRef.DeclareGlobalNewDelete();
285 break;
286
287 default:
288 break;
289 }
290 }
John McCall1d7c5282009-12-18 10:40:03 +0000291}
292
John McCall2a7fb272010-08-25 05:32:35 +0000293#ifndef NDEBUG
294void LookupResult::sanity() const {
295 assert(ResultKind != NotFound || Decls.size() == 0);
296 assert(ResultKind != Found || Decls.size() == 1);
297 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
298 (Decls.size() == 1 &&
299 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
300 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
301 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
302 (Decls.size() == 1 && Ambiguity == AmbiguousBaseSubobjects));
303 assert((Paths != NULL) == (ResultKind == Ambiguous &&
304 (Ambiguity == AmbiguousBaseSubobjectTypes ||
305 Ambiguity == AmbiguousBaseSubobjects)));
306}
307#endif
308
John McCallf36e02d2009-10-09 21:13:30 +0000309// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000310void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000311 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000312}
313
John McCall7453ed42009-11-22 00:44:51 +0000314/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000315void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000316 unsigned N = Decls.size();
John McCall9f54ad42009-12-10 09:41:52 +0000317
John McCallf36e02d2009-10-09 21:13:30 +0000318 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000319 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000320 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000321 return;
322 }
323
John McCall7453ed42009-11-22 00:44:51 +0000324 // If there's a single decl, we need to examine it to decide what
325 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000326 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000327 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
328 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000329 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000330 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000331 ResultKind = FoundUnresolvedValue;
332 return;
333 }
John McCallf36e02d2009-10-09 21:13:30 +0000334
John McCall6e247262009-10-10 05:48:19 +0000335 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000336 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000337
John McCallf36e02d2009-10-09 21:13:30 +0000338 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000339 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
340
John McCallf36e02d2009-10-09 21:13:30 +0000341 bool Ambiguous = false;
342 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000343 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000344
345 unsigned UniqueTagIndex = 0;
346
347 unsigned I = 0;
348 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000349 NamedDecl *D = Decls[I]->getUnderlyingDecl();
350 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000351
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000352 // Redeclarations of types via typedef can occur both within a scope
353 // and, through using declarations and directives, across scopes. There is
354 // no ambiguity if they all refer to the same type, so unique based on the
355 // canonical type.
356 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
357 if (!TD->getDeclContext()->isRecord()) {
358 QualType T = SemaRef.Context.getTypeDeclType(TD);
359 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
360 // The type is not unique; pull something off the back and continue
361 // at this index.
362 Decls[I] = Decls[--N];
363 continue;
364 }
365 }
366 }
367
John McCall314be4e2009-11-17 07:50:12 +0000368 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000369 // If it's not unique, pull something off the back (and
370 // continue at this index).
371 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000372 continue;
373 }
374
375 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000376
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000377 if (isa<UnresolvedUsingValueDecl>(D)) {
378 HasUnresolved = true;
379 } else if (isa<TagDecl>(D)) {
380 if (HasTag)
381 Ambiguous = true;
382 UniqueTagIndex = I;
383 HasTag = true;
384 } else if (isa<FunctionTemplateDecl>(D)) {
385 HasFunction = true;
386 HasFunctionTemplate = true;
387 } else if (isa<FunctionDecl>(D)) {
388 HasFunction = true;
389 } else {
390 if (HasNonFunction)
391 Ambiguous = true;
392 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000393 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000394 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000395 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000396
John McCallf36e02d2009-10-09 21:13:30 +0000397 // C++ [basic.scope.hiding]p2:
398 // A class name or enumeration name can be hidden by the name of
399 // an object, function, or enumerator declared in the same
400 // scope. If a class or enumeration name and an object, function,
401 // or enumerator are declared in the same scope (in any order)
402 // with the same name, the class or enumeration name is hidden
403 // wherever the object, function, or enumerator name is visible.
404 // But it's still an error if there are distinct tag types found,
405 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000406 if (HideTags && HasTag && !Ambiguous &&
407 (HasFunction || HasNonFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000408 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000409
John McCallf36e02d2009-10-09 21:13:30 +0000410 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000411
John McCallfda8e122009-12-03 00:58:24 +0000412 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000413 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000414
John McCallf36e02d2009-10-09 21:13:30 +0000415 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000416 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000417 else if (HasUnresolved)
418 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000419 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000420 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000421 else
John McCalla24dc2e2009-11-17 02:14:36 +0000422 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000423}
424
John McCall7d384dd2009-11-18 07:57:50 +0000425void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000426 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000427 DeclContext::lookup_iterator DI, DE;
428 for (I = P.begin(), E = P.end(); I != E; ++I)
429 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
430 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000431}
432
John McCall7d384dd2009-11-18 07:57:50 +0000433void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000434 Paths = new CXXBasePaths;
435 Paths->swap(P);
436 addDeclsFromBasePaths(*Paths);
437 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000438 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000439}
440
John McCall7d384dd2009-11-18 07:57:50 +0000441void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000442 Paths = new CXXBasePaths;
443 Paths->swap(P);
444 addDeclsFromBasePaths(*Paths);
445 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000446 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000447}
448
John McCall7d384dd2009-11-18 07:57:50 +0000449void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000450 Out << Decls.size() << " result(s)";
451 if (isAmbiguous()) Out << ", ambiguous";
452 if (Paths) Out << ", base paths present";
453
454 for (iterator I = begin(), E = end(); I != E; ++I) {
455 Out << "\n";
456 (*I)->print(Out, 2);
457 }
458}
459
Douglas Gregor85910982010-02-12 05:48:04 +0000460/// \brief Lookup a builtin function, when name lookup would otherwise
461/// fail.
462static bool LookupBuiltin(Sema &S, LookupResult &R) {
463 Sema::LookupNameKind NameKind = R.getLookupKind();
464
465 // If we didn't find a use of this identifier, and if the identifier
466 // corresponds to a compiler builtin, create the decl object for the builtin
467 // now, injecting it into translation unit scope, and return it.
468 if (NameKind == Sema::LookupOrdinaryName ||
469 NameKind == Sema::LookupRedeclarationWithLinkage) {
470 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
471 if (II) {
472 // If this is a builtin on this (or all) targets, create the decl.
473 if (unsigned BuiltinID = II->getBuiltinID()) {
474 // In C++, we don't have any predefined library functions like
475 // 'malloc'. Instead, we'll just error.
476 if (S.getLangOptions().CPlusPlus &&
477 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
478 return false;
479
480 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
481 S.TUScope, R.isForRedeclaration(),
482 R.getNameLoc());
483 if (D)
484 R.addDecl(D);
485 return (D != NULL);
486 }
487 }
488 }
489
490 return false;
491}
492
Douglas Gregor4923aa22010-07-02 20:37:36 +0000493/// \brief Determine whether we can declare a special member function within
494/// the class at this point.
495static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
496 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000497 // Don't do it if the class is invalid.
498 if (Class->isInvalidDecl())
499 return false;
500
Douglas Gregor4923aa22010-07-02 20:37:36 +0000501 // We need to have a definition for the class.
502 if (!Class->getDefinition() || Class->isDependentContext())
503 return false;
504
505 // We can't be in the middle of defining the class.
506 if (const RecordType *RecordTy
507 = Context.getTypeDeclType(Class)->getAs<RecordType>())
508 return !RecordTy->isBeingDefined();
509
510 return false;
511}
512
513void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000514 if (!CanDeclareSpecialMemberFunction(Context, Class))
515 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000516
517 // If the default constructor has not yet been declared, do so now.
518 if (!Class->hasDeclaredDefaultConstructor())
519 DeclareImplicitDefaultConstructor(Class);
Douglas Gregor22584312010-07-02 23:41:54 +0000520
521 // If the copy constructor has not yet been declared, do so now.
522 if (!Class->hasDeclaredCopyConstructor())
523 DeclareImplicitCopyConstructor(Class);
524
Douglas Gregora376d102010-07-02 21:50:04 +0000525 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000526 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000527 DeclareImplicitCopyAssignment(Class);
528
Douglas Gregor4923aa22010-07-02 20:37:36 +0000529 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000530 if (!Class->hasDeclaredDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +0000531 DeclareImplicitDestructor(Class);
532}
533
Douglas Gregora376d102010-07-02 21:50:04 +0000534/// \brief Determine whether this is the name of an implicitly-declared
535/// special member function.
536static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
537 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000538 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000539 case DeclarationName::CXXDestructorName:
540 return true;
541
542 case DeclarationName::CXXOperatorName:
543 return Name.getCXXOverloadedOperator() == OO_Equal;
544
545 default:
546 break;
547 }
548
549 return false;
550}
551
552/// \brief If there are any implicit member functions with the given name
553/// that need to be declared in the given declaration context, do so.
554static void DeclareImplicitMemberFunctionsWithName(Sema &S,
555 DeclarationName Name,
556 const DeclContext *DC) {
557 if (!DC)
558 return;
559
560 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000561 case DeclarationName::CXXConstructorName:
562 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000563 if (Record->getDefinition() &&
564 CanDeclareSpecialMemberFunction(S.Context, Record)) {
565 if (!Record->hasDeclaredDefaultConstructor())
566 S.DeclareImplicitDefaultConstructor(
567 const_cast<CXXRecordDecl *>(Record));
568 if (!Record->hasDeclaredCopyConstructor())
569 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
570 }
Douglas Gregor22584312010-07-02 23:41:54 +0000571 break;
572
Douglas Gregora376d102010-07-02 21:50:04 +0000573 case DeclarationName::CXXDestructorName:
574 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
575 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
576 CanDeclareSpecialMemberFunction(S.Context, Record))
577 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000578 break;
579
580 case DeclarationName::CXXOperatorName:
581 if (Name.getCXXOverloadedOperator() != OO_Equal)
582 break;
583
584 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
585 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
586 CanDeclareSpecialMemberFunction(S.Context, Record))
587 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
588 break;
589
590 default:
591 break;
592 }
593}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000594
John McCallf36e02d2009-10-09 21:13:30 +0000595// Adds all qualifying matches for a name within a decl context to the
596// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000597static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000598 bool Found = false;
599
Douglas Gregor4923aa22010-07-02 20:37:36 +0000600 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000601 if (S.getLangOptions().CPlusPlus)
602 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000603
604 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000605 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000606 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000607 NamedDecl *D = *I;
608 if (R.isAcceptableDecl(D)) {
609 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000610 Found = true;
611 }
612 }
John McCallf36e02d2009-10-09 21:13:30 +0000613
Douglas Gregor85910982010-02-12 05:48:04 +0000614 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
615 return true;
616
Douglas Gregor48026d22010-01-11 18:40:55 +0000617 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000618 != DeclarationName::CXXConversionFunctionName ||
619 R.getLookupName().getCXXNameType()->isDependentType() ||
620 !isa<CXXRecordDecl>(DC))
621 return Found;
622
623 // C++ [temp.mem]p6:
624 // A specialization of a conversion function template is not found by
625 // name lookup. Instead, any conversion function templates visible in the
626 // context of the use are considered. [...]
627 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
628 if (!Record->isDefinition())
629 return Found;
630
631 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
632 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
633 UEnd = Unresolved->end(); U != UEnd; ++U) {
634 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
635 if (!ConvTemplate)
636 continue;
637
638 // When we're performing lookup for the purposes of redeclaration, just
639 // add the conversion function template. When we deduce template
640 // arguments for specializations, we'll end up unifying the return
641 // type of the new declaration with the type of the function template.
642 if (R.isForRedeclaration()) {
643 R.addDecl(ConvTemplate);
644 Found = true;
645 continue;
646 }
647
Douglas Gregor48026d22010-01-11 18:40:55 +0000648 // C++ [temp.mem]p6:
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000649 // [...] For each such operator, if argument deduction succeeds
650 // (14.9.2.3), the resulting specialization is used as if found by
651 // name lookup.
652 //
653 // When referencing a conversion function for any purpose other than
654 // a redeclaration (such that we'll be building an expression with the
655 // result), perform template argument deduction and place the
656 // specialization into the result set. We do this to avoid forcing all
657 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000658 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000659 FunctionDecl *Specialization = 0;
660
661 const FunctionProtoType *ConvProto
662 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
663 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000664
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000665 // Compute the type of the function that we would expect the conversion
666 // function to have, if it were to match the name given.
667 // FIXME: Calling convention!
Rafael Espindola264ba482010-03-30 20:24:48 +0000668 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000669 QualType ExpectedType
670 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
671 0, 0, ConvProto->isVariadic(),
672 ConvProto->getTypeQuals(),
673 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000674 ConvProtoInfo.withCallingConv(CC_Default));
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000675
676 // Perform template argument deduction against the type that we would
677 // expect the function to have.
678 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
679 Specialization, Info)
680 == Sema::TDK_Success) {
681 R.addDecl(Specialization);
682 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000683 }
684 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000685
John McCallf36e02d2009-10-09 21:13:30 +0000686 return Found;
687}
688
John McCalld7be78a2009-11-10 07:01:13 +0000689// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000690static bool
Douglas Gregor85910982010-02-12 05:48:04 +0000691CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
692 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000693
694 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
695
John McCalld7be78a2009-11-10 07:01:13 +0000696 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000697 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000698
John McCalld7be78a2009-11-10 07:01:13 +0000699 // Perform direct name lookup into the namespaces nominated by the
700 // using directives whose common ancestor is this namespace.
701 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
702 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000703
John McCalld7be78a2009-11-10 07:01:13 +0000704 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000705 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000706 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000707
708 R.resolveKind();
709
710 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000711}
712
713static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000714 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000715 return Ctx->isFileContext();
716 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000717}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000718
Douglas Gregor711be1e2010-03-15 14:33:29 +0000719// Find the next outer declaration context from this scope. This
720// routine actually returns the semantic outer context, which may
721// differ from the lexical context (encoded directly in the Scope
722// stack) when we are parsing a member of a class template. In this
723// case, the second element of the pair will be true, to indicate that
724// name lookup should continue searching in this semantic context when
725// it leaves the current template parameter scope.
726static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
727 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
728 DeclContext *Lexical = 0;
729 for (Scope *OuterS = S->getParent(); OuterS;
730 OuterS = OuterS->getParent()) {
731 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000732 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000733 break;
734 }
735 }
736
737 // C++ [temp.local]p8:
738 // In the definition of a member of a class template that appears
739 // outside of the namespace containing the class template
740 // definition, the name of a template-parameter hides the name of
741 // a member of this namespace.
742 //
743 // Example:
744 //
745 // namespace N {
746 // class C { };
747 //
748 // template<class T> class B {
749 // void f(T);
750 // };
751 // }
752 //
753 // template<class C> void N::B<C>::f(C) {
754 // C b; // C is the template parameter, not N::C
755 // }
756 //
757 // In this example, the lexical context we return is the
758 // TranslationUnit, while the semantic context is the namespace N.
759 if (!Lexical || !DC || !S->getParent() ||
760 !S->getParent()->isTemplateParamScope())
761 return std::make_pair(Lexical, false);
762
763 // Find the outermost template parameter scope.
764 // For the example, this is the scope for the template parameters of
765 // template<class C>.
766 Scope *OutermostTemplateScope = S->getParent();
767 while (OutermostTemplateScope->getParent() &&
768 OutermostTemplateScope->getParent()->isTemplateParamScope())
769 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregore942bbe2009-09-10 16:57:35 +0000770
Douglas Gregor711be1e2010-03-15 14:33:29 +0000771 // Find the namespace context in which the original scope occurs. In
772 // the example, this is namespace N.
773 DeclContext *Semantic = DC;
774 while (!Semantic->isFileContext())
775 Semantic = Semantic->getParent();
776
777 // Find the declaration context just outside of the template
778 // parameter scope. This is the context in which the template is
779 // being lexically declaration (a namespace context). In the
780 // example, this is the global scope.
781 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
782 Lexical->Encloses(Semantic))
783 return std::make_pair(Semantic, true);
784
785 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000786}
787
John McCalla24dc2e2009-11-17 02:14:36 +0000788bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000789 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000790
791 DeclarationName Name = R.getLookupName();
792
Douglas Gregora376d102010-07-02 21:50:04 +0000793 // If this is the name of an implicitly-declared special member function,
794 // go through the scope stack to implicitly declare
795 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
796 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
797 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
798 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
799 }
800
801 // Implicitly declare member functions with the name we're looking for, if in
802 // fact we are in a scope where it matters.
803
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000804 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000805 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000806 I = IdResolver.begin(Name),
807 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000808
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000809 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000810 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000811 // ...During unqualified name lookup (3.4.1), the names appear as if
812 // they were declared in the nearest enclosing namespace which contains
813 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000814 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000815 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000816 //
817 // For example:
818 // namespace A { int i; }
819 // void foo() {
820 // int i;
821 // {
822 // using namespace A;
823 // ++i; // finds local 'i', A::i appears at global scope
824 // }
825 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000826 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000827 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000828 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000829 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
830
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000831 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000832 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000833 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000834 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000835 Found = true;
836 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000837 }
838 }
John McCallf36e02d2009-10-09 21:13:30 +0000839 if (Found) {
840 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000841 if (S->isClassScope())
842 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
843 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000844 return true;
845 }
846
Douglas Gregor711be1e2010-03-15 14:33:29 +0000847 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
848 S->getParent() && !S->getParent()->isTemplateParamScope()) {
849 // We've just searched the last template parameter scope and
850 // found nothing, so look into the the contexts between the
851 // lexical and semantic declaration contexts returned by
852 // findOuterContext(). This implements the name lookup behavior
853 // of C++ [temp.local]p8.
854 Ctx = OutsideOfTemplateParamDC;
855 OutsideOfTemplateParamDC = 0;
856 }
857
858 if (Ctx) {
859 DeclContext *OuterCtx;
860 bool SearchAfterTemplateScope;
861 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
862 if (SearchAfterTemplateScope)
863 OutsideOfTemplateParamDC = OuterCtx;
864
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000865 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000866 // We do not directly look into transparent contexts, since
867 // those entities will be found in the nearest enclosing
868 // non-transparent context.
869 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000870 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000871
872 // We do not look directly into function or method contexts,
873 // since all of the local variables and parameters of the
874 // function/method are present within the Scope.
875 if (Ctx->isFunctionOrMethod()) {
876 // If we have an Objective-C instance method, look for ivars
877 // in the corresponding interface.
878 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
879 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
880 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
881 ObjCInterfaceDecl *ClassDeclared;
882 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
883 Name.getAsIdentifierInfo(),
884 ClassDeclared)) {
885 if (R.isAcceptableDecl(Ivar)) {
886 R.addDecl(Ivar);
887 R.resolveKind();
888 return true;
889 }
890 }
891 }
892 }
893
894 continue;
895 }
896
Douglas Gregore942bbe2009-09-10 16:57:35 +0000897 // Perform qualified name lookup into this context.
898 // FIXME: In some cases, we know that every name that could be found by
899 // this qualified name lookup will also be on the identifier chain. For
900 // example, inside a class without any base classes, we never need to
901 // perform qualified lookup because all of the members are on top of the
902 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000903 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000904 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000905 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000906 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000907 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000908
John McCalld7be78a2009-11-10 07:01:13 +0000909 // Stop if we ran out of scopes.
910 // FIXME: This really, really shouldn't be happening.
911 if (!S) return false;
912
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000913 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000914 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000915 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000916 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
917 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000918
John McCalld7be78a2009-11-10 07:01:13 +0000919 UnqualUsingDirectiveSet UDirs;
920 UDirs.visitScopeChain(Initial, S);
921 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000922
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000923 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000924 // Unqualified name lookup in C++ requires looking into scopes
925 // that aren't strictly lexical, and therefore we walk through the
926 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000927
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000928 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000929 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000930 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000931 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000932 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000933 // We found something. Look for anything else in our scope
934 // with this same name and in an acceptable identifier
935 // namespace, so that we can construct an overload set if we
936 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000937 Found = true;
938 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000939 }
940 }
941
Douglas Gregor00b4b032010-05-14 04:53:42 +0000942 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000943 R.resolveKind();
944 return true;
945 }
946
Douglas Gregor00b4b032010-05-14 04:53:42 +0000947 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
948 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
949 S->getParent() && !S->getParent()->isTemplateParamScope()) {
950 // We've just searched the last template parameter scope and
951 // found nothing, so look into the the contexts between the
952 // lexical and semantic declaration contexts returned by
953 // findOuterContext(). This implements the name lookup behavior
954 // of C++ [temp.local]p8.
955 Ctx = OutsideOfTemplateParamDC;
956 OutsideOfTemplateParamDC = 0;
957 }
958
959 if (Ctx) {
960 DeclContext *OuterCtx;
961 bool SearchAfterTemplateScope;
962 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
963 if (SearchAfterTemplateScope)
964 OutsideOfTemplateParamDC = OuterCtx;
965
966 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
967 // We do not directly look into transparent contexts, since
968 // those entities will be found in the nearest enclosing
969 // non-transparent context.
970 if (Ctx->isTransparentContext())
971 continue;
972
973 // If we have a context, and it's not a context stashed in the
974 // template parameter scope for an out-of-line definition, also
975 // look into that context.
976 if (!(Found && S && S->isTemplateParamScope())) {
977 assert(Ctx->isFileContext() &&
978 "We should have been looking only at file context here already.");
979
980 // Look into context considering using-directives.
981 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
982 Found = true;
983 }
984
985 if (Found) {
986 R.resolveKind();
987 return true;
988 }
989
990 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
991 return false;
992 }
993 }
994
Douglas Gregor1df0ee92010-02-05 07:07:10 +0000995 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000996 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000997 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000998
John McCallf36e02d2009-10-09 21:13:30 +0000999 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001000}
1001
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001002/// @brief Perform unqualified name lookup starting from a given
1003/// scope.
1004///
1005/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1006/// used to find names within the current scope. For example, 'x' in
1007/// @code
1008/// int x;
1009/// int f() {
1010/// return x; // unqualified name look finds 'x' in the global scope
1011/// }
1012/// @endcode
1013///
1014/// Different lookup criteria can find different names. For example, a
1015/// particular scope can have both a struct and a function of the same
1016/// name, and each can be found by certain lookup criteria. For more
1017/// information about lookup criteria, see the documentation for the
1018/// class LookupCriteria.
1019///
1020/// @param S The scope from which unqualified name lookup will
1021/// begin. If the lookup criteria permits, name lookup may also search
1022/// in the parent scopes.
1023///
1024/// @param Name The name of the entity that we are searching for.
1025///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001026/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001027/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001028/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001029///
1030/// @returns The result of name lookup, which includes zero or more
1031/// declarations and possibly additional information used to diagnose
1032/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001033bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1034 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001035 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001036
John McCalla24dc2e2009-11-17 02:14:36 +00001037 LookupNameKind NameKind = R.getLookupKind();
1038
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001039 if (!getLangOptions().CPlusPlus) {
1040 // Unqualified name lookup in C/Objective-C is purely lexical, so
1041 // search in the declarations attached to the name.
1042
John McCall1d7c5282009-12-18 10:40:03 +00001043 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001044 // Find the nearest non-transparent declaration scope.
1045 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001046 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001047 static_cast<DeclContext *>(S->getEntity())
1048 ->isTransparentContext()))
1049 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001050 }
1051
John McCall1d7c5282009-12-18 10:40:03 +00001052 unsigned IDNS = R.getIdentifierNamespace();
1053
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001054 // Scan up the scope chain looking for a decl that matches this
1055 // identifier that is in the appropriate namespace. This search
1056 // should not take long, as shadowing of names is uncommon, and
1057 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001058 bool LeftStartingScope = false;
1059
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001060 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001061 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001062 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001063 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001064 if (NameKind == LookupRedeclarationWithLinkage) {
1065 // Determine whether this (or a previous) declaration is
1066 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001067 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001068 LeftStartingScope = true;
1069
1070 // If we found something outside of our starting scope that
1071 // does not have linkage, skip it.
1072 if (LeftStartingScope && !((*I)->hasLinkage()))
1073 continue;
1074 }
1075
John McCallf36e02d2009-10-09 21:13:30 +00001076 R.addDecl(*I);
1077
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001078 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001079 // If this declaration has the "overloadable" attribute, we
1080 // might have a set of overloaded functions.
1081
1082 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001083 while (!(S->getFlags() & Scope::DeclScope) ||
John McCalld226f652010-08-21 09:40:31 +00001084 !S->isDeclScope(*I))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001085 S = S->getParent();
1086
1087 // Find the last declaration in this scope (with the same
1088 // name, naturally).
1089 IdentifierResolver::iterator LastI = I;
1090 for (++LastI; LastI != IEnd; ++LastI) {
John McCalld226f652010-08-21 09:40:31 +00001091 if (!S->isDeclScope(*LastI))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001092 break;
John McCallf36e02d2009-10-09 21:13:30 +00001093 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001094 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001095 }
1096
John McCallf36e02d2009-10-09 21:13:30 +00001097 R.resolveKind();
1098
1099 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001100 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001101 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001102 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001103 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001104 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001105 }
1106
1107 // If we didn't find a use of this identifier, and if the identifier
1108 // corresponds to a compiler builtin, create the decl object for the builtin
1109 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +00001110 if (AllowBuiltinCreation)
1111 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001112
John McCallf36e02d2009-10-09 21:13:30 +00001113 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001114}
1115
John McCall6e247262009-10-10 05:48:19 +00001116/// @brief Perform qualified name lookup in the namespaces nominated by
1117/// using directives by the given context.
1118///
1119/// C++98 [namespace.qual]p2:
1120/// Given X::m (where X is a user-declared namespace), or given ::m
1121/// (where X is the global namespace), let S be the set of all
1122/// declarations of m in X and in the transitive closure of all
1123/// namespaces nominated by using-directives in X and its used
1124/// namespaces, except that using-directives are ignored in any
1125/// namespace, including X, directly containing one or more
1126/// declarations of m. No namespace is searched more than once in
1127/// the lookup of a name. If S is the empty set, the program is
1128/// ill-formed. Otherwise, if S has exactly one member, or if the
1129/// context of the reference is a using-declaration
1130/// (namespace.udecl), S is the required set of declarations of
1131/// m. Otherwise if the use of m is not one that allows a unique
1132/// declaration to be chosen from S, the program is ill-formed.
1133/// C++98 [namespace.qual]p5:
1134/// During the lookup of a qualified namespace member name, if the
1135/// lookup finds more than one declaration of the member, and if one
1136/// declaration introduces a class name or enumeration name and the
1137/// other declarations either introduce the same object, the same
1138/// enumerator or a set of functions, the non-type name hides the
1139/// class or enumeration name if and only if the declarations are
1140/// from the same namespace; otherwise (the declarations are from
1141/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001142static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001143 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001144 assert(StartDC->isFileContext() && "start context is not a file context");
1145
1146 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1147 DeclContext::udir_iterator E = StartDC->using_directives_end();
1148
1149 if (I == E) return false;
1150
1151 // We have at least added all these contexts to the queue.
1152 llvm::DenseSet<DeclContext*> Visited;
1153 Visited.insert(StartDC);
1154
1155 // We have not yet looked into these namespaces, much less added
1156 // their "using-children" to the queue.
1157 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1158
1159 // We have already looked into the initial namespace; seed the queue
1160 // with its using-children.
1161 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001162 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001163 if (Visited.insert(ND).second)
1164 Queue.push_back(ND);
1165 }
1166
1167 // The easiest way to implement the restriction in [namespace.qual]p5
1168 // is to check whether any of the individual results found a tag
1169 // and, if so, to declare an ambiguity if the final result is not
1170 // a tag.
1171 bool FoundTag = false;
1172 bool FoundNonTag = false;
1173
John McCall7d384dd2009-11-18 07:57:50 +00001174 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001175
1176 bool Found = false;
1177 while (!Queue.empty()) {
1178 NamespaceDecl *ND = Queue.back();
1179 Queue.pop_back();
1180
1181 // We go through some convolutions here to avoid copying results
1182 // between LookupResults.
1183 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001184 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001185 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001186
1187 if (FoundDirect) {
1188 // First do any local hiding.
1189 DirectR.resolveKind();
1190
1191 // If the local result is a tag, remember that.
1192 if (DirectR.isSingleTagDecl())
1193 FoundTag = true;
1194 else
1195 FoundNonTag = true;
1196
1197 // Append the local results to the total results if necessary.
1198 if (UseLocal) {
1199 R.addAllDecls(LocalR);
1200 LocalR.clear();
1201 }
1202 }
1203
1204 // If we find names in this namespace, ignore its using directives.
1205 if (FoundDirect) {
1206 Found = true;
1207 continue;
1208 }
1209
1210 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1211 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1212 if (Visited.insert(Nom).second)
1213 Queue.push_back(Nom);
1214 }
1215 }
1216
1217 if (Found) {
1218 if (FoundTag && FoundNonTag)
1219 R.setAmbiguousQualifiedTagHiding();
1220 else
1221 R.resolveKind();
1222 }
1223
1224 return Found;
1225}
1226
Douglas Gregor8071e422010-08-15 06:18:01 +00001227/// \brief Callback that looks for any member of a class with the given name.
1228static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1229 CXXBasePath &Path,
1230 void *Name) {
1231 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1232
1233 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1234 Path.Decls = BaseRecord->lookup(N);
1235 return Path.Decls.first != Path.Decls.second;
1236}
1237
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001238/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001239///
1240/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1241/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001242/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001243///
1244/// Different lookup criteria can find different names. For example, a
1245/// particular scope can have both a struct and a function of the same
1246/// name, and each can be found by certain lookup criteria. For more
1247/// information about lookup criteria, see the documentation for the
1248/// class LookupCriteria.
1249///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001250/// \param R captures both the lookup criteria and any lookup results found.
1251///
1252/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001253/// search. If the lookup criteria permits, name lookup may also search
1254/// in the parent contexts or (for C++ classes) base classes.
1255///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001256/// \param InUnqualifiedLookup true if this is qualified name lookup that
1257/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001258///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001259/// \returns true if lookup succeeded, false if it failed.
1260bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1261 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001262 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001263
John McCalla24dc2e2009-11-17 02:14:36 +00001264 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001265 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001267 // Make sure that the declaration context is complete.
1268 assert((!isa<TagDecl>(LookupCtx) ||
1269 LookupCtx->isDependentContext() ||
1270 cast<TagDecl>(LookupCtx)->isDefinition() ||
1271 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1272 ->isBeingDefined()) &&
1273 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001275 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001276 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001277 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001278 if (isa<CXXRecordDecl>(LookupCtx))
1279 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001280 return true;
1281 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001282
John McCall6e247262009-10-10 05:48:19 +00001283 // Don't descend into implied contexts for redeclarations.
1284 // C++98 [namespace.qual]p6:
1285 // In a declaration for a namespace member in which the
1286 // declarator-id is a qualified-id, given that the qualified-id
1287 // for the namespace member has the form
1288 // nested-name-specifier unqualified-id
1289 // the unqualified-id shall name a member of the namespace
1290 // designated by the nested-name-specifier.
1291 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001292 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001293 return false;
1294
John McCalla24dc2e2009-11-17 02:14:36 +00001295 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001296 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001297 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001298
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001299 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001300 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001301 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001302 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001303 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001304
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001305 // If we're performing qualified name lookup into a dependent class,
1306 // then we are actually looking into a current instantiation. If we have any
1307 // dependent base classes, then we either have to delay lookup until
1308 // template instantiation time (at which point all bases will be available)
1309 // or we have to fail.
1310 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1311 LookupRec->hasAnyDependentBases()) {
1312 R.setNotFoundInCurrentInstantiation();
1313 return false;
1314 }
1315
Douglas Gregor7176fff2009-01-15 00:26:24 +00001316 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001317 CXXBasePaths Paths;
1318 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001319
1320 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001321 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001322 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001323 case LookupOrdinaryName:
1324 case LookupMemberName:
1325 case LookupRedeclarationWithLinkage:
1326 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1327 break;
1328
1329 case LookupTagName:
1330 BaseCallback = &CXXRecordDecl::FindTagMember;
1331 break;
John McCall9f54ad42009-12-10 09:41:52 +00001332
Douglas Gregor8071e422010-08-15 06:18:01 +00001333 case LookupAnyName:
1334 BaseCallback = &LookupAnyMember;
1335 break;
1336
John McCall9f54ad42009-12-10 09:41:52 +00001337 case LookupUsingDeclName:
1338 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001339
1340 case LookupOperatorName:
1341 case LookupNamespaceName:
1342 case LookupObjCProtocolName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001343 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001344 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001345
1346 case LookupNestedNameSpecifierName:
1347 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1348 break;
1349 }
1350
John McCalla24dc2e2009-11-17 02:14:36 +00001351 if (!LookupRec->lookupInBases(BaseCallback,
1352 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001353 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001354
John McCall92f88312010-01-23 00:46:32 +00001355 R.setNamingClass(LookupRec);
1356
Douglas Gregor7176fff2009-01-15 00:26:24 +00001357 // C++ [class.member.lookup]p2:
1358 // [...] If the resulting set of declarations are not all from
1359 // sub-objects of the same type, or the set has a nonstatic member
1360 // and includes members from distinct sub-objects, there is an
1361 // ambiguity and the program is ill-formed. Otherwise that set is
1362 // the result of the lookup.
1363 // FIXME: support using declarations!
1364 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001365 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001366 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001367 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001368 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001369 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001370
John McCall46460a62010-01-20 21:53:11 +00001371 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1372 // across all paths.
1373 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1374
Douglas Gregor7176fff2009-01-15 00:26:24 +00001375 // Determine whether we're looking at a distinct sub-object or not.
1376 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001377 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001378 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1379 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00001380 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001381 != Context.getCanonicalType(PathElement.Base->getType())) {
1382 // We found members of the given name in two subobjects of
1383 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001384 R.setAmbiguousBaseSubobjectTypes(Paths);
1385 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001386 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1387 // We have a different subobject of the same type.
1388
1389 // C++ [class.member.lookup]p5:
1390 // A static member, a nested type or an enumerator defined in
1391 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001392 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001393 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001394 if (isa<VarDecl>(FirstDecl) ||
1395 isa<TypeDecl>(FirstDecl) ||
1396 isa<EnumConstantDecl>(FirstDecl))
1397 continue;
1398
1399 if (isa<CXXMethodDecl>(FirstDecl)) {
1400 // Determine whether all of the methods are static.
1401 bool AllMethodsAreStatic = true;
1402 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1403 Func != Path->Decls.second; ++Func) {
1404 if (!isa<CXXMethodDecl>(*Func)) {
1405 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1406 break;
1407 }
1408
1409 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1410 AllMethodsAreStatic = false;
1411 break;
1412 }
1413 }
1414
1415 if (AllMethodsAreStatic)
1416 continue;
1417 }
1418
1419 // We have found a nonstatic member name in multiple, distinct
1420 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001421 R.setAmbiguousBaseSubobjects(Paths);
1422 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001423 }
1424 }
1425
1426 // Lookup in a base class succeeded; return these results.
1427
John McCallf36e02d2009-10-09 21:13:30 +00001428 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001429 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1430 NamedDecl *D = *I;
1431 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1432 D->getAccess());
1433 R.addDecl(D, AS);
1434 }
John McCallf36e02d2009-10-09 21:13:30 +00001435 R.resolveKind();
1436 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001437}
1438
1439/// @brief Performs name lookup for a name that was parsed in the
1440/// source code, and may contain a C++ scope specifier.
1441///
1442/// This routine is a convenience routine meant to be called from
1443/// contexts that receive a name and an optional C++ scope specifier
1444/// (e.g., "N::M::x"). It will then perform either qualified or
1445/// unqualified name lookup (with LookupQualifiedName or LookupName,
1446/// respectively) on the given name and return those results.
1447///
1448/// @param S The scope from which unqualified name lookup will
1449/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001450///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001451/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001452///
1453/// @param Name The name of the entity that name lookup will
1454/// search for.
1455///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001456/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001457/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001458/// C library functions (like "malloc") are implicitly declared.
1459///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001460/// @param EnteringContext Indicates whether we are going to enter the
1461/// context of the scope-specifier SS (if present).
1462///
John McCallf36e02d2009-10-09 21:13:30 +00001463/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001464bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001465 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001466 if (SS && SS->isInvalid()) {
1467 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001468 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001469 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001470 }
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Douglas Gregor495c35d2009-08-25 22:51:20 +00001472 if (SS && SS->isSet()) {
1473 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001474 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001475 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001476 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001477 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001478
John McCalla24dc2e2009-11-17 02:14:36 +00001479 R.setContextRange(SS->getRange());
1480
1481 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001482 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001483
Douglas Gregor495c35d2009-08-25 22:51:20 +00001484 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001485 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001486 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001487 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001488 }
1489
Mike Stump1eb44332009-09-09 15:08:12 +00001490 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001491 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001492}
1493
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001494
Douglas Gregor7176fff2009-01-15 00:26:24 +00001495/// @brief Produce a diagnostic describing the ambiguity that resulted
1496/// from name lookup.
1497///
1498/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001499///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001500/// @param Name The name of the entity that name lookup was
1501/// searching for.
1502///
1503/// @param NameLoc The location of the name within the source code.
1504///
1505/// @param LookupRange A source range that provides more
1506/// source-location information concerning the lookup itself. For
1507/// example, this range might highlight a nested-name-specifier that
1508/// precedes the name.
1509///
1510/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001511bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001512 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1513
John McCalla24dc2e2009-11-17 02:14:36 +00001514 DeclarationName Name = Result.getLookupName();
1515 SourceLocation NameLoc = Result.getNameLoc();
1516 SourceRange LookupRange = Result.getContextRange();
1517
John McCall6e247262009-10-10 05:48:19 +00001518 switch (Result.getAmbiguityKind()) {
1519 case LookupResult::AmbiguousBaseSubobjects: {
1520 CXXBasePaths *Paths = Result.getBasePaths();
1521 QualType SubobjectType = Paths->front().back().Base->getType();
1522 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1523 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1524 << LookupRange;
1525
1526 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1527 while (isa<CXXMethodDecl>(*Found) &&
1528 cast<CXXMethodDecl>(*Found)->isStatic())
1529 ++Found;
1530
1531 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1532
1533 return true;
1534 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001535
John McCall6e247262009-10-10 05:48:19 +00001536 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001537 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1538 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001539
1540 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001541 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001542 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1543 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001544 Path != PathEnd; ++Path) {
1545 Decl *D = *Path->Decls.first;
1546 if (DeclsPrinted.insert(D).second)
1547 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1548 }
1549
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001550 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001551 }
1552
John McCall6e247262009-10-10 05:48:19 +00001553 case LookupResult::AmbiguousTagHiding: {
1554 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001555
John McCall6e247262009-10-10 05:48:19 +00001556 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1557
1558 LookupResult::iterator DI, DE = Result.end();
1559 for (DI = Result.begin(); DI != DE; ++DI)
1560 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1561 TagDecls.insert(TD);
1562 Diag(TD->getLocation(), diag::note_hidden_tag);
1563 }
1564
1565 for (DI = Result.begin(); DI != DE; ++DI)
1566 if (!isa<TagDecl>(*DI))
1567 Diag((*DI)->getLocation(), diag::note_hiding_object);
1568
1569 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001570 LookupResult::Filter F = Result.makeFilter();
1571 while (F.hasNext()) {
1572 if (TagDecls.count(F.next()))
1573 F.erase();
1574 }
1575 F.done();
John McCall6e247262009-10-10 05:48:19 +00001576
1577 return true;
1578 }
1579
1580 case LookupResult::AmbiguousReference: {
1581 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001582
John McCall6e247262009-10-10 05:48:19 +00001583 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1584 for (; DI != DE; ++DI)
1585 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001586
John McCall6e247262009-10-10 05:48:19 +00001587 return true;
1588 }
1589 }
1590
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001591 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001592 return true;
1593}
Douglas Gregorfa047642009-02-04 00:32:51 +00001594
John McCallc7e04da2010-05-28 18:45:08 +00001595namespace {
1596 struct AssociatedLookup {
1597 AssociatedLookup(Sema &S,
1598 Sema::AssociatedNamespaceSet &Namespaces,
1599 Sema::AssociatedClassSet &Classes)
1600 : S(S), Namespaces(Namespaces), Classes(Classes) {
1601 }
1602
1603 Sema &S;
1604 Sema::AssociatedNamespaceSet &Namespaces;
1605 Sema::AssociatedClassSet &Classes;
1606 };
1607}
1608
Mike Stump1eb44332009-09-09 15:08:12 +00001609static void
John McCallc7e04da2010-05-28 18:45:08 +00001610addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001611
Douglas Gregor54022952010-04-30 07:08:38 +00001612static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1613 DeclContext *Ctx) {
1614 // Add the associated namespace for this class.
1615
1616 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1617 // be a locally scoped record.
1618
1619 while (Ctx->isRecord() || Ctx->isTransparentContext())
1620 Ctx = Ctx->getParent();
1621
John McCall6ff07852009-08-07 22:18:02 +00001622 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001623 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001624}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001625
Mike Stump1eb44332009-09-09 15:08:12 +00001626// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001627// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001628static void
John McCallc7e04da2010-05-28 18:45:08 +00001629addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1630 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001631 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001632 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001633 switch (Arg.getKind()) {
1634 case TemplateArgument::Null:
1635 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Douglas Gregor69be8d62009-07-08 07:51:57 +00001637 case TemplateArgument::Type:
1638 // [...] the namespaces and classes associated with the types of the
1639 // template arguments provided for template type parameters (excluding
1640 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001641 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001642 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Douglas Gregor788cd062009-11-11 01:00:40 +00001644 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001645 // [...] the namespaces in which any template template arguments are
1646 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001647 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001648 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001649 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001650 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001651 DeclContext *Ctx = ClassTemplate->getDeclContext();
1652 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001653 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001654 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001655 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001656 }
1657 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001658 }
1659
1660 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001661 case TemplateArgument::Integral:
1662 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001663 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001664 // associated namespaces. ]
1665 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Douglas Gregor69be8d62009-07-08 07:51:57 +00001667 case TemplateArgument::Pack:
1668 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1669 PEnd = Arg.pack_end();
1670 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001671 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001672 break;
1673 }
1674}
1675
Douglas Gregorfa047642009-02-04 00:32:51 +00001676// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001677// argument-dependent lookup with an argument of class type
1678// (C++ [basic.lookup.koenig]p2).
1679static void
John McCallc7e04da2010-05-28 18:45:08 +00001680addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1681 CXXRecordDecl *Class) {
1682
1683 // Just silently ignore anything whose name is __va_list_tag.
1684 if (Class->getDeclName() == Result.S.VAListTagName)
1685 return;
1686
Douglas Gregorfa047642009-02-04 00:32:51 +00001687 // C++ [basic.lookup.koenig]p2:
1688 // [...]
1689 // -- If T is a class type (including unions), its associated
1690 // classes are: the class itself; the class of which it is a
1691 // member, if any; and its direct and indirect base
1692 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001693 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001694
1695 // Add the class of which it is a member, if any.
1696 DeclContext *Ctx = Class->getDeclContext();
1697 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001698 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001699 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001700 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Douglas Gregorfa047642009-02-04 00:32:51 +00001702 // Add the class itself. If we've already seen this class, we don't
1703 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001704 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001705 return;
1706
Mike Stump1eb44332009-09-09 15:08:12 +00001707 // -- If T is a template-id, its associated namespaces and classes are
1708 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001709 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001710 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001711 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001712 // namespaces in which any template template arguments are defined; and
1713 // the classes in which any member templates used as template template
1714 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001715 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001716 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001717 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1718 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1719 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001720 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001721 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001722 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Douglas Gregor69be8d62009-07-08 07:51:57 +00001724 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1725 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001726 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001727 }
Mike Stump1eb44332009-09-09 15:08:12 +00001728
John McCall86ff3082010-02-04 22:26:26 +00001729 // Only recurse into base classes for complete types.
1730 if (!Class->hasDefinition()) {
1731 // FIXME: we might need to instantiate templates here
1732 return;
1733 }
1734
Douglas Gregorfa047642009-02-04 00:32:51 +00001735 // Add direct and indirect base classes along with their associated
1736 // namespaces.
1737 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1738 Bases.push_back(Class);
1739 while (!Bases.empty()) {
1740 // Pop this class off the stack.
1741 Class = Bases.back();
1742 Bases.pop_back();
1743
1744 // Visit the base classes.
1745 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1746 BaseEnd = Class->bases_end();
1747 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001748 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001749 // In dependent contexts, we do ADL twice, and the first time around,
1750 // the base type might be a dependent TemplateSpecializationType, or a
1751 // TemplateTypeParmType. If that happens, simply ignore it.
1752 // FIXME: If we want to support export, we probably need to add the
1753 // namespace of the template in a TemplateSpecializationType, or even
1754 // the classes and namespaces of known non-dependent arguments.
1755 if (!BaseType)
1756 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001757 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001758 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001759 // Find the associated namespace for this base class.
1760 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001761 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001762
1763 // Make sure we visit the bases of this base class.
1764 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1765 Bases.push_back(BaseDecl);
1766 }
1767 }
1768 }
1769}
1770
1771// \brief Add the associated classes and namespaces for
1772// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001773// (C++ [basic.lookup.koenig]p2).
1774static void
John McCallc7e04da2010-05-28 18:45:08 +00001775addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001776 // C++ [basic.lookup.koenig]p2:
1777 //
1778 // For each argument type T in the function call, there is a set
1779 // of zero or more associated namespaces and a set of zero or more
1780 // associated classes to be considered. The sets of namespaces and
1781 // classes is determined entirely by the types of the function
1782 // arguments (and the namespace of any template template
1783 // argument). Typedef names and using-declarations used to specify
1784 // the types do not contribute to this set. The sets of namespaces
1785 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001786
John McCallfa4edcf2010-05-28 06:08:54 +00001787 llvm::SmallVector<const Type *, 16> Queue;
1788 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1789
Douglas Gregorfa047642009-02-04 00:32:51 +00001790 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001791 switch (T->getTypeClass()) {
1792
1793#define TYPE(Class, Base)
1794#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1795#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1796#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1797#define ABSTRACT_TYPE(Class, Base)
1798#include "clang/AST/TypeNodes.def"
1799 // T is canonical. We can also ignore dependent types because
1800 // we don't need to do ADL at the definition point, but if we
1801 // wanted to implement template export (or if we find some other
1802 // use for associated classes and namespaces...) this would be
1803 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001804 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001805
John McCallfa4edcf2010-05-28 06:08:54 +00001806 // -- If T is a pointer to U or an array of U, its associated
1807 // namespaces and classes are those associated with U.
1808 case Type::Pointer:
1809 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1810 continue;
1811 case Type::ConstantArray:
1812 case Type::IncompleteArray:
1813 case Type::VariableArray:
1814 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1815 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001816
John McCallfa4edcf2010-05-28 06:08:54 +00001817 // -- If T is a fundamental type, its associated sets of
1818 // namespaces and classes are both empty.
1819 case Type::Builtin:
1820 break;
1821
1822 // -- If T is a class type (including unions), its associated
1823 // classes are: the class itself; the class of which it is a
1824 // member, if any; and its direct and indirect base
1825 // classes. Its associated namespaces are the namespaces in
1826 // which its associated classes are defined.
1827 case Type::Record: {
1828 CXXRecordDecl *Class
1829 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001830 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001831 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001832 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001833
John McCallfa4edcf2010-05-28 06:08:54 +00001834 // -- If T is an enumeration type, its associated namespace is
1835 // the namespace in which it is defined. If it is class
1836 // member, its associated class is the member’s class; else
1837 // it has no associated class.
1838 case Type::Enum: {
1839 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001840
John McCallfa4edcf2010-05-28 06:08:54 +00001841 DeclContext *Ctx = Enum->getDeclContext();
1842 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001843 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001844
John McCallfa4edcf2010-05-28 06:08:54 +00001845 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001846 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001847
John McCallfa4edcf2010-05-28 06:08:54 +00001848 break;
1849 }
1850
1851 // -- If T is a function type, its associated namespaces and
1852 // classes are those associated with the function parameter
1853 // types and those associated with the return type.
1854 case Type::FunctionProto: {
1855 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1856 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1857 ArgEnd = Proto->arg_type_end();
1858 Arg != ArgEnd; ++Arg)
1859 Queue.push_back(Arg->getTypePtr());
1860 // fallthrough
1861 }
1862 case Type::FunctionNoProto: {
1863 const FunctionType *FnType = cast<FunctionType>(T);
1864 T = FnType->getResultType().getTypePtr();
1865 continue;
1866 }
1867
1868 // -- If T is a pointer to a member function of a class X, its
1869 // associated namespaces and classes are those associated
1870 // with the function parameter types and return type,
1871 // together with those associated with X.
1872 //
1873 // -- If T is a pointer to a data member of class X, its
1874 // associated namespaces and classes are those associated
1875 // with the member type together with those associated with
1876 // X.
1877 case Type::MemberPointer: {
1878 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1879
1880 // Queue up the class type into which this points.
1881 Queue.push_back(MemberPtr->getClass());
1882
1883 // And directly continue with the pointee type.
1884 T = MemberPtr->getPointeeType().getTypePtr();
1885 continue;
1886 }
1887
1888 // As an extension, treat this like a normal pointer.
1889 case Type::BlockPointer:
1890 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1891 continue;
1892
1893 // References aren't covered by the standard, but that's such an
1894 // obvious defect that we cover them anyway.
1895 case Type::LValueReference:
1896 case Type::RValueReference:
1897 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1898 continue;
1899
1900 // These are fundamental types.
1901 case Type::Vector:
1902 case Type::ExtVector:
1903 case Type::Complex:
1904 break;
1905
1906 // These are ignored by ADL.
1907 case Type::ObjCObject:
1908 case Type::ObjCInterface:
1909 case Type::ObjCObjectPointer:
1910 break;
1911 }
1912
1913 if (Queue.empty()) break;
1914 T = Queue.back();
1915 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001916 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001917}
1918
1919/// \brief Find the associated classes and namespaces for
1920/// argument-dependent lookup for a call with the given set of
1921/// arguments.
1922///
1923/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001924/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001925/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001926void
Douglas Gregorfa047642009-02-04 00:32:51 +00001927Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1928 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001929 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001930 AssociatedNamespaces.clear();
1931 AssociatedClasses.clear();
1932
John McCallc7e04da2010-05-28 18:45:08 +00001933 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1934
Douglas Gregorfa047642009-02-04 00:32:51 +00001935 // C++ [basic.lookup.koenig]p2:
1936 // For each argument type T in the function call, there is a set
1937 // of zero or more associated namespaces and a set of zero or more
1938 // associated classes to be considered. The sets of namespaces and
1939 // classes is determined entirely by the types of the function
1940 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001941 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001942 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1943 Expr *Arg = Args[ArgIdx];
1944
1945 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00001946 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001947 continue;
1948 }
1949
1950 // [...] In addition, if the argument is the name or address of a
1951 // set of overloaded functions and/or function templates, its
1952 // associated classes and namespaces are the union of those
1953 // associated with each of the members of the set: the namespace
1954 // in which the function or function template is defined and the
1955 // classes and namespaces associated with its (non-dependent)
1956 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001957 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001958 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1959 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1960 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001961
John McCallc7e04da2010-05-28 18:45:08 +00001962 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
1963 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00001964
John McCallc7e04da2010-05-28 18:45:08 +00001965 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
1966 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00001967 // Look through any using declarations to find the underlying function.
1968 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001969
Chandler Carruthbd647292009-12-29 06:17:27 +00001970 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
1971 if (!FDecl)
1972 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001973
1974 // Add the classes and namespaces associated with the parameter
1975 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00001976 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001977 }
1978 }
1979}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001980
1981/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1982/// an acceptable non-member overloaded operator for a call whose
1983/// arguments have types T1 (and, if non-empty, T2). This routine
1984/// implements the check in C++ [over.match.oper]p3b2 concerning
1985/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001986static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001987IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1988 QualType T1, QualType T2,
1989 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001990 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1991 return true;
1992
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001993 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1994 return true;
1995
John McCall183700f2009-09-21 23:43:11 +00001996 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001997 if (Proto->getNumArgs() < 1)
1998 return false;
1999
2000 if (T1->isEnumeralType()) {
2001 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002002 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002003 return true;
2004 }
2005
2006 if (Proto->getNumArgs() < 2)
2007 return false;
2008
2009 if (!T2.isNull() && T2->isEnumeralType()) {
2010 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002011 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002012 return true;
2013 }
2014
2015 return false;
2016}
2017
John McCall7d384dd2009-11-18 07:57:50 +00002018NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002019 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002020 LookupNameKind NameKind,
2021 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002022 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002023 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002024 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002025}
2026
Douglas Gregor6e378de2009-04-23 23:18:26 +00002027/// \brief Find the protocol with the given name, if any.
Douglas Gregorc83c6872010-04-15 22:33:43 +00002028ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2029 SourceLocation IdLoc) {
2030 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2031 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002032 return cast_or_null<ObjCProtocolDecl>(D);
2033}
2034
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002035void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002036 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002037 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002038 // C++ [over.match.oper]p3:
2039 // -- The set of non-member candidates is the result of the
2040 // unqualified lookup of operator@ in the context of the
2041 // expression according to the usual rules for name lookup in
2042 // unqualified function calls (3.4.2) except that all member
2043 // functions are ignored. However, if no operand has a class
2044 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002045 // that have a first parameter of type T1 or "reference to
2046 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002047 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002048 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002049 // when T2 is an enumeration type, are candidate functions.
2050 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002051 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2052 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002054 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2055
John McCallf36e02d2009-10-09 21:13:30 +00002056 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002057 return;
2058
2059 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2060 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002061 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2062 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002063 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002064 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002065 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002066 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002067 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002068 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002069 // later?
2070 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002071 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002072 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002073 }
2074}
2075
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002076/// \brief Look up the constructors for the given class.
2077DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +00002078 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002079 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2080 if (!Class->hasDeclaredDefaultConstructor())
2081 DeclareImplicitDefaultConstructor(Class);
2082 if (!Class->hasDeclaredCopyConstructor())
2083 DeclareImplicitCopyConstructor(Class);
2084 }
Douglas Gregor22584312010-07-02 23:41:54 +00002085
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002086 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2087 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2088 return Class->lookup(Name);
2089}
2090
Douglas Gregordb89f282010-07-01 22:47:18 +00002091/// \brief Look for the destructor of the given class.
2092///
2093/// During semantic analysis, this routine should be used in lieu of
2094/// CXXRecordDecl::getDestructor().
2095///
2096/// \returns The destructor for this class.
2097CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +00002098 // If the destructor has not yet been declared, do so now.
2099 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2100 !Class->hasDeclaredDestructor())
2101 DeclareImplicitDestructor(Class);
2102
Douglas Gregordb89f282010-07-01 22:47:18 +00002103 return Class->getDestructor();
2104}
2105
John McCall7edb5fd2010-01-26 07:16:45 +00002106void ADLResult::insert(NamedDecl *New) {
2107 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2108
2109 // If we haven't yet seen a decl for this key, or the last decl
2110 // was exactly this one, we're done.
2111 if (Old == 0 || Old == New) {
2112 Old = New;
2113 return;
2114 }
2115
2116 // Otherwise, decide which is a more recent redeclaration.
2117 FunctionDecl *OldFD, *NewFD;
2118 if (isa<FunctionTemplateDecl>(New)) {
2119 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2120 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2121 } else {
2122 OldFD = cast<FunctionDecl>(Old);
2123 NewFD = cast<FunctionDecl>(New);
2124 }
2125
2126 FunctionDecl *Cursor = NewFD;
2127 while (true) {
2128 Cursor = Cursor->getPreviousDeclaration();
2129
2130 // If we got to the end without finding OldFD, OldFD is the newer
2131 // declaration; leave things as they are.
2132 if (!Cursor) return;
2133
2134 // If we do find OldFD, then NewFD is newer.
2135 if (Cursor == OldFD) break;
2136
2137 // Otherwise, keep looking.
2138 }
2139
2140 Old = New;
2141}
2142
Sebastian Redl644be852009-10-23 19:23:15 +00002143void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002144 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00002145 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002146 // Find all of the associated namespaces and classes based on the
2147 // arguments we have.
2148 AssociatedNamespaceSet AssociatedNamespaces;
2149 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002150 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002151 AssociatedNamespaces,
2152 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002153
Sebastian Redl644be852009-10-23 19:23:15 +00002154 QualType T1, T2;
2155 if (Operator) {
2156 T1 = Args[0]->getType();
2157 if (NumArgs >= 2)
2158 T2 = Args[1]->getType();
2159 }
2160
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002161 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002162 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2163 // and let Y be the lookup set produced by argument dependent
2164 // lookup (defined as follows). If X contains [...] then Y is
2165 // empty. Otherwise Y is the set of declarations found in the
2166 // namespaces associated with the argument types as described
2167 // below. The set of declarations found by the lookup of the name
2168 // is the union of X and Y.
2169 //
2170 // Here, we compute Y and add its members to the overloaded
2171 // candidate set.
2172 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002173 NSEnd = AssociatedNamespaces.end();
2174 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002175 // When considering an associated namespace, the lookup is the
2176 // same as the lookup performed when the associated namespace is
2177 // used as a qualifier (3.4.3.2) except that:
2178 //
2179 // -- Any using-directives in the associated namespace are
2180 // ignored.
2181 //
John McCall6ff07852009-08-07 22:18:02 +00002182 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002183 // associated classes are visible within their respective
2184 // namespaces even if they are not visible during an ordinary
2185 // lookup (11.4).
2186 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002187 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002188 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002189 // If the only declaration here is an ordinary friend, consider
2190 // it only if it was declared in an associated classes.
2191 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002192 DeclContext *LexDC = D->getLexicalDeclContext();
2193 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2194 continue;
2195 }
Mike Stump1eb44332009-09-09 15:08:12 +00002196
John McCalla113e722010-01-26 06:04:06 +00002197 if (isa<UsingShadowDecl>(D))
2198 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002199
John McCalla113e722010-01-26 06:04:06 +00002200 if (isa<FunctionDecl>(D)) {
2201 if (Operator &&
2202 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2203 T1, T2, Context))
2204 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002205 } else if (!isa<FunctionTemplateDecl>(D))
2206 continue;
2207
2208 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002209 }
2210 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002211}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002212
2213//----------------------------------------------------------------------------
2214// Search for all visible declarations.
2215//----------------------------------------------------------------------------
2216VisibleDeclConsumer::~VisibleDeclConsumer() { }
2217
2218namespace {
2219
2220class ShadowContextRAII;
2221
2222class VisibleDeclsRecord {
2223public:
2224 /// \brief An entry in the shadow map, which is optimized to store a
2225 /// single declaration (the common case) but can also store a list
2226 /// of declarations.
2227 class ShadowMapEntry {
2228 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2229
2230 /// \brief Contains either the solitary NamedDecl * or a vector
2231 /// of declarations.
2232 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2233
2234 public:
2235 ShadowMapEntry() : DeclOrVector() { }
2236
2237 void Add(NamedDecl *ND);
2238 void Destroy();
2239
2240 // Iteration.
2241 typedef NamedDecl **iterator;
2242 iterator begin();
2243 iterator end();
2244 };
2245
2246private:
2247 /// \brief A mapping from declaration names to the declarations that have
2248 /// this name within a particular scope.
2249 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2250
2251 /// \brief A list of shadow maps, which is used to model name hiding.
2252 std::list<ShadowMap> ShadowMaps;
2253
2254 /// \brief The declaration contexts we have already visited.
2255 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2256
2257 friend class ShadowContextRAII;
2258
2259public:
2260 /// \brief Determine whether we have already visited this context
2261 /// (and, if not, note that we are going to visit that context now).
2262 bool visitedContext(DeclContext *Ctx) {
2263 return !VisitedContexts.insert(Ctx);
2264 }
2265
Douglas Gregor8071e422010-08-15 06:18:01 +00002266 bool alreadyVisitedContext(DeclContext *Ctx) {
2267 return VisitedContexts.count(Ctx);
2268 }
2269
Douglas Gregor546be3c2009-12-30 17:04:44 +00002270 /// \brief Determine whether the given declaration is hidden in the
2271 /// current scope.
2272 ///
2273 /// \returns the declaration that hides the given declaration, or
2274 /// NULL if no such declaration exists.
2275 NamedDecl *checkHidden(NamedDecl *ND);
2276
2277 /// \brief Add a declaration to the current shadow map.
2278 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2279};
2280
2281/// \brief RAII object that records when we've entered a shadow context.
2282class ShadowContextRAII {
2283 VisibleDeclsRecord &Visible;
2284
2285 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2286
2287public:
2288 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2289 Visible.ShadowMaps.push_back(ShadowMap());
2290 }
2291
2292 ~ShadowContextRAII() {
2293 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2294 EEnd = Visible.ShadowMaps.back().end();
2295 E != EEnd;
2296 ++E)
2297 E->second.Destroy();
2298
2299 Visible.ShadowMaps.pop_back();
2300 }
2301};
2302
2303} // end anonymous namespace
2304
2305void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2306 if (DeclOrVector.isNull()) {
2307 // 0 - > 1 elements: just set the single element information.
2308 DeclOrVector = ND;
2309 return;
2310 }
2311
2312 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2313 // 1 -> 2 elements: create the vector of results and push in the
2314 // existing declaration.
2315 DeclVector *Vec = new DeclVector;
2316 Vec->push_back(PrevND);
2317 DeclOrVector = Vec;
2318 }
2319
2320 // Add the new element to the end of the vector.
2321 DeclOrVector.get<DeclVector*>()->push_back(ND);
2322}
2323
2324void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2325 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2326 delete Vec;
2327 DeclOrVector = ((NamedDecl *)0);
2328 }
2329}
2330
2331VisibleDeclsRecord::ShadowMapEntry::iterator
2332VisibleDeclsRecord::ShadowMapEntry::begin() {
2333 if (DeclOrVector.isNull())
2334 return 0;
2335
2336 if (DeclOrVector.dyn_cast<NamedDecl *>())
2337 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2338
2339 return DeclOrVector.get<DeclVector *>()->begin();
2340}
2341
2342VisibleDeclsRecord::ShadowMapEntry::iterator
2343VisibleDeclsRecord::ShadowMapEntry::end() {
2344 if (DeclOrVector.isNull())
2345 return 0;
2346
2347 if (DeclOrVector.dyn_cast<NamedDecl *>())
2348 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2349
2350 return DeclOrVector.get<DeclVector *>()->end();
2351}
2352
2353NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002354 // Look through using declarations.
2355 ND = ND->getUnderlyingDecl();
2356
Douglas Gregor546be3c2009-12-30 17:04:44 +00002357 unsigned IDNS = ND->getIdentifierNamespace();
2358 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2359 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2360 SM != SMEnd; ++SM) {
2361 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2362 if (Pos == SM->end())
2363 continue;
2364
2365 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2366 IEnd = Pos->second.end();
2367 I != IEnd; ++I) {
2368 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002369 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor546be3c2009-12-30 17:04:44 +00002370 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2371 Decl::IDNS_ObjCProtocol)))
2372 continue;
2373
2374 // Protocols are in distinct namespaces from everything else.
2375 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2376 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2377 (*I)->getIdentifierNamespace() != IDNS)
2378 continue;
2379
Douglas Gregor0cc84042010-01-14 15:47:35 +00002380 // Functions and function templates in the same scope overload
2381 // rather than hide. FIXME: Look for hiding based on function
2382 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002383 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002384 ND->isFunctionOrFunctionTemplate() &&
2385 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002386 continue;
2387
Douglas Gregor546be3c2009-12-30 17:04:44 +00002388 // We've found a declaration that hides this one.
2389 return *I;
2390 }
2391 }
2392
2393 return 0;
2394}
2395
2396static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2397 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002398 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002399 VisibleDeclConsumer &Consumer,
2400 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002401 if (!Ctx)
2402 return;
2403
Douglas Gregor546be3c2009-12-30 17:04:44 +00002404 // Make sure we don't visit the same context twice.
2405 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2406 return;
2407
Douglas Gregor4923aa22010-07-02 20:37:36 +00002408 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2409 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2410
Douglas Gregor546be3c2009-12-30 17:04:44 +00002411 // Enumerate all of the results in this context.
2412 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2413 CurCtx = CurCtx->getNextContext()) {
2414 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2415 DEnd = CurCtx->decls_end();
2416 D != DEnd; ++D) {
2417 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2418 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002419 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002420 Visited.add(ND);
2421 }
2422
2423 // Visit transparent contexts inside this context.
2424 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2425 if (InnerCtx->isTransparentContext())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002426 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002427 Consumer, Visited);
2428 }
2429 }
2430 }
2431
2432 // Traverse using directives for qualified name lookup.
2433 if (QualifiedNameLookup) {
2434 ShadowContextRAII Shadow(Visited);
2435 DeclContext::udir_iterator I, E;
2436 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2437 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002438 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002439 }
2440 }
2441
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002442 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002443 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002444 if (!Record->hasDefinition())
2445 return;
2446
Douglas Gregor546be3c2009-12-30 17:04:44 +00002447 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2448 BEnd = Record->bases_end();
2449 B != BEnd; ++B) {
2450 QualType BaseType = B->getType();
2451
2452 // Don't look into dependent bases, because name lookup can't look
2453 // there anyway.
2454 if (BaseType->isDependentType())
2455 continue;
2456
2457 const RecordType *Record = BaseType->getAs<RecordType>();
2458 if (!Record)
2459 continue;
2460
2461 // FIXME: It would be nice to be able to determine whether referencing
2462 // a particular member would be ambiguous. For example, given
2463 //
2464 // struct A { int member; };
2465 // struct B { int member; };
2466 // struct C : A, B { };
2467 //
2468 // void f(C *c) { c->### }
2469 //
2470 // accessing 'member' would result in an ambiguity. However, we
2471 // could be smart enough to qualify the member with the base
2472 // class, e.g.,
2473 //
2474 // c->B::member
2475 //
2476 // or
2477 //
2478 // c->A::member
2479
2480 // Find results in this base class (and its bases).
2481 ShadowContextRAII Shadow(Visited);
2482 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002483 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002484 }
2485 }
2486
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002487 // Traverse the contexts of Objective-C classes.
2488 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2489 // Traverse categories.
2490 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2491 Category; Category = Category->getNextClassCategory()) {
2492 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002493 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2494 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002495 }
2496
2497 // Traverse protocols.
2498 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2499 E = IFace->protocol_end(); I != E; ++I) {
2500 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002501 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2502 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002503 }
2504
2505 // Traverse the superclass.
2506 if (IFace->getSuperClass()) {
2507 ShadowContextRAII Shadow(Visited);
2508 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002509 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002510 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002511
2512 // If there is an implementation, traverse it. We do this to find
2513 // synthesized ivars.
2514 if (IFace->getImplementation()) {
2515 ShadowContextRAII Shadow(Visited);
2516 LookupVisibleDecls(IFace->getImplementation(), Result,
2517 QualifiedNameLookup, true, Consumer, Visited);
2518 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002519 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2520 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2521 E = Protocol->protocol_end(); I != E; ++I) {
2522 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002523 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2524 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002525 }
2526 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2527 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2528 E = Category->protocol_end(); I != E; ++I) {
2529 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002530 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2531 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002532 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002533
2534 // If there is an implementation, traverse it.
2535 if (Category->getImplementation()) {
2536 ShadowContextRAII Shadow(Visited);
2537 LookupVisibleDecls(Category->getImplementation(), Result,
2538 QualifiedNameLookup, true, Consumer, Visited);
2539 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002540 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002541}
2542
2543static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2544 UnqualUsingDirectiveSet &UDirs,
2545 VisibleDeclConsumer &Consumer,
2546 VisibleDeclsRecord &Visited) {
2547 if (!S)
2548 return;
2549
Douglas Gregor8071e422010-08-15 06:18:01 +00002550 if (!S->getEntity() ||
2551 (!S->getParent() &&
2552 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002553 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2554 // Walk through the declarations in this Scope.
2555 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2556 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002557 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor539c5c32010-01-07 00:31:29 +00002558 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002559 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002560 Visited.add(ND);
2561 }
2562 }
2563 }
2564
Douglas Gregor711be1e2010-03-15 14:33:29 +00002565 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002566 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002567 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002568 // Look into this scope's declaration context, along with any of its
2569 // parent lookup contexts (e.g., enclosing classes), up to the point
2570 // where we hit the context stored in the next outer scope.
2571 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002572 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor546be3c2009-12-30 17:04:44 +00002573
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002574 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002575 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002576 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2577 if (Method->isInstanceMethod()) {
2578 // For instance methods, look for ivars in the method's interface.
2579 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2580 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregor62021192010-02-04 23:42:48 +00002581 if (ObjCInterfaceDecl *IFace = Method->getClassInterface())
2582 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2583 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002584 }
2585
2586 // We've already performed all of the name lookup that we need
2587 // to for Objective-C methods; the next context will be the
2588 // outer scope.
2589 break;
2590 }
2591
Douglas Gregor546be3c2009-12-30 17:04:44 +00002592 if (Ctx->isFunctionOrMethod())
2593 continue;
2594
2595 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002596 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002597 }
2598 } else if (!S->getParent()) {
2599 // Look into the translation unit scope. We walk through the translation
2600 // unit's declaration context, because the Scope itself won't have all of
2601 // the declarations if we loaded a precompiled header.
2602 // FIXME: We would like the translation unit's Scope object to point to the
2603 // translation unit, so we don't need this special "if" branch. However,
2604 // doing so would force the normal C++ name-lookup code to look into the
2605 // translation unit decl when the IdentifierInfo chains would suffice.
2606 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002607 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002608 Entity = Result.getSema().Context.getTranslationUnitDecl();
2609 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002610 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002611 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002612
2613 if (Entity) {
2614 // Lookup visible declarations in any namespaces found by using
2615 // directives.
2616 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2617 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2618 for (; UI != UEnd; ++UI)
2619 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002620 Result, /*QualifiedNameLookup=*/false,
2621 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002622 }
2623
2624 // Lookup names in the parent scope.
2625 ShadowContextRAII Shadow(Visited);
2626 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2627}
2628
2629void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002630 VisibleDeclConsumer &Consumer,
2631 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002632 // Determine the set of using directives available during
2633 // unqualified name lookup.
2634 Scope *Initial = S;
2635 UnqualUsingDirectiveSet UDirs;
2636 if (getLangOptions().CPlusPlus) {
2637 // Find the first namespace or translation-unit scope.
2638 while (S && !isNamespaceOrTranslationUnitScope(S))
2639 S = S->getParent();
2640
2641 UDirs.visitScopeChain(Initial, S);
2642 }
2643 UDirs.done();
2644
2645 // Look for visible declarations.
2646 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2647 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002648 if (!IncludeGlobalScope)
2649 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002650 ShadowContextRAII Shadow(Visited);
2651 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2652}
2653
2654void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002655 VisibleDeclConsumer &Consumer,
2656 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002657 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2658 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002659 if (!IncludeGlobalScope)
2660 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002661 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002662 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2663 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002664}
2665
2666//----------------------------------------------------------------------------
2667// Typo correction
2668//----------------------------------------------------------------------------
2669
2670namespace {
2671class TypoCorrectionConsumer : public VisibleDeclConsumer {
2672 /// \brief The name written that is a typo in the source.
2673 llvm::StringRef Typo;
2674
2675 /// \brief The results found that have the smallest edit distance
2676 /// found (so far) with the typo name.
2677 llvm::SmallVector<NamedDecl *, 4> BestResults;
2678
Douglas Gregoraaf87162010-04-14 20:04:41 +00002679 /// \brief The keywords that have the smallest edit distance.
2680 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords;
2681
Douglas Gregor546be3c2009-12-30 17:04:44 +00002682 /// \brief The best edit distance found so far.
2683 unsigned BestEditDistance;
2684
2685public:
2686 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2687 : Typo(Typo->getName()) { }
2688
Douglas Gregor0cc84042010-01-14 15:47:35 +00002689 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002690 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002691
2692 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator;
2693 iterator begin() const { return BestResults.begin(); }
2694 iterator end() const { return BestResults.end(); }
Douglas Gregoraaf87162010-04-14 20:04:41 +00002695 void clear_decls() { BestResults.clear(); }
2696
2697 bool empty() const { return BestResults.empty() && BestKeywords.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002698
Douglas Gregoraaf87162010-04-14 20:04:41 +00002699 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator
2700 keyword_iterator;
2701 keyword_iterator keyword_begin() const { return BestKeywords.begin(); }
2702 keyword_iterator keyword_end() const { return BestKeywords.end(); }
2703 bool keyword_empty() const { return BestKeywords.empty(); }
2704 unsigned keyword_size() const { return BestKeywords.size(); }
2705
2706 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002707};
2708
2709}
2710
Douglas Gregor0cc84042010-01-14 15:47:35 +00002711void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2712 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002713 // Don't consider hidden names for typo correction.
2714 if (Hiding)
2715 return;
2716
2717 // Only consider entities with identifiers for names, ignoring
2718 // special names (constructors, overloaded operators, selectors,
2719 // etc.).
2720 IdentifierInfo *Name = ND->getIdentifier();
2721 if (!Name)
2722 return;
2723
2724 // Compute the edit distance between the typo and the name of this
2725 // entity. If this edit distance is not worse than the best edit
2726 // distance we've seen so far, add it to the list of results.
2727 unsigned ED = Typo.edit_distance(Name->getName());
Douglas Gregoraaf87162010-04-14 20:04:41 +00002728 if (!BestResults.empty() || !BestKeywords.empty()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002729 if (ED < BestEditDistance) {
2730 // This result is better than any we've seen before; clear out
2731 // the previous results.
2732 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002733 BestKeywords.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002734 BestEditDistance = ED;
2735 } else if (ED > BestEditDistance) {
2736 // This result is worse than the best results we've seen so far;
2737 // ignore it.
2738 return;
2739 }
2740 } else
2741 BestEditDistance = ED;
2742
2743 BestResults.push_back(ND);
2744}
2745
Douglas Gregoraaf87162010-04-14 20:04:41 +00002746void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2747 llvm::StringRef Keyword) {
2748 // Compute the edit distance between the typo and this keyword.
2749 // If this edit distance is not worse than the best edit
2750 // distance we've seen so far, add it to the list of results.
2751 unsigned ED = Typo.edit_distance(Keyword);
2752 if (!BestResults.empty() || !BestKeywords.empty()) {
2753 if (ED < BestEditDistance) {
2754 BestResults.clear();
2755 BestKeywords.clear();
2756 BestEditDistance = ED;
2757 } else if (ED > BestEditDistance) {
2758 // This result is worse than the best results we've seen so far;
2759 // ignore it.
2760 return;
2761 }
2762 } else
2763 BestEditDistance = ED;
2764
2765 BestKeywords.push_back(&Context.Idents.get(Keyword));
2766}
2767
Douglas Gregor546be3c2009-12-30 17:04:44 +00002768/// \brief Try to "correct" a typo in the source code by finding
2769/// visible declarations whose names are similar to the name that was
2770/// present in the source code.
2771///
2772/// \param Res the \c LookupResult structure that contains the name
2773/// that was present in the source code along with the name-lookup
2774/// criteria used to search for the name. On success, this structure
2775/// will contain the results of name lookup.
2776///
2777/// \param S the scope in which name lookup occurs.
2778///
2779/// \param SS the nested-name-specifier that precedes the name we're
2780/// looking for, if present.
2781///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002782/// \param MemberContext if non-NULL, the context in which to look for
2783/// a member access expression.
2784///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002785/// \param EnteringContext whether we're entering the context described by
2786/// the nested-name-specifier SS.
2787///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002788/// \param CTC The context in which typo correction occurs, which impacts the
2789/// set of keywords permitted.
2790///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002791/// \param OPT when non-NULL, the search for visible declarations will
2792/// also walk the protocols in the qualified interfaces of \p OPT.
2793///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002794/// \returns the corrected name if the typo was corrected, otherwise returns an
2795/// empty \c DeclarationName. When a typo was corrected, the result structure
2796/// may contain the results of name lookup for the correct name or it may be
2797/// empty.
2798DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002799 DeclContext *MemberContext,
2800 bool EnteringContext,
2801 CorrectTypoContext CTC,
2802 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00002803 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002804 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002805
2806 // Provide a stop gap for files that are just seriously broken. Trying
2807 // to correct all typos can turn into a HUGE performance penalty, causing
2808 // some files to take minutes to get rejected by the parser.
2809 // FIXME: Is this the right solution?
2810 if (TyposCorrected == 20)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002811 return DeclarationName();
Ted Kremenekd0ed4482010-02-02 02:07:01 +00002812 ++TyposCorrected;
Ted Kremenek1dac3412010-01-06 00:23:04 +00002813
Douglas Gregor546be3c2009-12-30 17:04:44 +00002814 // We only attempt to correct typos for identifiers.
2815 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2816 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002817 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002818
2819 // If the scope specifier itself was invalid, don't try to correct
2820 // typos.
2821 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002822 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002823
2824 // Never try to correct typos during template deduction or
2825 // instantiation.
2826 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002827 return DeclarationName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002828
Douglas Gregor546be3c2009-12-30 17:04:44 +00002829 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002830
2831 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002832 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002833 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002834
2835 // Look in qualified interfaces.
2836 if (OPT) {
2837 for (ObjCObjectPointerType::qual_iterator
2838 I = OPT->qual_begin(), E = OPT->qual_end();
2839 I != E; ++I)
2840 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2841 }
2842 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002843 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2844 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002845 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002846
2847 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2848 } else {
2849 LookupVisibleDecls(S, Res.getLookupKind(), Consumer);
2850 }
2851
Douglas Gregoraaf87162010-04-14 20:04:41 +00002852 // Add context-dependent keywords.
2853 bool WantTypeSpecifiers = false;
2854 bool WantExpressionKeywords = false;
2855 bool WantCXXNamedCasts = false;
2856 bool WantRemainingKeywords = false;
2857 switch (CTC) {
2858 case CTC_Unknown:
2859 WantTypeSpecifiers = true;
2860 WantExpressionKeywords = true;
2861 WantCXXNamedCasts = true;
2862 WantRemainingKeywords = true;
Douglas Gregor91f7ac72010-05-18 16:14:23 +00002863
2864 if (ObjCMethodDecl *Method = getCurMethodDecl())
2865 if (Method->getClassInterface() &&
2866 Method->getClassInterface()->getSuperClass())
2867 Consumer.addKeywordResult(Context, "super");
2868
Douglas Gregoraaf87162010-04-14 20:04:41 +00002869 break;
2870
2871 case CTC_NoKeywords:
2872 break;
2873
2874 case CTC_Type:
2875 WantTypeSpecifiers = true;
2876 break;
2877
2878 case CTC_ObjCMessageReceiver:
2879 Consumer.addKeywordResult(Context, "super");
2880 // Fall through to handle message receivers like expressions.
2881
2882 case CTC_Expression:
2883 if (getLangOptions().CPlusPlus)
2884 WantTypeSpecifiers = true;
2885 WantExpressionKeywords = true;
2886 // Fall through to get C++ named casts.
2887
2888 case CTC_CXXCasts:
2889 WantCXXNamedCasts = true;
2890 break;
2891
2892 case CTC_MemberLookup:
2893 if (getLangOptions().CPlusPlus)
2894 Consumer.addKeywordResult(Context, "template");
2895 break;
2896 }
2897
2898 if (WantTypeSpecifiers) {
2899 // Add type-specifier keywords to the set of results.
2900 const char *CTypeSpecs[] = {
2901 "char", "const", "double", "enum", "float", "int", "long", "short",
2902 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
2903 "_Complex", "_Imaginary",
2904 // storage-specifiers as well
2905 "extern", "inline", "static", "typedef"
2906 };
2907
2908 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
2909 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
2910 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
2911
2912 if (getLangOptions().C99)
2913 Consumer.addKeywordResult(Context, "restrict");
2914 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
2915 Consumer.addKeywordResult(Context, "bool");
2916
2917 if (getLangOptions().CPlusPlus) {
2918 Consumer.addKeywordResult(Context, "class");
2919 Consumer.addKeywordResult(Context, "typename");
2920 Consumer.addKeywordResult(Context, "wchar_t");
2921
2922 if (getLangOptions().CPlusPlus0x) {
2923 Consumer.addKeywordResult(Context, "char16_t");
2924 Consumer.addKeywordResult(Context, "char32_t");
2925 Consumer.addKeywordResult(Context, "constexpr");
2926 Consumer.addKeywordResult(Context, "decltype");
2927 Consumer.addKeywordResult(Context, "thread_local");
2928 }
2929 }
2930
2931 if (getLangOptions().GNUMode)
2932 Consumer.addKeywordResult(Context, "typeof");
2933 }
2934
Douglas Gregord0785ea2010-05-18 16:30:22 +00002935 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00002936 Consumer.addKeywordResult(Context, "const_cast");
2937 Consumer.addKeywordResult(Context, "dynamic_cast");
2938 Consumer.addKeywordResult(Context, "reinterpret_cast");
2939 Consumer.addKeywordResult(Context, "static_cast");
2940 }
2941
2942 if (WantExpressionKeywords) {
2943 Consumer.addKeywordResult(Context, "sizeof");
2944 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
2945 Consumer.addKeywordResult(Context, "false");
2946 Consumer.addKeywordResult(Context, "true");
2947 }
2948
2949 if (getLangOptions().CPlusPlus) {
2950 const char *CXXExprs[] = {
2951 "delete", "new", "operator", "throw", "typeid"
2952 };
2953 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
2954 for (unsigned I = 0; I != NumCXXExprs; ++I)
2955 Consumer.addKeywordResult(Context, CXXExprs[I]);
2956
2957 if (isa<CXXMethodDecl>(CurContext) &&
2958 cast<CXXMethodDecl>(CurContext)->isInstance())
2959 Consumer.addKeywordResult(Context, "this");
2960
2961 if (getLangOptions().CPlusPlus0x) {
2962 Consumer.addKeywordResult(Context, "alignof");
2963 Consumer.addKeywordResult(Context, "nullptr");
2964 }
2965 }
2966 }
2967
2968 if (WantRemainingKeywords) {
2969 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
2970 // Statements.
2971 const char *CStmts[] = {
2972 "do", "else", "for", "goto", "if", "return", "switch", "while" };
2973 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
2974 for (unsigned I = 0; I != NumCStmts; ++I)
2975 Consumer.addKeywordResult(Context, CStmts[I]);
2976
2977 if (getLangOptions().CPlusPlus) {
2978 Consumer.addKeywordResult(Context, "catch");
2979 Consumer.addKeywordResult(Context, "try");
2980 }
2981
2982 if (S && S->getBreakParent())
2983 Consumer.addKeywordResult(Context, "break");
2984
2985 if (S && S->getContinueParent())
2986 Consumer.addKeywordResult(Context, "continue");
2987
2988 if (!getSwitchStack().empty()) {
2989 Consumer.addKeywordResult(Context, "case");
2990 Consumer.addKeywordResult(Context, "default");
2991 }
2992 } else {
2993 if (getLangOptions().CPlusPlus) {
2994 Consumer.addKeywordResult(Context, "namespace");
2995 Consumer.addKeywordResult(Context, "template");
2996 }
2997
2998 if (S && S->isClassScope()) {
2999 Consumer.addKeywordResult(Context, "explicit");
3000 Consumer.addKeywordResult(Context, "friend");
3001 Consumer.addKeywordResult(Context, "mutable");
3002 Consumer.addKeywordResult(Context, "private");
3003 Consumer.addKeywordResult(Context, "protected");
3004 Consumer.addKeywordResult(Context, "public");
3005 Consumer.addKeywordResult(Context, "virtual");
3006 }
3007 }
3008
3009 if (getLangOptions().CPlusPlus) {
3010 Consumer.addKeywordResult(Context, "using");
3011
3012 if (getLangOptions().CPlusPlus0x)
3013 Consumer.addKeywordResult(Context, "static_assert");
3014 }
3015 }
3016
3017 // If we haven't found anything, we're done.
Douglas Gregor546be3c2009-12-30 17:04:44 +00003018 if (Consumer.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003019 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003020
3021 // Only allow a single, closest name in the result set (it's okay to
3022 // have overloads of that name, though).
Douglas Gregoraaf87162010-04-14 20:04:41 +00003023 DeclarationName BestName;
3024 NamedDecl *BestIvarOrPropertyDecl = 0;
3025 bool FoundIvarOrPropertyDecl = false;
3026
3027 // Check all of the declaration results to find the best name so far.
3028 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3029 IEnd = Consumer.end();
3030 I != IEnd; ++I) {
3031 if (!BestName)
3032 BestName = (*I)->getDeclName();
3033 else if (BestName != (*I)->getDeclName())
Douglas Gregor931f98a2010-04-14 17:09:22 +00003034 return DeclarationName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003035
Douglas Gregoraaf87162010-04-14 20:04:41 +00003036 // \brief Keep track of either an Objective-C ivar or a property, but not
3037 // both.
3038 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) {
3039 if (FoundIvarOrPropertyDecl)
3040 BestIvarOrPropertyDecl = 0;
3041 else {
3042 BestIvarOrPropertyDecl = *I;
3043 FoundIvarOrPropertyDecl = true;
3044 }
3045 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003046 }
3047
Douglas Gregoraaf87162010-04-14 20:04:41 +00003048 // Now check all of the keyword results to find the best name.
3049 switch (Consumer.keyword_size()) {
3050 case 0:
3051 // No keywords matched.
3052 break;
3053
3054 case 1:
3055 // If we already have a name
3056 if (!BestName) {
3057 // We did not have anything previously,
3058 BestName = *Consumer.keyword_begin();
3059 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) {
3060 // We have a declaration with the same name as a context-sensitive
3061 // keyword. The keyword takes precedence.
3062 BestIvarOrPropertyDecl = 0;
3063 FoundIvarOrPropertyDecl = false;
3064 Consumer.clear_decls();
Douglas Gregord0785ea2010-05-18 16:30:22 +00003065 } else if (CTC == CTC_ObjCMessageReceiver &&
3066 (*Consumer.keyword_begin())->isStr("super")) {
3067 // In an Objective-C message send, give the "super" keyword a slight
3068 // edge over entities not in function or method scope.
3069 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3070 IEnd = Consumer.end();
3071 I != IEnd; ++I) {
3072 if ((*I)->getDeclName() == BestName) {
3073 if ((*I)->getDeclContext()->isFunctionOrMethod())
3074 return DeclarationName();
3075 }
3076 }
3077
3078 // Everything found was outside a function or method; the 'super'
3079 // keyword takes precedence.
3080 BestIvarOrPropertyDecl = 0;
3081 FoundIvarOrPropertyDecl = false;
3082 Consumer.clear_decls();
3083 BestName = *Consumer.keyword_begin();
Douglas Gregoraaf87162010-04-14 20:04:41 +00003084 } else {
3085 // Name collision; we will not correct typos.
3086 return DeclarationName();
3087 }
3088 break;
3089
3090 default:
3091 // Name collision; we will not correct typos.
3092 return DeclarationName();
3093 }
3094
Douglas Gregor546be3c2009-12-30 17:04:44 +00003095 // BestName is the closest viable name to what the user
3096 // typed. However, to make sure that we don't pick something that's
3097 // way off, make sure that the user typed at least 3 characters for
3098 // each correction.
3099 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregoraaf87162010-04-14 20:04:41 +00003100 if (ED == 0 || !BestName.getAsIdentifierInfo() ||
3101 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3)
Douglas Gregor931f98a2010-04-14 17:09:22 +00003102 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003103
3104 // Perform name lookup again with the name we chose, and declare
3105 // success if we found something that was not ambiguous.
3106 Res.clear();
3107 Res.setLookupName(BestName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003108
3109 // If we found an ivar or property, add that result; no further
3110 // lookup is required.
Douglas Gregoraaf87162010-04-14 20:04:41 +00003111 if (BestIvarOrPropertyDecl)
3112 Res.addDecl(BestIvarOrPropertyDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003113 // If we're looking into the context of a member, perform qualified
3114 // name lookup on the best name.
Douglas Gregoraaf87162010-04-14 20:04:41 +00003115 else if (!Consumer.keyword_empty()) {
3116 // The best match was a keyword. Return it.
3117 return BestName;
3118 } else if (MemberContext)
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003119 LookupQualifiedName(Res, MemberContext);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003120 // Perform lookup as if we had just parsed the best name.
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003121 else
3122 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3123 EnteringContext);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003124
3125 if (Res.isAmbiguous()) {
3126 Res.suppressDiagnostics();
Douglas Gregor931f98a2010-04-14 17:09:22 +00003127 return DeclarationName();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00003128 }
3129
Douglas Gregor931f98a2010-04-14 17:09:22 +00003130 if (Res.getResultKind() != LookupResult::NotFound)
3131 return BestName;
3132
3133 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003134}