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