blob: d4db84b7761c8f809db3f246272e8a4850c62c87 [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
John McCall19510852010-08-20 18:27:03 +000017#include "clang/Sema/DeclSpec.h"
John McCall5f1e0942010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall2a7fb272010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000023#include "clang/AST/Decl.h"
24#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000026#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000027#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000028#include "clang/AST/ExprCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000030#include "clang/Basic/LangOptions.h"
John McCall50df6ae2010-08-25 07:03:20 +000031#include "llvm/ADT/DenseSet.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000034#include "llvm/ADT/StringMap.h"
John McCall6e247262009-10-10 05:48:19 +000035#include "llvm/Support/ErrorHandling.h"
Douglas Gregore24b5752010-10-14 20:34:08 +000036#include <limits>
Douglas Gregor546be3c2009-12-30 17:04:44 +000037#include <list>
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000038#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000039#include <vector>
40#include <iterator>
41#include <utility>
42#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000043
44using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000045using namespace sema;
Douglas Gregoreb11cd02009-01-14 22:20:51 +000046
John McCalld7be78a2009-11-10 07:01:13 +000047namespace {
48 class UnqualUsingEntry {
49 const DeclContext *Nominated;
50 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000051
John McCalld7be78a2009-11-10 07:01:13 +000052 public:
53 UnqualUsingEntry(const DeclContext *Nominated,
54 const DeclContext *CommonAncestor)
55 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
56 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000057
John McCalld7be78a2009-11-10 07:01:13 +000058 const DeclContext *getCommonAncestor() const {
59 return CommonAncestor;
60 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000061
John McCalld7be78a2009-11-10 07:01:13 +000062 const DeclContext *getNominatedNamespace() const {
63 return Nominated;
64 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000065
John McCalld7be78a2009-11-10 07:01:13 +000066 // Sort by the pointer value of the common ancestor.
67 struct Comparator {
68 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
69 return L.getCommonAncestor() < R.getCommonAncestor();
70 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000071
John McCalld7be78a2009-11-10 07:01:13 +000072 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
73 return E.getCommonAncestor() < DC;
74 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000075
John McCalld7be78a2009-11-10 07:01:13 +000076 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
77 return DC < E.getCommonAncestor();
78 }
79 };
80 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000081
John McCalld7be78a2009-11-10 07:01:13 +000082 /// A collection of using directives, as used by C++ unqualified
83 /// lookup.
84 class UnqualUsingDirectiveSet {
85 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000086
John McCalld7be78a2009-11-10 07:01:13 +000087 ListTy list;
88 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000089
John McCalld7be78a2009-11-10 07:01:13 +000090 public:
91 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000092
John McCalld7be78a2009-11-10 07:01:13 +000093 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
94 // C++ [namespace.udir]p1:
95 // During unqualified name lookup, the names appear as if they
96 // were declared in the nearest enclosing namespace which contains
97 // both the using-directive and the nominated namespace.
98 DeclContext *InnermostFileDC
99 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
100 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000101
John McCalld7be78a2009-11-10 07:01:13 +0000102 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +0000103 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
104 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
105 visit(Ctx, EffectiveDC);
106 } else {
107 Scope::udir_iterator I = S->using_directives_begin(),
108 End = S->using_directives_end();
109
110 for (; I != End; ++I)
John McCalld226f652010-08-21 09:40:31 +0000111 visit(*I, InnermostFileDC);
John McCalld7be78a2009-11-10 07:01:13 +0000112 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000113 }
114 }
John McCalld7be78a2009-11-10 07:01:13 +0000115
116 // Visits a context and collect all of its using directives
117 // recursively. Treats all using directives as if they were
118 // declared in the context.
119 //
120 // A given context is only every visited once, so it is important
121 // that contexts be visited from the inside out in order to get
122 // the effective DCs right.
123 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
124 if (!visited.insert(DC))
125 return;
126
127 addUsingDirectives(DC, EffectiveDC);
128 }
129
130 // Visits a using directive and collects all of its using
131 // directives recursively. Treats all using directives as if they
132 // were declared in the effective DC.
133 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
134 DeclContext *NS = UD->getNominatedNamespace();
135 if (!visited.insert(NS))
136 return;
137
138 addUsingDirective(UD, EffectiveDC);
139 addUsingDirectives(NS, EffectiveDC);
140 }
141
142 // Adds all the using directives in a context (and those nominated
143 // by its using directives, transitively) as if they appeared in
144 // the given effective context.
145 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
146 llvm::SmallVector<DeclContext*,4> queue;
147 while (true) {
148 DeclContext::udir_iterator I, End;
149 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
150 UsingDirectiveDecl *UD = *I;
151 DeclContext *NS = UD->getNominatedNamespace();
152 if (visited.insert(NS)) {
153 addUsingDirective(UD, EffectiveDC);
154 queue.push_back(NS);
155 }
156 }
157
158 if (queue.empty())
159 return;
160
161 DC = queue.back();
162 queue.pop_back();
163 }
164 }
165
166 // Add a using directive as if it had been declared in the given
167 // context. This helps implement C++ [namespace.udir]p3:
168 // The using-directive is transitive: if a scope contains a
169 // using-directive that nominates a second namespace that itself
170 // contains using-directives, the effect is as if the
171 // using-directives from the second namespace also appeared in
172 // the first.
173 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
174 // Find the common ancestor between the effective context and
175 // the nominated namespace.
176 DeclContext *Common = UD->getNominatedNamespace();
177 while (!Common->Encloses(EffectiveDC))
178 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000179 Common = Common->getPrimaryContext();
John McCalld7be78a2009-11-10 07:01:13 +0000180
181 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
182 }
183
184 void done() {
185 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
186 }
187
John McCalld7be78a2009-11-10 07:01:13 +0000188 typedef ListTy::const_iterator const_iterator;
189
John McCalld7be78a2009-11-10 07:01:13 +0000190 const_iterator begin() const { return list.begin(); }
191 const_iterator end() const { return list.end(); }
192
193 std::pair<const_iterator,const_iterator>
194 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000195 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000196 UnqualUsingEntry::Comparator());
197 }
198 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000199}
200
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000201// Retrieve the set of identifier namespaces that correspond to a
202// specific kind of name lookup.
John McCall1d7c5282009-12-18 10:40:03 +0000203static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
204 bool CPlusPlus,
205 bool Redeclaration) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000206 unsigned IDNS = 0;
207 switch (NameKind) {
208 case Sema::LookupOrdinaryName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000209 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000210 IDNS = Decl::IDNS_Ordinary;
John McCall1d7c5282009-12-18 10:40:03 +0000211 if (CPlusPlus) {
John McCall0d6b1642010-04-23 18:46:30 +0000212 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
John McCall1d7c5282009-12-18 10:40:03 +0000213 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
214 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000215 break;
216
John McCall76d32642010-04-24 01:30:58 +0000217 case Sema::LookupOperatorName:
218 // Operator lookup is its own crazy thing; it is not the same
219 // as (e.g.) looking up an operator name for redeclaration.
220 assert(!Redeclaration && "cannot do redeclaration operator lookup");
221 IDNS = Decl::IDNS_NonMemberOperator;
222 break;
223
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000224 case Sema::LookupTagName:
John McCall0d6b1642010-04-23 18:46:30 +0000225 if (CPlusPlus) {
226 IDNS = Decl::IDNS_Type;
227
228 // When looking for a redeclaration of a tag name, we add:
229 // 1) TagFriend to find undeclared friend decls
230 // 2) Namespace because they can't "overload" with tag decls.
231 // 3) Tag because it includes class templates, which can't
232 // "overload" with tag decls.
233 if (Redeclaration)
234 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
235 } else {
236 IDNS = Decl::IDNS_Tag;
237 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000238 break;
239
240 case Sema::LookupMemberName:
241 IDNS = Decl::IDNS_Member;
242 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000244 break;
245
246 case Sema::LookupNestedNameSpecifierName:
John McCall0d6b1642010-04-23 18:46:30 +0000247 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
248 break;
249
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000250 case Sema::LookupNamespaceName:
John McCall0d6b1642010-04-23 18:46:30 +0000251 IDNS = Decl::IDNS_Namespace;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000252 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000253
John McCall9f54ad42009-12-10 09:41:52 +0000254 case Sema::LookupUsingDeclName:
255 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
256 | Decl::IDNS_Member | Decl::IDNS_Using;
257 break;
258
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000259 case Sema::LookupObjCProtocolName:
260 IDNS = Decl::IDNS_ObjCProtocol;
261 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000262
263 case Sema::LookupAnyName:
264 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
265 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
266 | Decl::IDNS_Type;
267 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000268 }
269 return IDNS;
270}
271
John McCall1d7c5282009-12-18 10:40:03 +0000272void LookupResult::configure() {
273 IDNS = getIDNS(LookupKind,
274 SemaRef.getLangOptions().CPlusPlus,
275 isForRedeclaration());
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000276
277 // If we're looking for one of the allocation or deallocation
278 // operators, make sure that the implicitly-declared new and delete
279 // operators can be found.
280 if (!isForRedeclaration()) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000281 switch (NameInfo.getName().getCXXOverloadedOperator()) {
Douglas Gregorb5b2ccb2010-03-24 05:07:21 +0000282 case OO_New:
283 case OO_Delete:
284 case OO_Array_New:
285 case OO_Array_Delete:
286 SemaRef.DeclareGlobalNewDelete();
287 break;
288
289 default:
290 break;
291 }
292 }
John McCall1d7c5282009-12-18 10:40:03 +0000293}
294
John McCall2a7fb272010-08-25 05:32:35 +0000295void LookupResult::sanity() const {
296 assert(ResultKind != NotFound || Decls.size() == 0);
297 assert(ResultKind != Found || Decls.size() == 1);
298 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
299 (Decls.size() == 1 &&
300 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
301 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
302 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
Douglas Gregorf17b58c2010-10-22 22:08:47 +0000303 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
304 Ambiguity == AmbiguousBaseSubobjectTypes)));
John McCall2a7fb272010-08-25 05:32:35 +0000305 assert((Paths != NULL) == (ResultKind == Ambiguous &&
306 (Ambiguity == AmbiguousBaseSubobjectTypes ||
307 Ambiguity == AmbiguousBaseSubobjects)));
308}
John McCall2a7fb272010-08-25 05:32:35 +0000309
John McCallf36e02d2009-10-09 21:13:30 +0000310// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000311void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000312 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000313}
314
John McCall7453ed42009-11-22 00:44:51 +0000315/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000316void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000317 unsigned N = Decls.size();
John McCall9f54ad42009-12-10 09:41:52 +0000318
John McCallf36e02d2009-10-09 21:13:30 +0000319 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000320 if (N == 0) {
John McCalldc5c7862010-01-15 21:27:01 +0000321 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
John McCall68263142009-11-18 22:49:29 +0000322 return;
323 }
324
John McCall7453ed42009-11-22 00:44:51 +0000325 // If there's a single decl, we need to examine it to decide what
326 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000327 if (N == 1) {
Douglas Gregor2b147f02010-04-25 21:15:30 +0000328 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
329 if (isa<FunctionTemplateDecl>(D))
John McCall7453ed42009-11-22 00:44:51 +0000330 ResultKind = FoundOverloaded;
Douglas Gregor2b147f02010-04-25 21:15:30 +0000331 else if (isa<UnresolvedUsingValueDecl>(D))
John McCall7ba107a2009-11-18 02:36:19 +0000332 ResultKind = FoundUnresolvedValue;
333 return;
334 }
John McCallf36e02d2009-10-09 21:13:30 +0000335
John McCall6e247262009-10-10 05:48:19 +0000336 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000337 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000338
John McCallf36e02d2009-10-09 21:13:30 +0000339 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000340 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
341
John McCallf36e02d2009-10-09 21:13:30 +0000342 bool Ambiguous = false;
343 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000344 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000345
346 unsigned UniqueTagIndex = 0;
347
348 unsigned I = 0;
349 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000350 NamedDecl *D = Decls[I]->getUnderlyingDecl();
351 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000352
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000353 // Redeclarations of types via typedef can occur both within a scope
354 // and, through using declarations and directives, across scopes. There is
355 // no ambiguity if they all refer to the same type, so unique based on the
356 // canonical type.
357 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
358 if (!TD->getDeclContext()->isRecord()) {
359 QualType T = SemaRef.Context.getTypeDeclType(TD);
360 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
361 // The type is not unique; pull something off the back and continue
362 // at this index.
363 Decls[I] = Decls[--N];
364 continue;
365 }
366 }
367 }
368
John McCall314be4e2009-11-17 07:50:12 +0000369 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000370 // If it's not unique, pull something off the back (and
371 // continue at this index).
372 Decls[I] = Decls[--N];
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000373 continue;
374 }
375
376 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000377
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000378 if (isa<UnresolvedUsingValueDecl>(D)) {
379 HasUnresolved = true;
380 } else if (isa<TagDecl>(D)) {
381 if (HasTag)
382 Ambiguous = true;
383 UniqueTagIndex = I;
384 HasTag = true;
385 } else if (isa<FunctionTemplateDecl>(D)) {
386 HasFunction = true;
387 HasFunctionTemplate = true;
388 } else if (isa<FunctionDecl>(D)) {
389 HasFunction = true;
390 } else {
391 if (HasNonFunction)
392 Ambiguous = true;
393 HasNonFunction = true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000394 }
Douglas Gregor7f1c5472010-08-11 14:45:53 +0000395 I++;
Mike Stump1eb44332009-09-09 15:08:12 +0000396 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000397
John McCallf36e02d2009-10-09 21:13:30 +0000398 // C++ [basic.scope.hiding]p2:
399 // A class name or enumeration name can be hidden by the name of
400 // an object, function, or enumerator declared in the same
401 // scope. If a class or enumeration name and an object, function,
402 // or enumerator are declared in the same scope (in any order)
403 // with the same name, the class or enumeration name is hidden
404 // wherever the object, function, or enumerator name is visible.
405 // But it's still an error if there are distinct tag types found,
406 // even if they're not visible. (ref?)
John McCallfda8e122009-12-03 00:58:24 +0000407 if (HideTags && HasTag && !Ambiguous &&
Douglas Gregor77a1a882010-10-23 16:06:17 +0000408 (HasFunction || HasNonFunction || HasUnresolved)) {
409 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
410 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
411 Decls[UniqueTagIndex] = Decls[--N];
412 else
413 Ambiguous = true;
414 }
Anders Carlsson8b50d012009-06-26 03:37:05 +0000415
John McCallf36e02d2009-10-09 21:13:30 +0000416 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000417
John McCallfda8e122009-12-03 00:58:24 +0000418 if (HasNonFunction && (HasFunction || HasUnresolved))
John McCallf36e02d2009-10-09 21:13:30 +0000419 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000420
John McCallf36e02d2009-10-09 21:13:30 +0000421 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000422 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000423 else if (HasUnresolved)
424 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000425 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000426 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000427 else
John McCalla24dc2e2009-11-17 02:14:36 +0000428 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000429}
430
John McCall7d384dd2009-11-18 07:57:50 +0000431void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCall6b2accb2010-02-10 09:31:12 +0000432 CXXBasePaths::const_paths_iterator I, E;
John McCallf36e02d2009-10-09 21:13:30 +0000433 DeclContext::lookup_iterator DI, DE;
434 for (I = P.begin(), E = P.end(); I != E; ++I)
435 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
436 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000437}
438
John McCall7d384dd2009-11-18 07:57:50 +0000439void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000440 Paths = new CXXBasePaths;
441 Paths->swap(P);
442 addDeclsFromBasePaths(*Paths);
443 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000444 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000445}
446
John McCall7d384dd2009-11-18 07:57:50 +0000447void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000448 Paths = new CXXBasePaths;
449 Paths->swap(P);
450 addDeclsFromBasePaths(*Paths);
451 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000452 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000453}
454
John McCall7d384dd2009-11-18 07:57:50 +0000455void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000456 Out << Decls.size() << " result(s)";
457 if (isAmbiguous()) Out << ", ambiguous";
458 if (Paths) Out << ", base paths present";
459
460 for (iterator I = begin(), E = end(); I != E; ++I) {
461 Out << "\n";
462 (*I)->print(Out, 2);
463 }
464}
465
Douglas Gregor85910982010-02-12 05:48:04 +0000466/// \brief Lookup a builtin function, when name lookup would otherwise
467/// fail.
468static bool LookupBuiltin(Sema &S, LookupResult &R) {
469 Sema::LookupNameKind NameKind = R.getLookupKind();
470
471 // If we didn't find a use of this identifier, and if the identifier
472 // corresponds to a compiler builtin, create the decl object for the builtin
473 // now, injecting it into translation unit scope, and return it.
474 if (NameKind == Sema::LookupOrdinaryName ||
475 NameKind == Sema::LookupRedeclarationWithLinkage) {
476 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
477 if (II) {
478 // If this is a builtin on this (or all) targets, create the decl.
479 if (unsigned BuiltinID = II->getBuiltinID()) {
480 // In C++, we don't have any predefined library functions like
481 // 'malloc'. Instead, we'll just error.
482 if (S.getLangOptions().CPlusPlus &&
483 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
484 return false;
Fariborz Jahanian67aba812010-11-30 17:35:24 +0000485
Douglas Gregor85910982010-02-12 05:48:04 +0000486 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
487 S.TUScope, R.isForRedeclaration(),
488 R.getNameLoc());
489 if (D)
490 R.addDecl(D);
491 return (D != NULL);
492 }
493 }
494 }
495
496 return false;
497}
498
Douglas Gregor4923aa22010-07-02 20:37:36 +0000499/// \brief Determine whether we can declare a special member function within
500/// the class at this point.
501static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
502 const CXXRecordDecl *Class) {
John McCallb3b50a82010-08-11 23:52:36 +0000503 // Don't do it if the class is invalid.
504 if (Class->isInvalidDecl())
505 return false;
506
Douglas Gregor4923aa22010-07-02 20:37:36 +0000507 // We need to have a definition for the class.
508 if (!Class->getDefinition() || Class->isDependentContext())
509 return false;
510
511 // We can't be in the middle of defining the class.
512 if (const RecordType *RecordTy
513 = Context.getTypeDeclType(Class)->getAs<RecordType>())
514 return !RecordTy->isBeingDefined();
515
516 return false;
517}
518
519void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +0000520 if (!CanDeclareSpecialMemberFunction(Context, Class))
521 return;
Douglas Gregor18274032010-07-03 00:47:00 +0000522
523 // If the default constructor has not yet been declared, do so now.
524 if (!Class->hasDeclaredDefaultConstructor())
525 DeclareImplicitDefaultConstructor(Class);
Douglas Gregor22584312010-07-02 23:41:54 +0000526
527 // If the copy constructor has not yet been declared, do so now.
528 if (!Class->hasDeclaredCopyConstructor())
529 DeclareImplicitCopyConstructor(Class);
530
Douglas Gregora376d102010-07-02 21:50:04 +0000531 // If the copy assignment operator has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000532 if (!Class->hasDeclaredCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +0000533 DeclareImplicitCopyAssignment(Class);
534
Douglas Gregor4923aa22010-07-02 20:37:36 +0000535 // If the destructor has not yet been declared, do so now.
Douglas Gregor22584312010-07-02 23:41:54 +0000536 if (!Class->hasDeclaredDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +0000537 DeclareImplicitDestructor(Class);
538}
539
Douglas Gregora376d102010-07-02 21:50:04 +0000540/// \brief Determine whether this is the name of an implicitly-declared
541/// special member function.
542static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
543 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000544 case DeclarationName::CXXConstructorName:
Douglas Gregora376d102010-07-02 21:50:04 +0000545 case DeclarationName::CXXDestructorName:
546 return true;
547
548 case DeclarationName::CXXOperatorName:
549 return Name.getCXXOverloadedOperator() == OO_Equal;
550
551 default:
552 break;
553 }
554
555 return false;
556}
557
558/// \brief If there are any implicit member functions with the given name
559/// that need to be declared in the given declaration context, do so.
560static void DeclareImplicitMemberFunctionsWithName(Sema &S,
561 DeclarationName Name,
562 const DeclContext *DC) {
563 if (!DC)
564 return;
565
566 switch (Name.getNameKind()) {
Douglas Gregor22584312010-07-02 23:41:54 +0000567 case DeclarationName::CXXConstructorName:
568 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
Douglas Gregor18274032010-07-03 00:47:00 +0000569 if (Record->getDefinition() &&
570 CanDeclareSpecialMemberFunction(S.Context, Record)) {
571 if (!Record->hasDeclaredDefaultConstructor())
572 S.DeclareImplicitDefaultConstructor(
573 const_cast<CXXRecordDecl *>(Record));
574 if (!Record->hasDeclaredCopyConstructor())
575 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
576 }
Douglas Gregor22584312010-07-02 23:41:54 +0000577 break;
578
Douglas Gregora376d102010-07-02 21:50:04 +0000579 case DeclarationName::CXXDestructorName:
580 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
581 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
582 CanDeclareSpecialMemberFunction(S.Context, Record))
583 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
Douglas Gregora376d102010-07-02 21:50:04 +0000584 break;
585
586 case DeclarationName::CXXOperatorName:
587 if (Name.getCXXOverloadedOperator() != OO_Equal)
588 break;
589
590 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
591 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
592 CanDeclareSpecialMemberFunction(S.Context, Record))
593 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
594 break;
595
596 default:
597 break;
598 }
599}
Douglas Gregor4923aa22010-07-02 20:37:36 +0000600
John McCallf36e02d2009-10-09 21:13:30 +0000601// Adds all qualifying matches for a name within a decl context to the
602// given lookup result. Returns true if any matches were found.
Douglas Gregor85910982010-02-12 05:48:04 +0000603static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000604 bool Found = false;
605
Douglas Gregor4923aa22010-07-02 20:37:36 +0000606 // Lazily declare C++ special member functions.
Douglas Gregora376d102010-07-02 21:50:04 +0000607 if (S.getLangOptions().CPlusPlus)
608 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000609
610 // Perform lookup into this declaration context.
John McCalld7be78a2009-11-10 07:01:13 +0000611 DeclContext::lookup_const_iterator I, E;
Douglas Gregor48026d22010-01-11 18:40:55 +0000612 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
John McCall46460a62010-01-20 21:53:11 +0000613 NamedDecl *D = *I;
614 if (R.isAcceptableDecl(D)) {
615 R.addDecl(D);
Douglas Gregor48026d22010-01-11 18:40:55 +0000616 Found = true;
617 }
618 }
John McCallf36e02d2009-10-09 21:13:30 +0000619
Douglas Gregor85910982010-02-12 05:48:04 +0000620 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
621 return true;
622
Douglas Gregor48026d22010-01-11 18:40:55 +0000623 if (R.getLookupName().getNameKind()
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000624 != DeclarationName::CXXConversionFunctionName ||
625 R.getLookupName().getCXXNameType()->isDependentType() ||
626 !isa<CXXRecordDecl>(DC))
627 return Found;
628
629 // C++ [temp.mem]p6:
630 // A specialization of a conversion function template is not found by
631 // name lookup. Instead, any conversion function templates visible in the
632 // context of the use are considered. [...]
633 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
634 if (!Record->isDefinition())
635 return Found;
636
637 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
638 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
639 UEnd = Unresolved->end(); U != UEnd; ++U) {
640 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
641 if (!ConvTemplate)
642 continue;
643
644 // When we're performing lookup for the purposes of redeclaration, just
645 // add the conversion function template. When we deduce template
646 // arguments for specializations, we'll end up unifying the return
647 // type of the new declaration with the type of the function template.
648 if (R.isForRedeclaration()) {
649 R.addDecl(ConvTemplate);
650 Found = true;
651 continue;
652 }
653
Douglas Gregor48026d22010-01-11 18:40:55 +0000654 // C++ [temp.mem]p6:
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000655 // [...] For each such operator, if argument deduction succeeds
656 // (14.9.2.3), the resulting specialization is used as if found by
657 // name lookup.
658 //
659 // When referencing a conversion function for any purpose other than
660 // a redeclaration (such that we'll be building an expression with the
661 // result), perform template argument deduction and place the
662 // specialization into the result set. We do this to avoid forcing all
663 // callers to perform special deduction for conversion functions.
John McCall2a7fb272010-08-25 05:32:35 +0000664 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000665 FunctionDecl *Specialization = 0;
666
667 const FunctionProtoType *ConvProto
668 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
669 assert(ConvProto && "Nonsensical conversion function template type");
Douglas Gregor3f477a12010-01-12 01:17:50 +0000670
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000671 // Compute the type of the function that we would expect the conversion
672 // function to have, if it were to match the name given.
673 // FIXME: Calling convention!
John McCall0e88aa72010-12-14 06:51:39 +0000674 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
675 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
676 EPI.HasExceptionSpec = false;
677 EPI.HasAnyExceptionSpec = false;
678 EPI.NumExceptions = 0;
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000679 QualType ExpectedType
680 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
John McCall0e88aa72010-12-14 06:51:39 +0000681 0, 0, EPI);
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000682
683 // Perform template argument deduction against the type that we would
684 // expect the function to have.
685 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
686 Specialization, Info)
687 == Sema::TDK_Success) {
688 R.addDecl(Specialization);
689 Found = true;
Douglas Gregor48026d22010-01-11 18:40:55 +0000690 }
691 }
Chandler Carruthaaa1a892010-01-31 11:44:02 +0000692
John McCallf36e02d2009-10-09 21:13:30 +0000693 return Found;
694}
695
John McCalld7be78a2009-11-10 07:01:13 +0000696// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000697static bool
Douglas Gregor85910982010-02-12 05:48:04 +0000698CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
699 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000700
701 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
702
John McCalld7be78a2009-11-10 07:01:13 +0000703 // Perform direct name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +0000704 bool Found = LookupDirect(S, R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000705
John McCalld7be78a2009-11-10 07:01:13 +0000706 // Perform direct name lookup into the namespaces nominated by the
707 // using directives whose common ancestor is this namespace.
708 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
709 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000710
John McCalld7be78a2009-11-10 07:01:13 +0000711 for (; UI != UEnd; ++UI)
Douglas Gregor85910982010-02-12 05:48:04 +0000712 if (LookupDirect(S, R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000713 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000714
715 R.resolveKind();
716
717 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000718}
719
720static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000721 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000722 return Ctx->isFileContext();
723 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000724}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000725
Douglas Gregor711be1e2010-03-15 14:33:29 +0000726// Find the next outer declaration context from this scope. This
727// routine actually returns the semantic outer context, which may
728// differ from the lexical context (encoded directly in the Scope
729// stack) when we are parsing a member of a class template. In this
730// case, the second element of the pair will be true, to indicate that
731// name lookup should continue searching in this semantic context when
732// it leaves the current template parameter scope.
733static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
734 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
735 DeclContext *Lexical = 0;
736 for (Scope *OuterS = S->getParent(); OuterS;
737 OuterS = OuterS->getParent()) {
738 if (OuterS->getEntity()) {
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000739 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
Douglas Gregor711be1e2010-03-15 14:33:29 +0000740 break;
741 }
742 }
743
744 // C++ [temp.local]p8:
745 // In the definition of a member of a class template that appears
746 // outside of the namespace containing the class template
747 // definition, the name of a template-parameter hides the name of
748 // a member of this namespace.
749 //
750 // Example:
751 //
752 // namespace N {
753 // class C { };
754 //
755 // template<class T> class B {
756 // void f(T);
757 // };
758 // }
759 //
760 // template<class C> void N::B<C>::f(C) {
761 // C b; // C is the template parameter, not N::C
762 // }
763 //
764 // In this example, the lexical context we return is the
765 // TranslationUnit, while the semantic context is the namespace N.
766 if (!Lexical || !DC || !S->getParent() ||
767 !S->getParent()->isTemplateParamScope())
768 return std::make_pair(Lexical, false);
769
770 // Find the outermost template parameter scope.
771 // For the example, this is the scope for the template parameters of
772 // template<class C>.
773 Scope *OutermostTemplateScope = S->getParent();
774 while (OutermostTemplateScope->getParent() &&
775 OutermostTemplateScope->getParent()->isTemplateParamScope())
776 OutermostTemplateScope = OutermostTemplateScope->getParent();
Douglas Gregore942bbe2009-09-10 16:57:35 +0000777
Douglas Gregor711be1e2010-03-15 14:33:29 +0000778 // Find the namespace context in which the original scope occurs. In
779 // the example, this is namespace N.
780 DeclContext *Semantic = DC;
781 while (!Semantic->isFileContext())
782 Semantic = Semantic->getParent();
783
784 // Find the declaration context just outside of the template
785 // parameter scope. This is the context in which the template is
786 // being lexically declaration (a namespace context). In the
787 // example, this is the global scope.
788 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
789 Lexical->Encloses(Semantic))
790 return std::make_pair(Semantic, true);
791
792 return std::make_pair(Lexical, false);
Douglas Gregore942bbe2009-09-10 16:57:35 +0000793}
794
John McCalla24dc2e2009-11-17 02:14:36 +0000795bool Sema::CppLookupName(LookupResult &R, Scope *S) {
John McCall1d7c5282009-12-18 10:40:03 +0000796 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000797
798 DeclarationName Name = R.getLookupName();
799
Douglas Gregora376d102010-07-02 21:50:04 +0000800 // If this is the name of an implicitly-declared special member function,
801 // go through the scope stack to implicitly declare
802 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
803 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
804 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
805 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
806 }
807
808 // Implicitly declare member functions with the name we're looking for, if in
809 // fact we are in a scope where it matters.
810
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000811 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000812 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000813 I = IdResolver.begin(Name),
814 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000815
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000816 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000817 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000818 // ...During unqualified name lookup (3.4.1), the names appear as if
819 // they were declared in the nearest enclosing namespace which contains
820 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000821 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000822 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000823 //
824 // For example:
825 // namespace A { int i; }
826 // void foo() {
827 // int i;
828 // {
829 // using namespace A;
830 // ++i; // finds local 'i', A::i appears at global scope
831 // }
832 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000833 //
Douglas Gregor711be1e2010-03-15 14:33:29 +0000834 DeclContext *OutsideOfTemplateParamDC = 0;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000835 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregord2235f62010-05-20 20:58:56 +0000836 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
837
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000838 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000839 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000840 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000841 if (R.isAcceptableDecl(*I)) {
John McCallf36e02d2009-10-09 21:13:30 +0000842 Found = true;
843 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000844 }
845 }
John McCallf36e02d2009-10-09 21:13:30 +0000846 if (Found) {
847 R.resolveKind();
Douglas Gregord2235f62010-05-20 20:58:56 +0000848 if (S->isClassScope())
849 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
850 R.setNamingClass(Record);
John McCallf36e02d2009-10-09 21:13:30 +0000851 return true;
852 }
853
Douglas Gregor711be1e2010-03-15 14:33:29 +0000854 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
855 S->getParent() && !S->getParent()->isTemplateParamScope()) {
856 // We've just searched the last template parameter scope and
857 // found nothing, so look into the the contexts between the
858 // lexical and semantic declaration contexts returned by
859 // findOuterContext(). This implements the name lookup behavior
860 // of C++ [temp.local]p8.
861 Ctx = OutsideOfTemplateParamDC;
862 OutsideOfTemplateParamDC = 0;
863 }
864
865 if (Ctx) {
866 DeclContext *OuterCtx;
867 bool SearchAfterTemplateScope;
868 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
869 if (SearchAfterTemplateScope)
870 OutsideOfTemplateParamDC = OuterCtx;
871
Douglas Gregordbdf5e72010-03-15 15:26:48 +0000872 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
Douglas Gregor36262b82010-02-19 16:08:35 +0000873 // We do not directly look into transparent contexts, since
874 // those entities will be found in the nearest enclosing
875 // non-transparent context.
876 if (Ctx->isTransparentContext())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000877 continue;
Douglas Gregor36262b82010-02-19 16:08:35 +0000878
879 // We do not look directly into function or method contexts,
880 // since all of the local variables and parameters of the
881 // function/method are present within the Scope.
882 if (Ctx->isFunctionOrMethod()) {
883 // If we have an Objective-C instance method, look for ivars
884 // in the corresponding interface.
885 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
886 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
887 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
888 ObjCInterfaceDecl *ClassDeclared;
889 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
890 Name.getAsIdentifierInfo(),
891 ClassDeclared)) {
892 if (R.isAcceptableDecl(Ivar)) {
893 R.addDecl(Ivar);
894 R.resolveKind();
895 return true;
896 }
897 }
898 }
899 }
900
901 continue;
902 }
903
Douglas Gregore942bbe2009-09-10 16:57:35 +0000904 // Perform qualified name lookup into this context.
905 // FIXME: In some cases, we know that every name that could be found by
906 // this qualified name lookup will also be on the identifier chain. For
907 // example, inside a class without any base classes, we never need to
908 // perform qualified lookup because all of the members are on top of the
909 // identifier chain.
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000910 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
John McCallf36e02d2009-10-09 21:13:30 +0000911 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000912 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000913 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000914 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000915
John McCalld7be78a2009-11-10 07:01:13 +0000916 // Stop if we ran out of scopes.
917 // FIXME: This really, really shouldn't be happening.
918 if (!S) return false;
919
Argyrios Kyrtzidis78f59112010-10-29 16:12:50 +0000920 // If we are looking for members, no need to look into global/namespace scope.
921 if (R.getLookupKind() == LookupMemberName)
922 return false;
923
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000924 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000925 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000926 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000927 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
928 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000929
John McCalld7be78a2009-11-10 07:01:13 +0000930 UnqualUsingDirectiveSet UDirs;
931 UDirs.visitScopeChain(Initial, S);
932 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000933
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000934 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000935 // Unqualified name lookup in C++ requires looking into scopes
936 // that aren't strictly lexical, and therefore we walk through the
937 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000938
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000939 for (; S; S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000940 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000941 bool Found = false;
John McCalld226f652010-08-21 09:40:31 +0000942 for (; I != IEnd && S->isDeclScope(*I); ++I) {
John McCall1d7c5282009-12-18 10:40:03 +0000943 if (R.isAcceptableDecl(*I)) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000944 // We found something. Look for anything else in our scope
945 // with this same name and in an acceptable identifier
946 // namespace, so that we can construct an overload set if we
947 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000948 Found = true;
949 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000950 }
951 }
952
Douglas Gregor00b4b032010-05-14 04:53:42 +0000953 if (Found && S->isTemplateParamScope()) {
John McCallf36e02d2009-10-09 21:13:30 +0000954 R.resolveKind();
955 return true;
956 }
957
Douglas Gregor00b4b032010-05-14 04:53:42 +0000958 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
959 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
960 S->getParent() && !S->getParent()->isTemplateParamScope()) {
961 // We've just searched the last template parameter scope and
962 // found nothing, so look into the the contexts between the
963 // lexical and semantic declaration contexts returned by
964 // findOuterContext(). This implements the name lookup behavior
965 // of C++ [temp.local]p8.
966 Ctx = OutsideOfTemplateParamDC;
967 OutsideOfTemplateParamDC = 0;
968 }
969
970 if (Ctx) {
971 DeclContext *OuterCtx;
972 bool SearchAfterTemplateScope;
973 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
974 if (SearchAfterTemplateScope)
975 OutsideOfTemplateParamDC = OuterCtx;
976
977 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
978 // We do not directly look into transparent contexts, since
979 // those entities will be found in the nearest enclosing
980 // non-transparent context.
981 if (Ctx->isTransparentContext())
982 continue;
983
984 // If we have a context, and it's not a context stashed in the
985 // template parameter scope for an out-of-line definition, also
986 // look into that context.
987 if (!(Found && S && S->isTemplateParamScope())) {
988 assert(Ctx->isFileContext() &&
989 "We should have been looking only at file context here already.");
990
991 // Look into context considering using-directives.
992 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
993 Found = true;
994 }
995
996 if (Found) {
997 R.resolveKind();
998 return true;
999 }
1000
1001 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1002 return false;
1003 }
1004 }
1005
Douglas Gregor1df0ee92010-02-05 07:07:10 +00001006 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +00001007 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +00001008 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001009
John McCallf36e02d2009-10-09 21:13:30 +00001010 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001011}
1012
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001013/// @brief Perform unqualified name lookup starting from a given
1014/// scope.
1015///
1016/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1017/// used to find names within the current scope. For example, 'x' in
1018/// @code
1019/// int x;
1020/// int f() {
1021/// return x; // unqualified name look finds 'x' in the global scope
1022/// }
1023/// @endcode
1024///
1025/// Different lookup criteria can find different names. For example, a
1026/// particular scope can have both a struct and a function of the same
1027/// name, and each can be found by certain lookup criteria. For more
1028/// information about lookup criteria, see the documentation for the
1029/// class LookupCriteria.
1030///
1031/// @param S The scope from which unqualified name lookup will
1032/// begin. If the lookup criteria permits, name lookup may also search
1033/// in the parent scopes.
1034///
1035/// @param Name The name of the entity that we are searching for.
1036///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001037/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001038/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001039/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001040///
1041/// @returns The result of name lookup, which includes zero or more
1042/// declarations and possibly additional information used to diagnose
1043/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +00001044bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1045 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +00001046 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001047
John McCalla24dc2e2009-11-17 02:14:36 +00001048 LookupNameKind NameKind = R.getLookupKind();
1049
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001050 if (!getLangOptions().CPlusPlus) {
1051 // Unqualified name lookup in C/Objective-C is purely lexical, so
1052 // search in the declarations attached to the name.
1053
John McCall1d7c5282009-12-18 10:40:03 +00001054 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001055 // Find the nearest non-transparent declaration scope.
1056 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001057 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001058 static_cast<DeclContext *>(S->getEntity())
1059 ->isTransparentContext()))
1060 S = S->getParent();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001061 }
1062
John McCall1d7c5282009-12-18 10:40:03 +00001063 unsigned IDNS = R.getIdentifierNamespace();
1064
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001065 // Scan up the scope chain looking for a decl that matches this
1066 // identifier that is in the appropriate namespace. This search
1067 // should not take long, as shadowing of names is uncommon, and
1068 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001069 bool LeftStartingScope = false;
1070
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001071 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +00001072 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001073 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001074 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001075 if (NameKind == LookupRedeclarationWithLinkage) {
1076 // Determine whether this (or a previous) declaration is
1077 // out-of-scope.
John McCalld226f652010-08-21 09:40:31 +00001078 if (!LeftStartingScope && !S->isDeclScope(*I))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001079 LeftStartingScope = true;
1080
1081 // If we found something outside of our starting scope that
1082 // does not have linkage, skip it.
1083 if (LeftStartingScope && !((*I)->hasLinkage()))
1084 continue;
1085 }
1086
John McCallf36e02d2009-10-09 21:13:30 +00001087 R.addDecl(*I);
1088
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001089 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001090 // If this declaration has the "overloadable" attribute, we
1091 // might have a set of overloaded functions.
1092
1093 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001094 while (!(S->getFlags() & Scope::DeclScope) ||
John McCalld226f652010-08-21 09:40:31 +00001095 !S->isDeclScope(*I))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001096 S = S->getParent();
1097
1098 // Find the last declaration in this scope (with the same
1099 // name, naturally).
1100 IdentifierResolver::iterator LastI = I;
1101 for (++LastI; LastI != IEnd; ++LastI) {
John McCalld226f652010-08-21 09:40:31 +00001102 if (!S->isDeclScope(*LastI))
Douglas Gregorf9201e02009-02-11 23:02:49 +00001103 break;
John McCallf36e02d2009-10-09 21:13:30 +00001104 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001105 }
Douglas Gregorf9201e02009-02-11 23:02:49 +00001106 }
1107
John McCallf36e02d2009-10-09 21:13:30 +00001108 R.resolveKind();
1109
1110 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +00001111 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001112 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001113 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +00001114 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +00001115 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001116 }
1117
1118 // If we didn't find a use of this identifier, and if the identifier
1119 // corresponds to a compiler builtin, create the decl object for the builtin
1120 // now, injecting it into translation unit scope, and return it.
Douglas Gregor85910982010-02-12 05:48:04 +00001121 if (AllowBuiltinCreation)
1122 return LookupBuiltin(*this, R);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001123
John McCallf36e02d2009-10-09 21:13:30 +00001124 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001125}
1126
John McCall6e247262009-10-10 05:48:19 +00001127/// @brief Perform qualified name lookup in the namespaces nominated by
1128/// using directives by the given context.
1129///
1130/// C++98 [namespace.qual]p2:
1131/// Given X::m (where X is a user-declared namespace), or given ::m
1132/// (where X is the global namespace), let S be the set of all
1133/// declarations of m in X and in the transitive closure of all
1134/// namespaces nominated by using-directives in X and its used
1135/// namespaces, except that using-directives are ignored in any
1136/// namespace, including X, directly containing one or more
1137/// declarations of m. No namespace is searched more than once in
1138/// the lookup of a name. If S is the empty set, the program is
1139/// ill-formed. Otherwise, if S has exactly one member, or if the
1140/// context of the reference is a using-declaration
1141/// (namespace.udecl), S is the required set of declarations of
1142/// m. Otherwise if the use of m is not one that allows a unique
1143/// declaration to be chosen from S, the program is ill-formed.
1144/// C++98 [namespace.qual]p5:
1145/// During the lookup of a qualified namespace member name, if the
1146/// lookup finds more than one declaration of the member, and if one
1147/// declaration introduces a class name or enumeration name and the
1148/// other declarations either introduce the same object, the same
1149/// enumerator or a set of functions, the non-type name hides the
1150/// class or enumeration name if and only if the declarations are
1151/// from the same namespace; otherwise (the declarations are from
1152/// different namespaces), the program is ill-formed.
Douglas Gregor85910982010-02-12 05:48:04 +00001153static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +00001154 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +00001155 assert(StartDC->isFileContext() && "start context is not a file context");
1156
1157 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1158 DeclContext::udir_iterator E = StartDC->using_directives_end();
1159
1160 if (I == E) return false;
1161
1162 // We have at least added all these contexts to the queue.
1163 llvm::DenseSet<DeclContext*> Visited;
1164 Visited.insert(StartDC);
1165
1166 // We have not yet looked into these namespaces, much less added
1167 // their "using-children" to the queue.
1168 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1169
1170 // We have already looked into the initial namespace; seed the queue
1171 // with its using-children.
1172 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +00001173 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +00001174 if (Visited.insert(ND).second)
1175 Queue.push_back(ND);
1176 }
1177
1178 // The easiest way to implement the restriction in [namespace.qual]p5
1179 // is to check whether any of the individual results found a tag
1180 // and, if so, to declare an ambiguity if the final result is not
1181 // a tag.
1182 bool FoundTag = false;
1183 bool FoundNonTag = false;
1184
John McCall7d384dd2009-11-18 07:57:50 +00001185 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +00001186
1187 bool Found = false;
1188 while (!Queue.empty()) {
1189 NamespaceDecl *ND = Queue.back();
1190 Queue.pop_back();
1191
1192 // We go through some convolutions here to avoid copying results
1193 // between LookupResults.
1194 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +00001195 LookupResult &DirectR = UseLocal ? LocalR : R;
Douglas Gregor85910982010-02-12 05:48:04 +00001196 bool FoundDirect = LookupDirect(S, DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +00001197
1198 if (FoundDirect) {
1199 // First do any local hiding.
1200 DirectR.resolveKind();
1201
1202 // If the local result is a tag, remember that.
1203 if (DirectR.isSingleTagDecl())
1204 FoundTag = true;
1205 else
1206 FoundNonTag = true;
1207
1208 // Append the local results to the total results if necessary.
1209 if (UseLocal) {
1210 R.addAllDecls(LocalR);
1211 LocalR.clear();
1212 }
1213 }
1214
1215 // If we find names in this namespace, ignore its using directives.
1216 if (FoundDirect) {
1217 Found = true;
1218 continue;
1219 }
1220
1221 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1222 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1223 if (Visited.insert(Nom).second)
1224 Queue.push_back(Nom);
1225 }
1226 }
1227
1228 if (Found) {
1229 if (FoundTag && FoundNonTag)
1230 R.setAmbiguousQualifiedTagHiding();
1231 else
1232 R.resolveKind();
1233 }
1234
1235 return Found;
1236}
1237
Douglas Gregor8071e422010-08-15 06:18:01 +00001238/// \brief Callback that looks for any member of a class with the given name.
1239static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1240 CXXBasePath &Path,
1241 void *Name) {
1242 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1243
1244 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1245 Path.Decls = BaseRecord->lookup(N);
1246 return Path.Decls.first != Path.Decls.second;
1247}
1248
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001249/// \brief Determine whether the given set of member declarations contains only
1250/// static members, nested types, and enumerators.
1251template<typename InputIterator>
1252static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1253 Decl *D = (*First)->getUnderlyingDecl();
1254 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1255 return true;
1256
1257 if (isa<CXXMethodDecl>(D)) {
1258 // Determine whether all of the methods are static.
1259 bool AllMethodsAreStatic = true;
1260 for(; First != Last; ++First) {
1261 D = (*First)->getUnderlyingDecl();
1262
1263 if (!isa<CXXMethodDecl>(D)) {
1264 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1265 break;
1266 }
1267
1268 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1269 AllMethodsAreStatic = false;
1270 break;
1271 }
1272 }
1273
1274 if (AllMethodsAreStatic)
1275 return true;
1276 }
1277
1278 return false;
1279}
1280
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001281/// \brief Perform qualified name lookup into a given context.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001282///
1283/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1284/// names when the context of those names is explicit specified, e.g.,
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001285/// "std::vector" or "x->member", or as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001286///
1287/// Different lookup criteria can find different names. For example, a
1288/// particular scope can have both a struct and a function of the same
1289/// name, and each can be found by certain lookup criteria. For more
1290/// information about lookup criteria, see the documentation for the
1291/// class LookupCriteria.
1292///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001293/// \param R captures both the lookup criteria and any lookup results found.
1294///
1295/// \param LookupCtx The context in which qualified name lookup will
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001296/// search. If the lookup criteria permits, name lookup may also search
1297/// in the parent contexts or (for C++ classes) base classes.
1298///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001299/// \param InUnqualifiedLookup true if this is qualified name lookup that
1300/// occurs as part of unqualified name lookup.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001301///
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001302/// \returns true if lookup succeeded, false if it failed.
1303bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1304 bool InUnqualifiedLookup) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001305 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +00001306
John McCalla24dc2e2009-11-17 02:14:36 +00001307 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +00001308 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001310 // Make sure that the declaration context is complete.
1311 assert((!isa<TagDecl>(LookupCtx) ||
1312 LookupCtx->isDependentContext() ||
1313 cast<TagDecl>(LookupCtx)->isDefinition() ||
1314 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1315 ->isBeingDefined()) &&
1316 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001318 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor85910982010-02-12 05:48:04 +00001319 if (LookupDirect(*this, R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +00001320 R.resolveKind();
John McCall92f88312010-01-23 00:46:32 +00001321 if (isa<CXXRecordDecl>(LookupCtx))
1322 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
John McCallf36e02d2009-10-09 21:13:30 +00001323 return true;
1324 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001325
John McCall6e247262009-10-10 05:48:19 +00001326 // Don't descend into implied contexts for redeclarations.
1327 // C++98 [namespace.qual]p6:
1328 // In a declaration for a namespace member in which the
1329 // declarator-id is a qualified-id, given that the qualified-id
1330 // for the namespace member has the form
1331 // nested-name-specifier unqualified-id
1332 // the unqualified-id shall name a member of the namespace
1333 // designated by the nested-name-specifier.
1334 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +00001335 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +00001336 return false;
1337
John McCalla24dc2e2009-11-17 02:14:36 +00001338 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +00001339 if (LookupCtx->isFileContext())
Douglas Gregor85910982010-02-12 05:48:04 +00001340 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +00001341
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001342 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +00001343 // classes, we're done.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001344 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
Douglas Gregor025291b2010-07-01 00:21:21 +00001345 if (!LookupRec || !LookupRec->getDefinition())
John McCallf36e02d2009-10-09 21:13:30 +00001346 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001347
Douglas Gregor7d3f5762010-01-15 01:44:47 +00001348 // If we're performing qualified name lookup into a dependent class,
1349 // then we are actually looking into a current instantiation. If we have any
1350 // dependent base classes, then we either have to delay lookup until
1351 // template instantiation time (at which point all bases will be available)
1352 // or we have to fail.
1353 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1354 LookupRec->hasAnyDependentBases()) {
1355 R.setNotFoundInCurrentInstantiation();
1356 return false;
1357 }
1358
Douglas Gregor7176fff2009-01-15 00:26:24 +00001359 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001360 CXXBasePaths Paths;
1361 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001362
1363 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +00001364 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00001365 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001366 case LookupOrdinaryName:
1367 case LookupMemberName:
1368 case LookupRedeclarationWithLinkage:
1369 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1370 break;
1371
1372 case LookupTagName:
1373 BaseCallback = &CXXRecordDecl::FindTagMember;
1374 break;
John McCall9f54ad42009-12-10 09:41:52 +00001375
Douglas Gregor8071e422010-08-15 06:18:01 +00001376 case LookupAnyName:
1377 BaseCallback = &LookupAnyMember;
1378 break;
1379
John McCall9f54ad42009-12-10 09:41:52 +00001380 case LookupUsingDeclName:
1381 // This lookup is for redeclarations only.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001382
1383 case LookupOperatorName:
1384 case LookupNamespaceName:
1385 case LookupObjCProtocolName:
Douglas Gregora8f32e02009-10-06 17:59:45 +00001386 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +00001387 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001388
1389 case LookupNestedNameSpecifierName:
1390 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1391 break;
1392 }
1393
John McCalla24dc2e2009-11-17 02:14:36 +00001394 if (!LookupRec->lookupInBases(BaseCallback,
1395 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +00001396 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001397
John McCall92f88312010-01-23 00:46:32 +00001398 R.setNamingClass(LookupRec);
1399
Douglas Gregor7176fff2009-01-15 00:26:24 +00001400 // C++ [class.member.lookup]p2:
1401 // [...] If the resulting set of declarations are not all from
1402 // sub-objects of the same type, or the set has a nonstatic member
1403 // and includes members from distinct sub-objects, there is an
1404 // ambiguity and the program is ill-formed. Otherwise that set is
1405 // the result of the lookup.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001406 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001407 int SubobjectNumber = 0;
John McCall7aceaf82010-03-18 23:49:19 +00001408 AccessSpecifier SubobjectAccess = AS_none;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001409
Douglas Gregora8f32e02009-10-06 17:59:45 +00001410 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001411 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001412 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +00001413
John McCall46460a62010-01-20 21:53:11 +00001414 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1415 // across all paths.
1416 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1417
Douglas Gregor7176fff2009-01-15 00:26:24 +00001418 // Determine whether we're looking at a distinct sub-object or not.
1419 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +00001420 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001421 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1422 SubobjectNumber = PathElement.SubobjectNumber;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001423 continue;
1424 }
1425
1426 if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +00001427 != Context.getCanonicalType(PathElement.Base->getType())) {
1428 // We found members of the given name in two subobjects of
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001429 // different types. If the declaration sets aren't the same, this
1430 // this lookup is ambiguous.
1431 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1432 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1433 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1434 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
1435
1436 while (FirstD != FirstPath->Decls.second &&
1437 CurrentD != Path->Decls.second) {
1438 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1439 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1440 break;
1441
1442 ++FirstD;
1443 ++CurrentD;
1444 }
1445
1446 if (FirstD == FirstPath->Decls.second &&
1447 CurrentD == Path->Decls.second)
1448 continue;
1449 }
1450
John McCallf36e02d2009-10-09 21:13:30 +00001451 R.setAmbiguousBaseSubobjectTypes(Paths);
1452 return true;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001453 }
1454
1455 if (SubobjectNumber != PathElement.SubobjectNumber) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001456 // We have a different subobject of the same type.
1457
1458 // C++ [class.member.lookup]p5:
1459 // A static member, a nested type or an enumerator defined in
1460 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +00001461 // has more than one base class subobject of type T.
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001462 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
Douglas Gregor7176fff2009-01-15 00:26:24 +00001463 continue;
Douglas Gregorf17b58c2010-10-22 22:08:47 +00001464
Douglas Gregor7176fff2009-01-15 00:26:24 +00001465 // We have found a nonstatic member name in multiple, distinct
1466 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001467 R.setAmbiguousBaseSubobjects(Paths);
1468 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001469 }
1470 }
1471
1472 // Lookup in a base class succeeded; return these results.
1473
John McCallf36e02d2009-10-09 21:13:30 +00001474 DeclContext::lookup_iterator I, E;
John McCall92f88312010-01-23 00:46:32 +00001475 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1476 NamedDecl *D = *I;
1477 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1478 D->getAccess());
1479 R.addDecl(D, AS);
1480 }
John McCallf36e02d2009-10-09 21:13:30 +00001481 R.resolveKind();
1482 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001483}
1484
1485/// @brief Performs name lookup for a name that was parsed in the
1486/// source code, and may contain a C++ scope specifier.
1487///
1488/// This routine is a convenience routine meant to be called from
1489/// contexts that receive a name and an optional C++ scope specifier
1490/// (e.g., "N::M::x"). It will then perform either qualified or
1491/// unqualified name lookup (with LookupQualifiedName or LookupName,
1492/// respectively) on the given name and return those results.
1493///
1494/// @param S The scope from which unqualified name lookup will
1495/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001496///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001497/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001498///
1499/// @param Name The name of the entity that name lookup will
1500/// search for.
1501///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001502/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001503/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001504/// C library functions (like "malloc") are implicitly declared.
1505///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001506/// @param EnteringContext Indicates whether we are going to enter the
1507/// context of the scope-specifier SS (if present).
1508///
John McCallf36e02d2009-10-09 21:13:30 +00001509/// @returns True if any decls were found (but possibly ambiguous)
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001510bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001511 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001512 if (SS && SS->isInvalid()) {
1513 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001514 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001515 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001516 }
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Douglas Gregor495c35d2009-08-25 22:51:20 +00001518 if (SS && SS->isSet()) {
1519 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001520 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001521 // contex, and will perform name lookup in that context.
John McCall77bb1aa2010-05-01 00:40:08 +00001522 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
John McCallf36e02d2009-10-09 21:13:30 +00001523 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001524
John McCalla24dc2e2009-11-17 02:14:36 +00001525 R.setContextRange(SS->getRange());
1526
1527 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001528 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001529
Douglas Gregor495c35d2009-08-25 22:51:20 +00001530 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001531 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001532 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001533 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001534 }
1535
Mike Stump1eb44332009-09-09 15:08:12 +00001536 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001537 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001538}
1539
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001540
Douglas Gregor7176fff2009-01-15 00:26:24 +00001541/// @brief Produce a diagnostic describing the ambiguity that resulted
1542/// from name lookup.
1543///
1544/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001545///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001546/// @param Name The name of the entity that name lookup was
1547/// searching for.
1548///
1549/// @param NameLoc The location of the name within the source code.
1550///
1551/// @param LookupRange A source range that provides more
1552/// source-location information concerning the lookup itself. For
1553/// example, this range might highlight a nested-name-specifier that
1554/// precedes the name.
1555///
1556/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001557bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001558 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1559
John McCalla24dc2e2009-11-17 02:14:36 +00001560 DeclarationName Name = Result.getLookupName();
1561 SourceLocation NameLoc = Result.getNameLoc();
1562 SourceRange LookupRange = Result.getContextRange();
1563
John McCall6e247262009-10-10 05:48:19 +00001564 switch (Result.getAmbiguityKind()) {
1565 case LookupResult::AmbiguousBaseSubobjects: {
1566 CXXBasePaths *Paths = Result.getBasePaths();
1567 QualType SubobjectType = Paths->front().back().Base->getType();
1568 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1569 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1570 << LookupRange;
1571
1572 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1573 while (isa<CXXMethodDecl>(*Found) &&
1574 cast<CXXMethodDecl>(*Found)->isStatic())
1575 ++Found;
1576
1577 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1578
1579 return true;
1580 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001581
John McCall6e247262009-10-10 05:48:19 +00001582 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001583 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1584 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001585
1586 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001587 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001588 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1589 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001590 Path != PathEnd; ++Path) {
1591 Decl *D = *Path->Decls.first;
1592 if (DeclsPrinted.insert(D).second)
1593 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1594 }
1595
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001596 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001597 }
1598
John McCall6e247262009-10-10 05:48:19 +00001599 case LookupResult::AmbiguousTagHiding: {
1600 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001601
John McCall6e247262009-10-10 05:48:19 +00001602 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1603
1604 LookupResult::iterator DI, DE = Result.end();
1605 for (DI = Result.begin(); DI != DE; ++DI)
1606 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1607 TagDecls.insert(TD);
1608 Diag(TD->getLocation(), diag::note_hidden_tag);
1609 }
1610
1611 for (DI = Result.begin(); DI != DE; ++DI)
1612 if (!isa<TagDecl>(*DI))
1613 Diag((*DI)->getLocation(), diag::note_hiding_object);
1614
1615 // For recovery purposes, go ahead and implement the hiding.
John McCalleec51cf2010-01-20 00:46:10 +00001616 LookupResult::Filter F = Result.makeFilter();
1617 while (F.hasNext()) {
1618 if (TagDecls.count(F.next()))
1619 F.erase();
1620 }
1621 F.done();
John McCall6e247262009-10-10 05:48:19 +00001622
1623 return true;
1624 }
1625
1626 case LookupResult::AmbiguousReference: {
1627 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001628
John McCall6e247262009-10-10 05:48:19 +00001629 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1630 for (; DI != DE; ++DI)
1631 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001632
John McCall6e247262009-10-10 05:48:19 +00001633 return true;
1634 }
1635 }
1636
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001637 llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001638 return true;
1639}
Douglas Gregorfa047642009-02-04 00:32:51 +00001640
John McCallc7e04da2010-05-28 18:45:08 +00001641namespace {
1642 struct AssociatedLookup {
1643 AssociatedLookup(Sema &S,
1644 Sema::AssociatedNamespaceSet &Namespaces,
1645 Sema::AssociatedClassSet &Classes)
1646 : S(S), Namespaces(Namespaces), Classes(Classes) {
1647 }
1648
1649 Sema &S;
1650 Sema::AssociatedNamespaceSet &Namespaces;
1651 Sema::AssociatedClassSet &Classes;
1652 };
1653}
1654
Mike Stump1eb44332009-09-09 15:08:12 +00001655static void
John McCallc7e04da2010-05-28 18:45:08 +00001656addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
John McCall6ff07852009-08-07 22:18:02 +00001657
Douglas Gregor54022952010-04-30 07:08:38 +00001658static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1659 DeclContext *Ctx) {
1660 // Add the associated namespace for this class.
1661
1662 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1663 // be a locally scoped record.
1664
Sebastian Redl410c4f22010-08-31 20:53:31 +00001665 // We skip out of inline namespaces. The innermost non-inline namespace
1666 // contains all names of all its nested inline namespaces anyway, so we can
1667 // replace the entire inline namespace tree with its root.
1668 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1669 Ctx->isInlineNamespace())
Douglas Gregor54022952010-04-30 07:08:38 +00001670 Ctx = Ctx->getParent();
1671
John McCall6ff07852009-08-07 22:18:02 +00001672 if (Ctx->isFileContext())
Douglas Gregor54022952010-04-30 07:08:38 +00001673 Namespaces.insert(Ctx->getPrimaryContext());
John McCall6ff07852009-08-07 22:18:02 +00001674}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001675
Mike Stump1eb44332009-09-09 15:08:12 +00001676// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001677// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001678static void
John McCallc7e04da2010-05-28 18:45:08 +00001679addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1680 const TemplateArgument &Arg) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001681 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001682 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001683 switch (Arg.getKind()) {
1684 case TemplateArgument::Null:
1685 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Douglas Gregor69be8d62009-07-08 07:51:57 +00001687 case TemplateArgument::Type:
1688 // [...] the namespaces and classes associated with the types of the
1689 // template arguments provided for template type parameters (excluding
1690 // template template parameters)
John McCallc7e04da2010-05-28 18:45:08 +00001691 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
Douglas Gregor69be8d62009-07-08 07:51:57 +00001692 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Douglas Gregor788cd062009-11-11 01:00:40 +00001694 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001695 // [...] the namespaces in which any template template arguments are
1696 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001697 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001698 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001699 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001700 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001701 DeclContext *Ctx = ClassTemplate->getDeclContext();
1702 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001703 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001704 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001705 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001706 }
1707 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001708 }
1709
1710 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001711 case TemplateArgument::Integral:
1712 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001713 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001714 // associated namespaces. ]
1715 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Douglas Gregor69be8d62009-07-08 07:51:57 +00001717 case TemplateArgument::Pack:
1718 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1719 PEnd = Arg.pack_end();
1720 P != PEnd; ++P)
John McCallc7e04da2010-05-28 18:45:08 +00001721 addAssociatedClassesAndNamespaces(Result, *P);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001722 break;
1723 }
1724}
1725
Douglas Gregorfa047642009-02-04 00:32:51 +00001726// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001727// argument-dependent lookup with an argument of class type
1728// (C++ [basic.lookup.koenig]p2).
1729static void
John McCallc7e04da2010-05-28 18:45:08 +00001730addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1731 CXXRecordDecl *Class) {
1732
1733 // Just silently ignore anything whose name is __va_list_tag.
1734 if (Class->getDeclName() == Result.S.VAListTagName)
1735 return;
1736
Douglas Gregorfa047642009-02-04 00:32:51 +00001737 // C++ [basic.lookup.koenig]p2:
1738 // [...]
1739 // -- If T is a class type (including unions), its associated
1740 // classes are: the class itself; the class of which it is a
1741 // member, if any; and its direct and indirect base
1742 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001743 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001744
1745 // Add the class of which it is a member, if any.
1746 DeclContext *Ctx = Class->getDeclContext();
1747 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001748 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001749 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001750 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Douglas Gregorfa047642009-02-04 00:32:51 +00001752 // Add the class itself. If we've already seen this class, we don't
1753 // need to visit base classes.
John McCallc7e04da2010-05-28 18:45:08 +00001754 if (!Result.Classes.insert(Class))
Douglas Gregorfa047642009-02-04 00:32:51 +00001755 return;
1756
Mike Stump1eb44332009-09-09 15:08:12 +00001757 // -- If T is a template-id, its associated namespaces and classes are
1758 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001759 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001760 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001761 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001762 // namespaces in which any template template arguments are defined; and
1763 // the classes in which any member templates used as template template
1764 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001765 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001766 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001767 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1768 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1769 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001770 Result.Classes.insert(EnclosingClass);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001771 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001772 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Douglas Gregor69be8d62009-07-08 07:51:57 +00001774 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1775 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
John McCallc7e04da2010-05-28 18:45:08 +00001776 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001777 }
Mike Stump1eb44332009-09-09 15:08:12 +00001778
John McCall86ff3082010-02-04 22:26:26 +00001779 // Only recurse into base classes for complete types.
1780 if (!Class->hasDefinition()) {
1781 // FIXME: we might need to instantiate templates here
1782 return;
1783 }
1784
Douglas Gregorfa047642009-02-04 00:32:51 +00001785 // Add direct and indirect base classes along with their associated
1786 // namespaces.
1787 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1788 Bases.push_back(Class);
1789 while (!Bases.empty()) {
1790 // Pop this class off the stack.
1791 Class = Bases.back();
1792 Bases.pop_back();
1793
1794 // Visit the base classes.
1795 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1796 BaseEnd = Class->bases_end();
1797 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001798 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001799 // In dependent contexts, we do ADL twice, and the first time around,
1800 // the base type might be a dependent TemplateSpecializationType, or a
1801 // TemplateTypeParmType. If that happens, simply ignore it.
1802 // FIXME: If we want to support export, we probably need to add the
1803 // namespace of the template in a TemplateSpecializationType, or even
1804 // the classes and namespaces of known non-dependent arguments.
1805 if (!BaseType)
1806 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001807 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001808 if (Result.Classes.insert(BaseDecl)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001809 // Find the associated namespace for this base class.
1810 DeclContext *BaseCtx = BaseDecl->getDeclContext();
John McCallc7e04da2010-05-28 18:45:08 +00001811 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001812
1813 // Make sure we visit the bases of this base class.
1814 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1815 Bases.push_back(BaseDecl);
1816 }
1817 }
1818 }
1819}
1820
1821// \brief Add the associated classes and namespaces for
1822// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001823// (C++ [basic.lookup.koenig]p2).
1824static void
John McCallc7e04da2010-05-28 18:45:08 +00001825addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001826 // C++ [basic.lookup.koenig]p2:
1827 //
1828 // For each argument type T in the function call, there is a set
1829 // of zero or more associated namespaces and a set of zero or more
1830 // associated classes to be considered. The sets of namespaces and
1831 // classes is determined entirely by the types of the function
1832 // arguments (and the namespace of any template template
1833 // argument). Typedef names and using-declarations used to specify
1834 // the types do not contribute to this set. The sets of namespaces
1835 // and classes are determined in the following way:
Douglas Gregorfa047642009-02-04 00:32:51 +00001836
John McCallfa4edcf2010-05-28 06:08:54 +00001837 llvm::SmallVector<const Type *, 16> Queue;
1838 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1839
Douglas Gregorfa047642009-02-04 00:32:51 +00001840 while (true) {
John McCallfa4edcf2010-05-28 06:08:54 +00001841 switch (T->getTypeClass()) {
1842
1843#define TYPE(Class, Base)
1844#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1845#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1846#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1847#define ABSTRACT_TYPE(Class, Base)
1848#include "clang/AST/TypeNodes.def"
1849 // T is canonical. We can also ignore dependent types because
1850 // we don't need to do ADL at the definition point, but if we
1851 // wanted to implement template export (or if we find some other
1852 // use for associated classes and namespaces...) this would be
1853 // wrong.
Douglas Gregorfa047642009-02-04 00:32:51 +00001854 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001855
John McCallfa4edcf2010-05-28 06:08:54 +00001856 // -- If T is a pointer to U or an array of U, its associated
1857 // namespaces and classes are those associated with U.
1858 case Type::Pointer:
1859 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1860 continue;
1861 case Type::ConstantArray:
1862 case Type::IncompleteArray:
1863 case Type::VariableArray:
1864 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1865 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001866
John McCallfa4edcf2010-05-28 06:08:54 +00001867 // -- If T is a fundamental type, its associated sets of
1868 // namespaces and classes are both empty.
1869 case Type::Builtin:
1870 break;
1871
1872 // -- If T is a class type (including unions), its associated
1873 // classes are: the class itself; the class of which it is a
1874 // member, if any; and its direct and indirect base
1875 // classes. Its associated namespaces are the namespaces in
1876 // which its associated classes are defined.
1877 case Type::Record: {
1878 CXXRecordDecl *Class
1879 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
John McCallc7e04da2010-05-28 18:45:08 +00001880 addAssociatedClassesAndNamespaces(Result, Class);
John McCallfa4edcf2010-05-28 06:08:54 +00001881 break;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001882 }
Douglas Gregor4e58c252010-05-20 02:26:51 +00001883
John McCallfa4edcf2010-05-28 06:08:54 +00001884 // -- If T is an enumeration type, its associated namespace is
1885 // the namespace in which it is defined. If it is class
1886 // member, its associated class is the member’s class; else
1887 // it has no associated class.
1888 case Type::Enum: {
1889 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001890
John McCallfa4edcf2010-05-28 06:08:54 +00001891 DeclContext *Ctx = Enum->getDeclContext();
1892 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
John McCallc7e04da2010-05-28 18:45:08 +00001893 Result.Classes.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001894
John McCallfa4edcf2010-05-28 06:08:54 +00001895 // Add the associated namespace for this class.
John McCallc7e04da2010-05-28 18:45:08 +00001896 CollectEnclosingNamespace(Result.Namespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001897
John McCallfa4edcf2010-05-28 06:08:54 +00001898 break;
1899 }
1900
1901 // -- If T is a function type, its associated namespaces and
1902 // classes are those associated with the function parameter
1903 // types and those associated with the return type.
1904 case Type::FunctionProto: {
1905 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1906 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1907 ArgEnd = Proto->arg_type_end();
1908 Arg != ArgEnd; ++Arg)
1909 Queue.push_back(Arg->getTypePtr());
1910 // fallthrough
1911 }
1912 case Type::FunctionNoProto: {
1913 const FunctionType *FnType = cast<FunctionType>(T);
1914 T = FnType->getResultType().getTypePtr();
1915 continue;
1916 }
1917
1918 // -- If T is a pointer to a member function of a class X, its
1919 // associated namespaces and classes are those associated
1920 // with the function parameter types and return type,
1921 // together with those associated with X.
1922 //
1923 // -- If T is a pointer to a data member of class X, its
1924 // associated namespaces and classes are those associated
1925 // with the member type together with those associated with
1926 // X.
1927 case Type::MemberPointer: {
1928 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1929
1930 // Queue up the class type into which this points.
1931 Queue.push_back(MemberPtr->getClass());
1932
1933 // And directly continue with the pointee type.
1934 T = MemberPtr->getPointeeType().getTypePtr();
1935 continue;
1936 }
1937
1938 // As an extension, treat this like a normal pointer.
1939 case Type::BlockPointer:
1940 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1941 continue;
1942
1943 // References aren't covered by the standard, but that's such an
1944 // obvious defect that we cover them anyway.
1945 case Type::LValueReference:
1946 case Type::RValueReference:
1947 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1948 continue;
1949
1950 // These are fundamental types.
1951 case Type::Vector:
1952 case Type::ExtVector:
1953 case Type::Complex:
1954 break;
1955
1956 // These are ignored by ADL.
1957 case Type::ObjCObject:
1958 case Type::ObjCInterface:
1959 case Type::ObjCObjectPointer:
1960 break;
1961 }
1962
1963 if (Queue.empty()) break;
1964 T = Queue.back();
1965 Queue.pop_back();
Douglas Gregorfa047642009-02-04 00:32:51 +00001966 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001967}
1968
1969/// \brief Find the associated classes and namespaces for
1970/// argument-dependent lookup for a call with the given set of
1971/// arguments.
1972///
1973/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001974/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001975/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001976void
Douglas Gregorfa047642009-02-04 00:32:51 +00001977Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1978 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001979 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001980 AssociatedNamespaces.clear();
1981 AssociatedClasses.clear();
1982
John McCallc7e04da2010-05-28 18:45:08 +00001983 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1984
Douglas Gregorfa047642009-02-04 00:32:51 +00001985 // C++ [basic.lookup.koenig]p2:
1986 // For each argument type T in the function call, there is a set
1987 // of zero or more associated namespaces and a set of zero or more
1988 // associated classes to be considered. The sets of namespaces and
1989 // classes is determined entirely by the types of the function
1990 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001991 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001992 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1993 Expr *Arg = Args[ArgIdx];
1994
1995 if (Arg->getType() != Context.OverloadTy) {
John McCallc7e04da2010-05-28 18:45:08 +00001996 addAssociatedClassesAndNamespaces(Result, Arg->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00001997 continue;
1998 }
1999
2000 // [...] In addition, if the argument is the name or address of a
2001 // set of overloaded functions and/or function templates, its
2002 // associated classes and namespaces are the union of those
2003 // associated with each of the members of the set: the namespace
2004 // in which the function or function template is defined and the
2005 // classes and namespaces associated with its (non-dependent)
2006 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00002007 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00002008 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
John McCall2de56d12010-08-25 11:45:40 +00002009 if (unaryOp->getOpcode() == UO_AddrOf)
John McCallba135432009-11-21 08:51:07 +00002010 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002011
John McCallc7e04da2010-05-28 18:45:08 +00002012 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2013 if (!ULE) continue;
John McCallba135432009-11-21 08:51:07 +00002014
John McCallc7e04da2010-05-28 18:45:08 +00002015 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2016 I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00002017 // Look through any using declarations to find the underlying function.
2018 NamedDecl *Fn = (*I)->getUnderlyingDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002019
Chandler Carruthbd647292009-12-29 06:17:27 +00002020 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2021 if (!FDecl)
2022 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00002023
2024 // Add the classes and namespaces associated with the parameter
2025 // types and return type of this function.
John McCallc7e04da2010-05-28 18:45:08 +00002026 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
Douglas Gregorfa047642009-02-04 00:32:51 +00002027 }
2028 }
2029}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002030
2031/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2032/// an acceptable non-member overloaded operator for a call whose
2033/// arguments have types T1 (and, if non-empty, T2). This routine
2034/// implements the check in C++ [over.match.oper]p3b2 concerning
2035/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00002036static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002037IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2038 QualType T1, QualType T2,
2039 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00002040 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2041 return true;
2042
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002043 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2044 return true;
2045
John McCall183700f2009-09-21 23:43:11 +00002046 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002047 if (Proto->getNumArgs() < 1)
2048 return false;
2049
2050 if (T1->isEnumeralType()) {
2051 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002052 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002053 return true;
2054 }
2055
2056 if (Proto->getNumArgs() < 2)
2057 return false;
2058
2059 if (!T2.isNull() && T2->isEnumeralType()) {
2060 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00002061 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002062 return true;
2063 }
2064
2065 return false;
2066}
2067
John McCall7d384dd2009-11-18 07:57:50 +00002068NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
Douglas Gregorc83c6872010-04-15 22:33:43 +00002069 SourceLocation Loc,
John McCall7d384dd2009-11-18 07:57:50 +00002070 LookupNameKind NameKind,
2071 RedeclarationKind Redecl) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00002072 LookupResult R(*this, Name, Loc, NameKind, Redecl);
John McCall7d384dd2009-11-18 07:57:50 +00002073 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00002074 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00002075}
2076
Douglas Gregor6e378de2009-04-23 23:18:26 +00002077/// \brief Find the protocol with the given name, if any.
Douglas Gregorc83c6872010-04-15 22:33:43 +00002078ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2079 SourceLocation IdLoc) {
2080 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2081 LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00002082 return cast_or_null<ObjCProtocolDecl>(D);
2083}
2084
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002085void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00002086 QualType T1, QualType T2,
John McCall6e266892010-01-26 03:27:55 +00002087 UnresolvedSetImpl &Functions) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002088 // C++ [over.match.oper]p3:
2089 // -- The set of non-member candidates is the result of the
2090 // unqualified lookup of operator@ in the context of the
2091 // expression according to the usual rules for name lookup in
2092 // unqualified function calls (3.4.2) except that all member
2093 // functions are ignored. However, if no operand has a class
2094 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00002095 // that have a first parameter of type T1 or "reference to
2096 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002097 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00002098 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002099 // when T2 is an enumeration type, are candidate functions.
2100 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00002101 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2102 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002104 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2105
John McCallf36e02d2009-10-09 21:13:30 +00002106 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002107 return;
2108
2109 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2110 Op != OpEnd; ++Op) {
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002111 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2112 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002113 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002114 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00002115 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002116 = dyn_cast<FunctionTemplateDecl>(Found)) {
Douglas Gregor364e0212009-06-27 21:05:07 +00002117 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00002118 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00002119 // later?
2120 if (!FunTmpl->getDeclContext()->isRecord())
Douglas Gregor6bf356f2010-04-25 20:25:43 +00002121 Functions.addDecl(*Op, Op.getAccess());
Douglas Gregor364e0212009-06-27 21:05:07 +00002122 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002123 }
2124}
2125
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002126/// \brief Look up the constructors for the given class.
2127DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
Douglas Gregor22584312010-07-02 23:41:54 +00002128 // If the copy constructor has not yet been declared, do so now.
Douglas Gregor18274032010-07-03 00:47:00 +00002129 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2130 if (!Class->hasDeclaredDefaultConstructor())
2131 DeclareImplicitDefaultConstructor(Class);
2132 if (!Class->hasDeclaredCopyConstructor())
2133 DeclareImplicitCopyConstructor(Class);
2134 }
Douglas Gregor22584312010-07-02 23:41:54 +00002135
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002136 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2137 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2138 return Class->lookup(Name);
2139}
2140
Douglas Gregordb89f282010-07-01 22:47:18 +00002141/// \brief Look for the destructor of the given class.
2142///
2143/// During semantic analysis, this routine should be used in lieu of
2144/// CXXRecordDecl::getDestructor().
2145///
2146/// \returns The destructor for this class.
2147CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
Douglas Gregor4923aa22010-07-02 20:37:36 +00002148 // If the destructor has not yet been declared, do so now.
2149 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2150 !Class->hasDeclaredDestructor())
2151 DeclareImplicitDestructor(Class);
2152
Douglas Gregordb89f282010-07-01 22:47:18 +00002153 return Class->getDestructor();
2154}
2155
John McCall7edb5fd2010-01-26 07:16:45 +00002156void ADLResult::insert(NamedDecl *New) {
2157 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2158
2159 // If we haven't yet seen a decl for this key, or the last decl
2160 // was exactly this one, we're done.
2161 if (Old == 0 || Old == New) {
2162 Old = New;
2163 return;
2164 }
2165
2166 // Otherwise, decide which is a more recent redeclaration.
2167 FunctionDecl *OldFD, *NewFD;
2168 if (isa<FunctionTemplateDecl>(New)) {
2169 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2170 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2171 } else {
2172 OldFD = cast<FunctionDecl>(Old);
2173 NewFD = cast<FunctionDecl>(New);
2174 }
2175
2176 FunctionDecl *Cursor = NewFD;
2177 while (true) {
2178 Cursor = Cursor->getPreviousDeclaration();
2179
2180 // If we got to the end without finding OldFD, OldFD is the newer
2181 // declaration; leave things as they are.
2182 if (!Cursor) return;
2183
2184 // If we do find OldFD, then NewFD is newer.
2185 if (Cursor == OldFD) break;
2186
2187 // Otherwise, keep looking.
2188 }
2189
2190 Old = New;
2191}
2192
Sebastian Redl644be852009-10-23 19:23:15 +00002193void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002194 Expr **Args, unsigned NumArgs,
John McCall7edb5fd2010-01-26 07:16:45 +00002195 ADLResult &Result) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002196 // Find all of the associated namespaces and classes based on the
2197 // arguments we have.
2198 AssociatedNamespaceSet AssociatedNamespaces;
2199 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00002200 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00002201 AssociatedNamespaces,
2202 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002203
Sebastian Redl644be852009-10-23 19:23:15 +00002204 QualType T1, T2;
2205 if (Operator) {
2206 T1 = Args[0]->getType();
2207 if (NumArgs >= 2)
2208 T2 = Args[1]->getType();
2209 }
2210
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002211 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002212 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2213 // and let Y be the lookup set produced by argument dependent
2214 // lookup (defined as follows). If X contains [...] then Y is
2215 // empty. Otherwise Y is the set of declarations found in the
2216 // namespaces associated with the argument types as described
2217 // below. The set of declarations found by the lookup of the name
2218 // is the union of X and Y.
2219 //
2220 // Here, we compute Y and add its members to the overloaded
2221 // candidate set.
2222 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002223 NSEnd = AssociatedNamespaces.end();
2224 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002225 // When considering an associated namespace, the lookup is the
2226 // same as the lookup performed when the associated namespace is
2227 // used as a qualifier (3.4.3.2) except that:
2228 //
2229 // -- Any using-directives in the associated namespace are
2230 // ignored.
2231 //
John McCall6ff07852009-08-07 22:18:02 +00002232 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002233 // associated classes are visible within their respective
2234 // namespaces even if they are not visible during an ordinary
2235 // lookup (11.4).
2236 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00002237 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00002238 NamedDecl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00002239 // If the only declaration here is an ordinary friend, consider
2240 // it only if it was declared in an associated classes.
2241 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00002242 DeclContext *LexDC = D->getLexicalDeclContext();
2243 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2244 continue;
2245 }
Mike Stump1eb44332009-09-09 15:08:12 +00002246
John McCalla113e722010-01-26 06:04:06 +00002247 if (isa<UsingShadowDecl>(D))
2248 D = cast<UsingShadowDecl>(D)->getTargetDecl();
John McCall6e266892010-01-26 03:27:55 +00002249
John McCalla113e722010-01-26 06:04:06 +00002250 if (isa<FunctionDecl>(D)) {
2251 if (Operator &&
2252 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2253 T1, T2, Context))
2254 continue;
John McCall7edb5fd2010-01-26 07:16:45 +00002255 } else if (!isa<FunctionTemplateDecl>(D))
2256 continue;
2257
2258 Result.insert(D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00002259 }
2260 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00002261}
Douglas Gregor546be3c2009-12-30 17:04:44 +00002262
2263//----------------------------------------------------------------------------
2264// Search for all visible declarations.
2265//----------------------------------------------------------------------------
2266VisibleDeclConsumer::~VisibleDeclConsumer() { }
2267
2268namespace {
2269
2270class ShadowContextRAII;
2271
2272class VisibleDeclsRecord {
2273public:
2274 /// \brief An entry in the shadow map, which is optimized to store a
2275 /// single declaration (the common case) but can also store a list
2276 /// of declarations.
2277 class ShadowMapEntry {
2278 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2279
2280 /// \brief Contains either the solitary NamedDecl * or a vector
2281 /// of declarations.
2282 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2283
2284 public:
2285 ShadowMapEntry() : DeclOrVector() { }
2286
2287 void Add(NamedDecl *ND);
2288 void Destroy();
2289
2290 // Iteration.
2291 typedef NamedDecl **iterator;
2292 iterator begin();
2293 iterator end();
2294 };
2295
2296private:
2297 /// \brief A mapping from declaration names to the declarations that have
2298 /// this name within a particular scope.
2299 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2300
2301 /// \brief A list of shadow maps, which is used to model name hiding.
2302 std::list<ShadowMap> ShadowMaps;
2303
2304 /// \brief The declaration contexts we have already visited.
2305 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2306
2307 friend class ShadowContextRAII;
2308
2309public:
2310 /// \brief Determine whether we have already visited this context
2311 /// (and, if not, note that we are going to visit that context now).
2312 bool visitedContext(DeclContext *Ctx) {
2313 return !VisitedContexts.insert(Ctx);
2314 }
2315
Douglas Gregor8071e422010-08-15 06:18:01 +00002316 bool alreadyVisitedContext(DeclContext *Ctx) {
2317 return VisitedContexts.count(Ctx);
2318 }
2319
Douglas Gregor546be3c2009-12-30 17:04:44 +00002320 /// \brief Determine whether the given declaration is hidden in the
2321 /// current scope.
2322 ///
2323 /// \returns the declaration that hides the given declaration, or
2324 /// NULL if no such declaration exists.
2325 NamedDecl *checkHidden(NamedDecl *ND);
2326
2327 /// \brief Add a declaration to the current shadow map.
2328 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2329};
2330
2331/// \brief RAII object that records when we've entered a shadow context.
2332class ShadowContextRAII {
2333 VisibleDeclsRecord &Visible;
2334
2335 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2336
2337public:
2338 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2339 Visible.ShadowMaps.push_back(ShadowMap());
2340 }
2341
2342 ~ShadowContextRAII() {
2343 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2344 EEnd = Visible.ShadowMaps.back().end();
2345 E != EEnd;
2346 ++E)
2347 E->second.Destroy();
2348
2349 Visible.ShadowMaps.pop_back();
2350 }
2351};
2352
2353} // end anonymous namespace
2354
2355void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2356 if (DeclOrVector.isNull()) {
2357 // 0 - > 1 elements: just set the single element information.
2358 DeclOrVector = ND;
2359 return;
2360 }
2361
2362 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2363 // 1 -> 2 elements: create the vector of results and push in the
2364 // existing declaration.
2365 DeclVector *Vec = new DeclVector;
2366 Vec->push_back(PrevND);
2367 DeclOrVector = Vec;
2368 }
2369
2370 // Add the new element to the end of the vector.
2371 DeclOrVector.get<DeclVector*>()->push_back(ND);
2372}
2373
2374void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2375 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2376 delete Vec;
2377 DeclOrVector = ((NamedDecl *)0);
2378 }
2379}
2380
2381VisibleDeclsRecord::ShadowMapEntry::iterator
2382VisibleDeclsRecord::ShadowMapEntry::begin() {
2383 if (DeclOrVector.isNull())
2384 return 0;
2385
2386 if (DeclOrVector.dyn_cast<NamedDecl *>())
2387 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2388
2389 return DeclOrVector.get<DeclVector *>()->begin();
2390}
2391
2392VisibleDeclsRecord::ShadowMapEntry::iterator
2393VisibleDeclsRecord::ShadowMapEntry::end() {
2394 if (DeclOrVector.isNull())
2395 return 0;
2396
2397 if (DeclOrVector.dyn_cast<NamedDecl *>())
2398 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2399
2400 return DeclOrVector.get<DeclVector *>()->end();
2401}
2402
2403NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
Douglas Gregorefcf16d2010-01-14 00:06:47 +00002404 // Look through using declarations.
2405 ND = ND->getUnderlyingDecl();
2406
Douglas Gregor546be3c2009-12-30 17:04:44 +00002407 unsigned IDNS = ND->getIdentifierNamespace();
2408 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2409 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2410 SM != SMEnd; ++SM) {
2411 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2412 if (Pos == SM->end())
2413 continue;
2414
2415 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2416 IEnd = Pos->second.end();
2417 I != IEnd; ++I) {
2418 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +00002419 if ((*I)->hasTagIdentifierNamespace() &&
Douglas Gregor546be3c2009-12-30 17:04:44 +00002420 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2421 Decl::IDNS_ObjCProtocol)))
2422 continue;
2423
2424 // Protocols are in distinct namespaces from everything else.
2425 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2426 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2427 (*I)->getIdentifierNamespace() != IDNS)
2428 continue;
2429
Douglas Gregor0cc84042010-01-14 15:47:35 +00002430 // Functions and function templates in the same scope overload
2431 // rather than hide. FIXME: Look for hiding based on function
2432 // signatures!
Douglas Gregordef91072010-01-14 03:35:48 +00002433 if ((*I)->isFunctionOrFunctionTemplate() &&
Douglas Gregor0cc84042010-01-14 15:47:35 +00002434 ND->isFunctionOrFunctionTemplate() &&
2435 SM == ShadowMaps.rbegin())
Douglas Gregordef91072010-01-14 03:35:48 +00002436 continue;
2437
Douglas Gregor546be3c2009-12-30 17:04:44 +00002438 // We've found a declaration that hides this one.
2439 return *I;
2440 }
2441 }
2442
2443 return 0;
2444}
2445
2446static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2447 bool QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002448 bool InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002449 VisibleDeclConsumer &Consumer,
2450 VisibleDeclsRecord &Visited) {
Douglas Gregor62021192010-02-04 23:42:48 +00002451 if (!Ctx)
2452 return;
2453
Douglas Gregor546be3c2009-12-30 17:04:44 +00002454 // Make sure we don't visit the same context twice.
2455 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2456 return;
2457
Douglas Gregor4923aa22010-07-02 20:37:36 +00002458 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2459 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2460
Douglas Gregor546be3c2009-12-30 17:04:44 +00002461 // Enumerate all of the results in this context.
2462 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2463 CurCtx = CurCtx->getNextContext()) {
2464 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2465 DEnd = CurCtx->decls_end();
2466 D != DEnd; ++D) {
Douglas Gregor70c23352010-12-09 21:44:02 +00002467 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002468 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002469 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002470 Visited.add(ND);
2471 }
Douglas Gregor70c23352010-12-09 21:44:02 +00002472 } else if (ObjCForwardProtocolDecl *ForwardProto
2473 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2474 for (ObjCForwardProtocolDecl::protocol_iterator
2475 P = ForwardProto->protocol_begin(),
2476 PEnd = ForwardProto->protocol_end();
2477 P != PEnd;
2478 ++P) {
2479 if (Result.isAcceptableDecl(*P)) {
2480 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2481 Visited.add(*P);
2482 }
2483 }
2484 }
Sebastian Redl410c4f22010-08-31 20:53:31 +00002485 // Visit transparent contexts and inline namespaces inside this context.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002486 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
Sebastian Redl410c4f22010-08-31 20:53:31 +00002487 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Douglas Gregor0cc84042010-01-14 15:47:35 +00002488 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
Douglas Gregor546be3c2009-12-30 17:04:44 +00002489 Consumer, Visited);
2490 }
2491 }
2492 }
2493
2494 // Traverse using directives for qualified name lookup.
2495 if (QualifiedNameLookup) {
2496 ShadowContextRAII Shadow(Visited);
2497 DeclContext::udir_iterator I, E;
2498 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2499 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002500 QualifiedNameLookup, InBaseClass, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002501 }
2502 }
2503
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002504 // Traverse the contexts of inherited C++ classes.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002505 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
John McCall86ff3082010-02-04 22:26:26 +00002506 if (!Record->hasDefinition())
2507 return;
2508
Douglas Gregor546be3c2009-12-30 17:04:44 +00002509 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2510 BEnd = Record->bases_end();
2511 B != BEnd; ++B) {
2512 QualType BaseType = B->getType();
2513
2514 // Don't look into dependent bases, because name lookup can't look
2515 // there anyway.
2516 if (BaseType->isDependentType())
2517 continue;
2518
2519 const RecordType *Record = BaseType->getAs<RecordType>();
2520 if (!Record)
2521 continue;
2522
2523 // FIXME: It would be nice to be able to determine whether referencing
2524 // a particular member would be ambiguous. For example, given
2525 //
2526 // struct A { int member; };
2527 // struct B { int member; };
2528 // struct C : A, B { };
2529 //
2530 // void f(C *c) { c->### }
2531 //
2532 // accessing 'member' would result in an ambiguity. However, we
2533 // could be smart enough to qualify the member with the base
2534 // class, e.g.,
2535 //
2536 // c->B::member
2537 //
2538 // or
2539 //
2540 // c->A::member
2541
2542 // Find results in this base class (and its bases).
2543 ShadowContextRAII Shadow(Visited);
2544 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002545 true, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002546 }
2547 }
2548
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002549 // Traverse the contexts of Objective-C classes.
2550 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2551 // Traverse categories.
2552 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2553 Category; Category = Category->getNextClassCategory()) {
2554 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002555 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2556 Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002557 }
2558
2559 // Traverse protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00002560 for (ObjCInterfaceDecl::all_protocol_iterator
2561 I = IFace->all_referenced_protocol_begin(),
2562 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002563 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002564 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2565 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002566 }
2567
2568 // Traverse the superclass.
2569 if (IFace->getSuperClass()) {
2570 ShadowContextRAII Shadow(Visited);
2571 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002572 true, Consumer, Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002573 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002574
2575 // If there is an implementation, traverse it. We do this to find
2576 // synthesized ivars.
2577 if (IFace->getImplementation()) {
2578 ShadowContextRAII Shadow(Visited);
2579 LookupVisibleDecls(IFace->getImplementation(), Result,
2580 QualifiedNameLookup, true, Consumer, Visited);
2581 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002582 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2583 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2584 E = Protocol->protocol_end(); I != E; ++I) {
2585 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002586 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2587 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002588 }
2589 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2590 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2591 E = Category->protocol_end(); I != E; ++I) {
2592 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002593 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2594 Visited);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002595 }
Douglas Gregorc220a182010-04-19 18:02:19 +00002596
2597 // If there is an implementation, traverse it.
2598 if (Category->getImplementation()) {
2599 ShadowContextRAII Shadow(Visited);
2600 LookupVisibleDecls(Category->getImplementation(), Result,
2601 QualifiedNameLookup, true, Consumer, Visited);
2602 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002603 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002604}
2605
2606static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2607 UnqualUsingDirectiveSet &UDirs,
2608 VisibleDeclConsumer &Consumer,
2609 VisibleDeclsRecord &Visited) {
2610 if (!S)
2611 return;
2612
Douglas Gregor8071e422010-08-15 06:18:01 +00002613 if (!S->getEntity() ||
2614 (!S->getParent() &&
2615 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
Douglas Gregor539c5c32010-01-07 00:31:29 +00002616 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2617 // Walk through the declarations in this Scope.
2618 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2619 D != DEnd; ++D) {
John McCalld226f652010-08-21 09:40:31 +00002620 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor539c5c32010-01-07 00:31:29 +00002621 if (Result.isAcceptableDecl(ND)) {
Douglas Gregor0cc84042010-01-14 15:47:35 +00002622 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002623 Visited.add(ND);
2624 }
2625 }
2626 }
2627
Douglas Gregor711be1e2010-03-15 14:33:29 +00002628 // FIXME: C++ [temp.local]p8
Douglas Gregor546be3c2009-12-30 17:04:44 +00002629 DeclContext *Entity = 0;
Douglas Gregore3582012010-01-01 17:44:25 +00002630 if (S->getEntity()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002631 // Look into this scope's declaration context, along with any of its
2632 // parent lookup contexts (e.g., enclosing classes), up to the point
2633 // where we hit the context stored in the next outer scope.
2634 Entity = (DeclContext *)S->getEntity();
Douglas Gregor711be1e2010-03-15 14:33:29 +00002635 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
Douglas Gregor546be3c2009-12-30 17:04:44 +00002636
Douglas Gregordbdf5e72010-03-15 15:26:48 +00002637 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002638 Ctx = Ctx->getLookupParent()) {
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002639 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2640 if (Method->isInstanceMethod()) {
2641 // For instance methods, look for ivars in the method's interface.
2642 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2643 Result.getNameLoc(), Sema::LookupMemberName);
Douglas Gregorca45da02010-11-02 20:36:02 +00002644 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
Douglas Gregor62021192010-02-04 23:42:48 +00002645 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2646 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregorca45da02010-11-02 20:36:02 +00002647
2648 // Look for properties from which we can synthesize ivars, if
2649 // permitted.
2650 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2651 IFace->getImplementation() &&
2652 Result.getLookupKind() == Sema::LookupOrdinaryName) {
2653 for (ObjCInterfaceDecl::prop_iterator
2654 P = IFace->prop_begin(),
2655 PEnd = IFace->prop_end();
2656 P != PEnd; ++P) {
2657 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2658 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2659 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2660 Visited.add(*P);
2661 }
2662 }
2663 }
2664 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002665 }
2666
2667 // We've already performed all of the name lookup that we need
2668 // to for Objective-C methods; the next context will be the
2669 // outer scope.
2670 break;
2671 }
2672
Douglas Gregor546be3c2009-12-30 17:04:44 +00002673 if (Ctx->isFunctionOrMethod())
2674 continue;
2675
2676 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002677 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002678 }
2679 } else if (!S->getParent()) {
2680 // Look into the translation unit scope. We walk through the translation
2681 // unit's declaration context, because the Scope itself won't have all of
2682 // the declarations if we loaded a precompiled header.
2683 // FIXME: We would like the translation unit's Scope object to point to the
2684 // translation unit, so we don't need this special "if" branch. However,
2685 // doing so would force the normal C++ name-lookup code to look into the
2686 // translation unit decl when the IdentifierInfo chains would suffice.
2687 // Once we fix that problem (which is part of a more general "don't look
Douglas Gregor539c5c32010-01-07 00:31:29 +00002688 // in DeclContexts unless we have to" optimization), we can eliminate this.
Douglas Gregor546be3c2009-12-30 17:04:44 +00002689 Entity = Result.getSema().Context.getTranslationUnitDecl();
2690 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
Douglas Gregor0cc84042010-01-14 15:47:35 +00002691 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor539c5c32010-01-07 00:31:29 +00002692 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002693
2694 if (Entity) {
2695 // Lookup visible declarations in any namespaces found by using
2696 // directives.
2697 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2698 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2699 for (; UI != UEnd; ++UI)
2700 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
Douglas Gregor0cc84042010-01-14 15:47:35 +00002701 Result, /*QualifiedNameLookup=*/false,
2702 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002703 }
2704
2705 // Lookup names in the parent scope.
2706 ShadowContextRAII Shadow(Visited);
2707 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2708}
2709
2710void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002711 VisibleDeclConsumer &Consumer,
2712 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002713 // Determine the set of using directives available during
2714 // unqualified name lookup.
2715 Scope *Initial = S;
2716 UnqualUsingDirectiveSet UDirs;
2717 if (getLangOptions().CPlusPlus) {
2718 // Find the first namespace or translation-unit scope.
2719 while (S && !isNamespaceOrTranslationUnitScope(S))
2720 S = S->getParent();
2721
2722 UDirs.visitScopeChain(Initial, S);
2723 }
2724 UDirs.done();
2725
2726 // Look for visible declarations.
2727 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2728 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002729 if (!IncludeGlobalScope)
2730 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002731 ShadowContextRAII Shadow(Visited);
2732 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2733}
2734
2735void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
Douglas Gregor8071e422010-08-15 06:18:01 +00002736 VisibleDeclConsumer &Consumer,
2737 bool IncludeGlobalScope) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002738 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2739 VisibleDeclsRecord Visited;
Douglas Gregor8071e422010-08-15 06:18:01 +00002740 if (!IncludeGlobalScope)
2741 Visited.visitedContext(Context.getTranslationUnitDecl());
Douglas Gregor546be3c2009-12-30 17:04:44 +00002742 ShadowContextRAII Shadow(Visited);
Douglas Gregor0cc84042010-01-14 15:47:35 +00002743 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2744 /*InBaseClass=*/false, Consumer, Visited);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002745}
2746
2747//----------------------------------------------------------------------------
2748// Typo correction
2749//----------------------------------------------------------------------------
2750
2751namespace {
2752class TypoCorrectionConsumer : public VisibleDeclConsumer {
2753 /// \brief The name written that is a typo in the source.
2754 llvm::StringRef Typo;
2755
2756 /// \brief The results found that have the smallest edit distance
2757 /// found (so far) with the typo name.
Douglas Gregore24b5752010-10-14 20:34:08 +00002758 ///
2759 /// The boolean value indicates whether there is a keyword with this name.
2760 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
Douglas Gregor546be3c2009-12-30 17:04:44 +00002761
2762 /// \brief The best edit distance found so far.
2763 unsigned BestEditDistance;
2764
2765public:
2766 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
Douglas Gregore24b5752010-10-14 20:34:08 +00002767 : Typo(Typo->getName()),
2768 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002769
Douglas Gregor0cc84042010-01-14 15:47:35 +00002770 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
Douglas Gregor95f42922010-10-14 22:11:03 +00002771 void FoundName(llvm::StringRef Name);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002772 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
Douglas Gregor546be3c2009-12-30 17:04:44 +00002773
Douglas Gregore24b5752010-10-14 20:34:08 +00002774 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2775 iterator begin() { return BestResults.begin(); }
2776 iterator end() { return BestResults.end(); }
2777 void erase(iterator I) { BestResults.erase(I); }
2778 unsigned size() const { return BestResults.size(); }
2779 bool empty() const { return BestResults.empty(); }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002780
Douglas Gregor7b824e82010-10-15 13:35:25 +00002781 bool &operator[](llvm::StringRef Name) {
2782 return BestResults[Name];
2783 }
2784
Douglas Gregoraaf87162010-04-14 20:04:41 +00002785 unsigned getBestEditDistance() const { return BestEditDistance; }
Douglas Gregor546be3c2009-12-30 17:04:44 +00002786};
2787
2788}
2789
Douglas Gregor0cc84042010-01-14 15:47:35 +00002790void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2791 bool InBaseClass) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002792 // Don't consider hidden names for typo correction.
2793 if (Hiding)
2794 return;
2795
2796 // Only consider entities with identifiers for names, ignoring
2797 // special names (constructors, overloaded operators, selectors,
2798 // etc.).
2799 IdentifierInfo *Name = ND->getIdentifier();
2800 if (!Name)
2801 return;
2802
Douglas Gregor95f42922010-10-14 22:11:03 +00002803 FoundName(Name->getName());
2804}
2805
2806void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
Douglas Gregora1194772010-10-19 22:14:33 +00002807 using namespace std;
2808
Douglas Gregor362a8f22010-10-19 19:39:10 +00002809 // Use a simple length-based heuristic to determine the minimum possible
2810 // edit distance. If the minimum isn't good enough, bail out early.
2811 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
2812 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
2813 return;
2814
Douglas Gregora1194772010-10-19 22:14:33 +00002815 // Compute an upper bound on the allowable edit distance, so that the
2816 // edit-distance algorithm can short-circuit.
2817 unsigned UpperBound = min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
2818
Douglas Gregor546be3c2009-12-30 17:04:44 +00002819 // Compute the edit distance between the typo and the name of this
2820 // entity. If this edit distance is not worse than the best edit
2821 // distance we've seen so far, add it to the list of results.
Douglas Gregora1194772010-10-19 22:14:33 +00002822 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
Douglas Gregor95f42922010-10-14 22:11:03 +00002823 if (ED == 0)
2824 return;
2825
Douglas Gregore24b5752010-10-14 20:34:08 +00002826 if (ED < BestEditDistance) {
2827 // This result is better than any we've seen before; clear out
2828 // the previous results.
2829 BestResults.clear();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002830 BestEditDistance = ED;
Douglas Gregore24b5752010-10-14 20:34:08 +00002831 } else if (ED > BestEditDistance) {
2832 // This result is worse than the best results we've seen so far;
2833 // ignore it.
2834 return;
2835 }
Douglas Gregor95f42922010-10-14 22:11:03 +00002836
Douglas Gregore24b5752010-10-14 20:34:08 +00002837 // Add this name to the list of results. By not assigning a value, we
2838 // keep the current value if we've seen this name before (either as a
2839 // keyword or as a declaration), or get the default value (not a keyword)
2840 // if we haven't seen it before.
Douglas Gregor95f42922010-10-14 22:11:03 +00002841 (void)BestResults[Name];
Douglas Gregor546be3c2009-12-30 17:04:44 +00002842}
2843
Douglas Gregoraaf87162010-04-14 20:04:41 +00002844void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2845 llvm::StringRef Keyword) {
2846 // Compute the edit distance between the typo and this keyword.
2847 // If this edit distance is not worse than the best edit
2848 // distance we've seen so far, add it to the list of results.
2849 unsigned ED = Typo.edit_distance(Keyword);
Douglas Gregore24b5752010-10-14 20:34:08 +00002850 if (ED < BestEditDistance) {
2851 BestResults.clear();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002852 BestEditDistance = ED;
Douglas Gregore24b5752010-10-14 20:34:08 +00002853 } else if (ED > BestEditDistance) {
2854 // This result is worse than the best results we've seen so far;
2855 // ignore it.
2856 return;
2857 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00002858
Douglas Gregore24b5752010-10-14 20:34:08 +00002859 BestResults[Keyword] = true;
Douglas Gregoraaf87162010-04-14 20:04:41 +00002860}
2861
Douglas Gregor9a632ea2010-10-20 03:06:34 +00002862/// \brief Perform name lookup for a possible result for typo correction.
2863static void LookupPotentialTypoResult(Sema &SemaRef,
2864 LookupResult &Res,
2865 IdentifierInfo *Name,
2866 Scope *S, CXXScopeSpec *SS,
2867 DeclContext *MemberContext,
2868 bool EnteringContext,
2869 Sema::CorrectTypoContext CTC) {
2870 Res.suppressDiagnostics();
2871 Res.clear();
2872 Res.setLookupName(Name);
2873 if (MemberContext) {
2874 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
2875 if (CTC == Sema::CTC_ObjCIvarLookup) {
2876 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
2877 Res.addDecl(Ivar);
2878 Res.resolveKind();
2879 return;
2880 }
2881 }
2882
2883 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
2884 Res.addDecl(Prop);
2885 Res.resolveKind();
2886 return;
2887 }
2888 }
2889
2890 SemaRef.LookupQualifiedName(Res, MemberContext);
2891 return;
2892 }
2893
2894 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2895 EnteringContext);
2896
2897 // Fake ivar lookup; this should really be part of
2898 // LookupParsedName.
2899 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2900 if (Method->isInstanceMethod() && Method->getClassInterface() &&
2901 (Res.empty() ||
2902 (Res.isSingleResult() &&
2903 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
2904 if (ObjCIvarDecl *IV
2905 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
2906 Res.addDecl(IV);
2907 Res.resolveKind();
2908 }
2909 }
2910 }
2911}
2912
Douglas Gregor546be3c2009-12-30 17:04:44 +00002913/// \brief Try to "correct" a typo in the source code by finding
2914/// visible declarations whose names are similar to the name that was
2915/// present in the source code.
2916///
2917/// \param Res the \c LookupResult structure that contains the name
2918/// that was present in the source code along with the name-lookup
2919/// criteria used to search for the name. On success, this structure
2920/// will contain the results of name lookup.
2921///
2922/// \param S the scope in which name lookup occurs.
2923///
2924/// \param SS the nested-name-specifier that precedes the name we're
2925/// looking for, if present.
2926///
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002927/// \param MemberContext if non-NULL, the context in which to look for
2928/// a member access expression.
2929///
Douglas Gregorbb092ba2009-12-31 05:20:13 +00002930/// \param EnteringContext whether we're entering the context described by
2931/// the nested-name-specifier SS.
2932///
Douglas Gregoraaf87162010-04-14 20:04:41 +00002933/// \param CTC The context in which typo correction occurs, which impacts the
2934/// set of keywords permitted.
2935///
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002936/// \param OPT when non-NULL, the search for visible declarations will
2937/// also walk the protocols in the qualified interfaces of \p OPT.
2938///
Douglas Gregor931f98a2010-04-14 17:09:22 +00002939/// \returns the corrected name if the typo was corrected, otherwise returns an
2940/// empty \c DeclarationName. When a typo was corrected, the result structure
2941/// may contain the results of name lookup for the correct name or it may be
2942/// empty.
2943DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
Douglas Gregoraaf87162010-04-14 20:04:41 +00002944 DeclContext *MemberContext,
2945 bool EnteringContext,
2946 CorrectTypoContext CTC,
2947 const ObjCObjectPointerType *OPT) {
Douglas Gregora0068fc2010-07-09 17:35:33 +00002948 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002949 return DeclarationName();
Ted Kremenek1dac3412010-01-06 00:23:04 +00002950
Douglas Gregor546be3c2009-12-30 17:04:44 +00002951 // We only attempt to correct typos for identifiers.
2952 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2953 if (!Typo)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002954 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002955
2956 // If the scope specifier itself was invalid, don't try to correct
2957 // typos.
2958 if (SS && SS->isInvalid())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002959 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002960
2961 // Never try to correct typos during template deduction or
2962 // instantiation.
2963 if (!ActiveTemplateInstantiations.empty())
Douglas Gregor931f98a2010-04-14 17:09:22 +00002964 return DeclarationName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002965
Douglas Gregor546be3c2009-12-30 17:04:44 +00002966 TypoCorrectionConsumer Consumer(Typo);
Douglas Gregoraaf87162010-04-14 20:04:41 +00002967
2968 // Perform name lookup to find visible, similarly-named entities.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00002969 bool IsUnqualifiedLookup = false;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002970 if (MemberContext) {
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002971 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002972
2973 // Look in qualified interfaces.
2974 if (OPT) {
2975 for (ObjCObjectPointerType::qual_iterator
2976 I = OPT->qual_begin(), E = OPT->qual_end();
2977 I != E; ++I)
2978 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2979 }
2980 } else if (SS && SS->isSet()) {
Douglas Gregor546be3c2009-12-30 17:04:44 +00002981 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2982 if (!DC)
Douglas Gregor931f98a2010-04-14 17:09:22 +00002983 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00002984
Douglas Gregor3eedbb02010-10-20 01:32:02 +00002985 // Provide a stop gap for files that are just seriously broken. Trying
2986 // to correct all typos can turn into a HUGE performance penalty, causing
2987 // some files to take minutes to get rejected by the parser.
2988 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
2989 return DeclarationName();
2990 ++TyposCorrected;
2991
Douglas Gregor546be3c2009-12-30 17:04:44 +00002992 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2993 } else {
Douglas Gregor3eedbb02010-10-20 01:32:02 +00002994 IsUnqualifiedLookup = true;
2995 UnqualifiedTyposCorrectedMap::iterator Cached
2996 = UnqualifiedTyposCorrected.find(Typo);
2997 if (Cached == UnqualifiedTyposCorrected.end()) {
2998 // Provide a stop gap for files that are just seriously broken. Trying
2999 // to correct all typos can turn into a HUGE performance penalty, causing
3000 // some files to take minutes to get rejected by the parser.
3001 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3002 return DeclarationName();
3003
3004 // For unqualified lookup, look through all of the names that we have
3005 // seen in this translation unit.
3006 for (IdentifierTable::iterator I = Context.Idents.begin(),
3007 IEnd = Context.Idents.end();
3008 I != IEnd; ++I)
3009 Consumer.FoundName(I->getKey());
3010
3011 // Walk through identifiers in external identifier sources.
3012 if (IdentifierInfoLookup *External
Douglas Gregor95f42922010-10-14 22:11:03 +00003013 = Context.Idents.getExternalIdentifierLookup()) {
Ted Kremenek7a054b12010-11-07 06:11:33 +00003014 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003015 do {
3016 llvm::StringRef Name = Iter->Next();
3017 if (Name.empty())
3018 break;
Douglas Gregor95f42922010-10-14 22:11:03 +00003019
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003020 Consumer.FoundName(Name);
3021 } while (true);
3022 }
3023 } else {
3024 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3025 // end up adding the keyword below.
3026 if (Cached->second.first.empty())
3027 return DeclarationName();
3028
3029 if (!Cached->second.second)
3030 Consumer.FoundName(Cached->second.first);
Douglas Gregor95f42922010-10-14 22:11:03 +00003031 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003032 }
3033
Douglas Gregoraaf87162010-04-14 20:04:41 +00003034 // Add context-dependent keywords.
3035 bool WantTypeSpecifiers = false;
3036 bool WantExpressionKeywords = false;
3037 bool WantCXXNamedCasts = false;
3038 bool WantRemainingKeywords = false;
3039 switch (CTC) {
3040 case CTC_Unknown:
3041 WantTypeSpecifiers = true;
3042 WantExpressionKeywords = true;
3043 WantCXXNamedCasts = true;
3044 WantRemainingKeywords = true;
Douglas Gregor91f7ac72010-05-18 16:14:23 +00003045
3046 if (ObjCMethodDecl *Method = getCurMethodDecl())
3047 if (Method->getClassInterface() &&
3048 Method->getClassInterface()->getSuperClass())
3049 Consumer.addKeywordResult(Context, "super");
3050
Douglas Gregoraaf87162010-04-14 20:04:41 +00003051 break;
3052
3053 case CTC_NoKeywords:
3054 break;
3055
3056 case CTC_Type:
3057 WantTypeSpecifiers = true;
3058 break;
3059
3060 case CTC_ObjCMessageReceiver:
3061 Consumer.addKeywordResult(Context, "super");
3062 // Fall through to handle message receivers like expressions.
3063
3064 case CTC_Expression:
3065 if (getLangOptions().CPlusPlus)
3066 WantTypeSpecifiers = true;
3067 WantExpressionKeywords = true;
3068 // Fall through to get C++ named casts.
3069
3070 case CTC_CXXCasts:
3071 WantCXXNamedCasts = true;
3072 break;
3073
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003074 case CTC_ObjCPropertyLookup:
3075 // FIXME: Add "isa"?
3076 break;
3077
Douglas Gregoraaf87162010-04-14 20:04:41 +00003078 case CTC_MemberLookup:
3079 if (getLangOptions().CPlusPlus)
3080 Consumer.addKeywordResult(Context, "template");
3081 break;
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003082
3083 case CTC_ObjCIvarLookup:
3084 break;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003085 }
3086
3087 if (WantTypeSpecifiers) {
3088 // Add type-specifier keywords to the set of results.
3089 const char *CTypeSpecs[] = {
3090 "char", "const", "double", "enum", "float", "int", "long", "short",
3091 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3092 "_Complex", "_Imaginary",
3093 // storage-specifiers as well
3094 "extern", "inline", "static", "typedef"
3095 };
3096
3097 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3098 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3099 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
3100
3101 if (getLangOptions().C99)
3102 Consumer.addKeywordResult(Context, "restrict");
3103 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3104 Consumer.addKeywordResult(Context, "bool");
3105
3106 if (getLangOptions().CPlusPlus) {
3107 Consumer.addKeywordResult(Context, "class");
3108 Consumer.addKeywordResult(Context, "typename");
3109 Consumer.addKeywordResult(Context, "wchar_t");
3110
3111 if (getLangOptions().CPlusPlus0x) {
3112 Consumer.addKeywordResult(Context, "char16_t");
3113 Consumer.addKeywordResult(Context, "char32_t");
3114 Consumer.addKeywordResult(Context, "constexpr");
3115 Consumer.addKeywordResult(Context, "decltype");
3116 Consumer.addKeywordResult(Context, "thread_local");
3117 }
3118 }
3119
3120 if (getLangOptions().GNUMode)
3121 Consumer.addKeywordResult(Context, "typeof");
3122 }
3123
Douglas Gregord0785ea2010-05-18 16:30:22 +00003124 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003125 Consumer.addKeywordResult(Context, "const_cast");
3126 Consumer.addKeywordResult(Context, "dynamic_cast");
3127 Consumer.addKeywordResult(Context, "reinterpret_cast");
3128 Consumer.addKeywordResult(Context, "static_cast");
3129 }
3130
3131 if (WantExpressionKeywords) {
3132 Consumer.addKeywordResult(Context, "sizeof");
3133 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3134 Consumer.addKeywordResult(Context, "false");
3135 Consumer.addKeywordResult(Context, "true");
3136 }
3137
3138 if (getLangOptions().CPlusPlus) {
3139 const char *CXXExprs[] = {
3140 "delete", "new", "operator", "throw", "typeid"
3141 };
3142 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3143 for (unsigned I = 0; I != NumCXXExprs; ++I)
3144 Consumer.addKeywordResult(Context, CXXExprs[I]);
3145
3146 if (isa<CXXMethodDecl>(CurContext) &&
3147 cast<CXXMethodDecl>(CurContext)->isInstance())
3148 Consumer.addKeywordResult(Context, "this");
3149
3150 if (getLangOptions().CPlusPlus0x) {
3151 Consumer.addKeywordResult(Context, "alignof");
3152 Consumer.addKeywordResult(Context, "nullptr");
3153 }
3154 }
3155 }
3156
3157 if (WantRemainingKeywords) {
3158 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3159 // Statements.
3160 const char *CStmts[] = {
3161 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3162 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3163 for (unsigned I = 0; I != NumCStmts; ++I)
3164 Consumer.addKeywordResult(Context, CStmts[I]);
3165
3166 if (getLangOptions().CPlusPlus) {
3167 Consumer.addKeywordResult(Context, "catch");
3168 Consumer.addKeywordResult(Context, "try");
3169 }
3170
3171 if (S && S->getBreakParent())
3172 Consumer.addKeywordResult(Context, "break");
3173
3174 if (S && S->getContinueParent())
3175 Consumer.addKeywordResult(Context, "continue");
3176
John McCall781472f2010-08-25 08:40:02 +00003177 if (!getCurFunction()->SwitchStack.empty()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00003178 Consumer.addKeywordResult(Context, "case");
3179 Consumer.addKeywordResult(Context, "default");
3180 }
3181 } else {
3182 if (getLangOptions().CPlusPlus) {
3183 Consumer.addKeywordResult(Context, "namespace");
3184 Consumer.addKeywordResult(Context, "template");
3185 }
3186
3187 if (S && S->isClassScope()) {
3188 Consumer.addKeywordResult(Context, "explicit");
3189 Consumer.addKeywordResult(Context, "friend");
3190 Consumer.addKeywordResult(Context, "mutable");
3191 Consumer.addKeywordResult(Context, "private");
3192 Consumer.addKeywordResult(Context, "protected");
3193 Consumer.addKeywordResult(Context, "public");
3194 Consumer.addKeywordResult(Context, "virtual");
3195 }
3196 }
3197
3198 if (getLangOptions().CPlusPlus) {
3199 Consumer.addKeywordResult(Context, "using");
3200
3201 if (getLangOptions().CPlusPlus0x)
3202 Consumer.addKeywordResult(Context, "static_assert");
3203 }
3204 }
3205
3206 // If we haven't found anything, we're done.
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003207 if (Consumer.empty()) {
3208 // If this was an unqualified lookup, note that no correction was found.
3209 if (IsUnqualifiedLookup)
3210 (void)UnqualifiedTyposCorrected[Typo];
3211
Douglas Gregor931f98a2010-04-14 17:09:22 +00003212 return DeclarationName();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003213 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003214
Douglas Gregore24b5752010-10-14 20:34:08 +00003215 // Make sure that the user typed at least 3 characters for each correction
3216 // made. Otherwise, we don't even both looking at the results.
Douglas Gregor53e4b552010-10-26 17:18:00 +00003217
3218 // We also suppress exact matches; those should be handled by a
3219 // different mechanism (e.g., one that introduces qualification in
3220 // C++).
Douglas Gregore24b5752010-10-14 20:34:08 +00003221 unsigned ED = Consumer.getBestEditDistance();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003222 if (ED > 0 && Typo->getName().size() / ED < 3) {
3223 // If this was an unqualified lookup, note that no correction was found.
Douglas Gregor157a3ff2010-10-27 14:20:34 +00003224 if (IsUnqualifiedLookup)
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003225 (void)UnqualifiedTyposCorrected[Typo];
3226
Douglas Gregore24b5752010-10-14 20:34:08 +00003227 return DeclarationName();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003228 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003229
3230 // Weed out any names that could not be found by name lookup.
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003231 bool LastLookupWasAccepted = false;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003232 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3233 IEnd = Consumer.end();
Douglas Gregore24b5752010-10-14 20:34:08 +00003234 I != IEnd; /* Increment in loop. */) {
3235 // Keywords are always found.
3236 if (I->second) {
3237 ++I;
3238 continue;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003239 }
Douglas Gregore24b5752010-10-14 20:34:08 +00003240
3241 // Perform name lookup on this name.
3242 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003243 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3244 EnteringContext, CTC);
Douglas Gregore24b5752010-10-14 20:34:08 +00003245
3246 switch (Res.getResultKind()) {
3247 case LookupResult::NotFound:
3248 case LookupResult::NotFoundInCurrentInstantiation:
3249 case LookupResult::Ambiguous:
3250 // We didn't find this name in our scope, or didn't like what we found;
3251 // ignore it.
3252 Res.suppressDiagnostics();
3253 {
3254 TypoCorrectionConsumer::iterator Next = I;
3255 ++Next;
3256 Consumer.erase(I);
3257 I = Next;
3258 }
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003259 LastLookupWasAccepted = false;
Douglas Gregore24b5752010-10-14 20:34:08 +00003260 break;
3261
3262 case LookupResult::Found:
3263 case LookupResult::FoundOverloaded:
3264 case LookupResult::FoundUnresolvedValue:
3265 ++I;
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003266 LastLookupWasAccepted = true;
Douglas Gregoraaf87162010-04-14 20:04:41 +00003267 break;
Douglas Gregore24b5752010-10-14 20:34:08 +00003268 }
3269
3270 if (Res.isAmbiguous()) {
3271 // We don't deal with ambiguities.
3272 Res.suppressDiagnostics();
3273 Res.clear();
3274 return DeclarationName();
3275 }
Douglas Gregoraaf87162010-04-14 20:04:41 +00003276 }
Douglas Gregor546be3c2009-12-30 17:04:44 +00003277
Douglas Gregore24b5752010-10-14 20:34:08 +00003278 // If only a single name remains, return that result.
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003279 if (Consumer.size() == 1) {
3280 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregorf98402d2010-10-20 01:01:57 +00003281 if (Consumer.begin()->second) {
3282 Res.suppressDiagnostics();
3283 Res.clear();
Douglas Gregor53e4b552010-10-26 17:18:00 +00003284
3285 // Don't correct to a keyword that's the same as the typo; the keyword
3286 // wasn't actually in scope.
3287 if (ED == 0) {
3288 Res.setLookupName(Typo);
3289 return DeclarationName();
3290 }
3291
Douglas Gregorf98402d2010-10-20 01:01:57 +00003292 } else if (!LastLookupWasAccepted) {
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003293 // Perform name lookup on this name.
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003294 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3295 EnteringContext, CTC);
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003296 }
3297
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003298 // Record the correction for unqualified lookup.
3299 if (IsUnqualifiedLookup)
3300 UnqualifiedTyposCorrected[Typo]
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003301 = std::make_pair(Name->getName(), Consumer.begin()->second);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003302
Douglas Gregore24b5752010-10-14 20:34:08 +00003303 return &Context.Idents.get(Consumer.begin()->getKey());
Douglas Gregor6eaac8b2010-10-15 16:49:56 +00003304 }
Douglas Gregor7b824e82010-10-15 13:35:25 +00003305 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
3306 && Consumer["super"]) {
3307 // Prefix 'super' when we're completing in a message-receiver
3308 // context.
3309 Res.suppressDiagnostics();
3310 Res.clear();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003311
Douglas Gregor53e4b552010-10-26 17:18:00 +00003312 // Don't correct to a keyword that's the same as the typo; the keyword
3313 // wasn't actually in scope.
3314 if (ED == 0) {
3315 Res.setLookupName(Typo);
3316 return DeclarationName();
3317 }
3318
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003319 // Record the correction for unqualified lookup.
3320 if (IsUnqualifiedLookup)
3321 UnqualifiedTyposCorrected[Typo]
Douglas Gregor9a632ea2010-10-20 03:06:34 +00003322 = std::make_pair("super", Consumer.begin()->second);
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003323
Douglas Gregor7b824e82010-10-15 13:35:25 +00003324 return &Context.Idents.get("super");
3325 }
3326
Douglas Gregore24b5752010-10-14 20:34:08 +00003327 Res.suppressDiagnostics();
3328 Res.setLookupName(Typo);
Douglas Gregor546be3c2009-12-30 17:04:44 +00003329 Res.clear();
Douglas Gregor3eedbb02010-10-20 01:32:02 +00003330 // Record the correction for unqualified lookup.
3331 if (IsUnqualifiedLookup)
3332 (void)UnqualifiedTyposCorrected[Typo];
3333
Douglas Gregor931f98a2010-04-14 17:09:22 +00003334 return DeclarationName();
Douglas Gregor546be3c2009-12-30 17:04:44 +00003335}