blob: 09431492b9c60ba7168e6ec3278c7d616bd23003 [file] [log] [blame]
Douglas Gregor78d70132009-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//===----------------------------------------------------------------------===//
14#include "Sema.h"
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000015#include "SemaInherit.h"
16#include "clang/AST/ASTContext.h"
Douglas Gregor78d70132009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
Douglas Gregoraa1da4a2009-02-04 00:32:51 +000020#include "clang/AST/Expr.h"
Douglas Gregor78d70132009-01-14 22:20:51 +000021#include "clang/Parse/DeclSpec.h"
22#include "clang/Basic/LangOptions.h"
23#include "llvm/ADT/STLExtras.h"
Douglas Gregoraa1da4a2009-02-04 00:32:51 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorb9ef0552009-01-16 00:38:09 +000025#include <set>
Douglas Gregor7a7be652009-02-03 19:21:40 +000026#include <vector>
27#include <iterator>
28#include <utility>
29#include <algorithm>
Douglas Gregor78d70132009-01-14 22:20:51 +000030
31using namespace clang;
32
Douglas Gregor7a7be652009-02-03 19:21:40 +000033typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy;
34typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet;
35typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy;
36
37/// UsingDirAncestorCompare - Implements strict weak ordering of
38/// UsingDirectives. It orders them by address of its common ancestor.
39struct UsingDirAncestorCompare {
40
41 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
42 bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const {
43 return U->getCommonAncestor() < Ctx;
44 }
45
46 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
47 bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const {
48 return Ctx < U->getCommonAncestor();
49 }
50
51 /// @brief Compares UsingDirectiveDecl common ancestors.
52 bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const {
53 return U1->getCommonAncestor() < U2->getCommonAncestor();
54 }
55};
56
57/// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs
58/// (ordered by common ancestors), found in namespace NS,
59/// including all found (recursively) in their nominated namespaces.
60void AddNamespaceUsingDirectives(DeclContext *NS,
61 UsingDirectivesTy &UDirs,
62 NamespaceSet &Visited) {
63 DeclContext::udir_iterator I, End;
64
65 for (llvm::tie(I, End) = NS->getUsingDirectives(); I !=End; ++I) {
66 UDirs.push_back(*I);
67 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
68 NamespaceDecl *Nominated = (*I)->getNominatedNamespace();
69 if (Visited.insert(Nominated).second)
70 AddNamespaceUsingDirectives(Nominated, UDirs, /*ref*/ Visited);
71 }
72}
73
74/// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S,
75/// including all found in the namespaces they nominate.
76static void AddScopeUsingDirectives(Scope *S, UsingDirectivesTy &UDirs) {
77 NamespaceSet VisitedNS;
78
79 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
80
81 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx))
82 VisitedNS.insert(NS);
83
84 AddNamespaceUsingDirectives(Ctx, UDirs, /*ref*/ VisitedNS);
85
86 } else {
87 Scope::udir_iterator
88 I = S->using_directives_begin(),
89 End = S->using_directives_end();
90
91 for (; I != End; ++I) {
92 UsingDirectiveDecl * UD = static_cast<UsingDirectiveDecl*>(*I);
93 UDirs.push_back(UD);
94 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
95
96 NamespaceDecl *Nominated = UD->getNominatedNamespace();
97 if (!VisitedNS.count(Nominated)) {
98 VisitedNS.insert(Nominated);
99 AddNamespaceUsingDirectives(Nominated, UDirs, /*ref*/ VisitedNS);
100 }
101 }
102 }
103}
104
Douglas Gregor78d70132009-01-14 22:20:51 +0000105/// MaybeConstructOverloadSet - Name lookup has determined that the
106/// elements in [I, IEnd) have the name that we are looking for, and
107/// *I is a match for the namespace. This routine returns an
108/// appropriate Decl for name lookup, which may either be *I or an
Douglas Gregor7a7be652009-02-03 19:21:40 +0000109/// OverloadedFunctionDecl that represents the overloaded functions in
Douglas Gregor78d70132009-01-14 22:20:51 +0000110/// [I, IEnd).
111///
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000112/// The existance of this routine is temporary; users of LookupResult
113/// should be able to handle multiple results, to deal with cases of
Douglas Gregor78d70132009-01-14 22:20:51 +0000114/// ambiguity and overloaded functions without needing to create a
115/// Decl node.
116template<typename DeclIterator>
117static Decl *
118MaybeConstructOverloadSet(ASTContext &Context,
119 DeclIterator I, DeclIterator IEnd) {
120 assert(I != IEnd && "Iterator range cannot be empty");
121 assert(!isa<OverloadedFunctionDecl>(*I) &&
122 "Cannot have an overloaded function");
123
124 if (isa<FunctionDecl>(*I)) {
125 // If we found a function, there might be more functions. If
126 // so, collect them into an overload set.
127 DeclIterator Last = I;
128 OverloadedFunctionDecl *Ovl = 0;
129 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
130 if (!Ovl) {
131 // FIXME: We leak this overload set. Eventually, we want to
132 // stop building the declarations for these overload sets, so
133 // there will be nothing to leak.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000134 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
Douglas Gregor78d70132009-01-14 22:20:51 +0000135 (*I)->getDeclName());
136 Ovl->addOverload(cast<FunctionDecl>(*I));
137 }
138 Ovl->addOverload(cast<FunctionDecl>(*Last));
139 }
140
141 // If we had more than one function, we built an overload
142 // set. Return it.
143 if (Ovl)
144 return Ovl;
145 }
146
147 return *I;
148}
149
Douglas Gregor7a7be652009-02-03 19:21:40 +0000150/// Merges together multiple LookupResults dealing with duplicated Decl's.
151static Sema::LookupResult
152MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
153 typedef Sema::LookupResult LResult;
154 typedef llvm::SmallVector<NamedDecl*, 3> DeclsVecTy;
155
156 DeclsVecTy FoundDecls;
157 OverloadedFunctionDecl *FoundOverloaded = 0;
158
159 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
160 for (; I != End; ++I) {
161
162 switch (I->getKind()) {
163 case LResult::NotFound:
164 assert(false &&
165 "Should be always successful name lookup result here.");
166 break;
167
168 case LResult::AmbiguousReference:
169 assert(false &&
170 "Shouldn't get ambiguous reference here.");
171 break;
172
173 case LResult::Found:
174 FoundDecls.push_back(cast<NamedDecl>(I->getAsDecl()));
175 break;
176
177 case LResult::AmbiguousBaseSubobjectTypes:
178 case LResult::AmbiguousBaseSubobjects: {
179 LResult Ambig = *I;
180 // Free rest of OverloadedFunctionDecl, and other BasePaths
181 // stored in LookupResults.
182#if 0
183 // FIXME:
184 // It should not happen, when we look start in each DeclContext only once.
185 // See FIXME in CppLookupName.
186 assert(Results.size() == 1 && "Multiple LookupResults should be not case "
187 "here, since using-directives can't occur at class scope.");
188#else
189 if (FoundOverloaded)
190 FoundOverloaded->Destroy(Context);
191
192 for (++I; I != End; ++I) {
193 if (I->getKind() == LResult::FoundOverloaded)
194 cast<OverloadedFunctionDecl>(I->getAsDecl())->Destroy(Context);
195 else if (BasePaths *Paths = I->getBasePaths())
196 delete Paths;
197 assert(I->getKind() != LResult::AmbiguousReference &&
198 "Shouldn't get ambiguous reference here.");
199 }
200#endif
201 return Ambig;
202 }
203
204 case LResult::FoundOverloaded:
205 if (FoundOverloaded) {
206 // We have one spare OverloadedFunctionDecl already, so we store
207 // its function decls.
208#if 0
209 FIXME: As soon as, stop call MaybeConstructOverloadSet here,
210 which requires iterator::reference of type NamedDecl*, FoundDecls
211 can be SmallVector<Decl*, >
212 or when Lookup*Name() starts return NamedDecl's* instead of Decl's
213
214 this will work:
215 std::copy(I->begin(), I->end(), std::back_inserter(FoundDecls));
216#else
217 Sema::LookupResult::iterator OI = I->begin(), OEnd = I->end();
218 for (; OI != OEnd; ++OI)
219 FoundDecls.push_back(cast<NamedDecl>(*OI));
220#endif
221 } else {
222 // First time we found OverloadedFunctionDecl, we want to conserve
223 // it, and possibly add other found Decls later.
224 FoundOverloaded = cast<OverloadedFunctionDecl>(I->getAsDecl());
225 }
226 break;
227 }
228 }
229
230 // Remove duplicated Decl pointing at same Decl, this might be case
231 // for code like:
232 //
233 // namespace A { int i; }
234 // namespace B { using namespace A; }
235 // namespace C { using namespace A; }
236 //
237 // void foo() {
238 // using namespace B;
239 // using namespace C;
240 // ++i; // finds A::i, from both namespace B and C at global scope
241 // }
242 //
243 // C++ [namespace.qual].p3:
244 // The same declaration found more than once is not an ambiguity
245 // (because it is still a unique declaration).
246 //
247 // FIXME: At this point happens too, because we are doing redundant lookups.
248 //
249 DeclsVecTy::iterator DI = FoundDecls.begin(), DEnd = FoundDecls.end();
250 // FIXME: Using SmallPtrSet instead would be better, once OverloadedFunctionDecl
251 // dies.
252 std::sort(DI, DEnd);
253 DEnd = std::unique(DI, DEnd);
254
255 if (FoundOverloaded) {
256 // We found overloaded functions result. We want to add any other
257 // found decls, that are not already in FoundOverloaded, and are functions
258 // or methods.
259 OverloadedFunctionDecl::function_iterator
260 FBegin = FoundOverloaded->function_begin(),
261 FEnd = FoundOverloaded->function_end();
262 // FIXME: This is O(n^2)!
Chris Lattnerb02f5f22009-02-03 21:29:32 +0000263 for (; DI < DEnd; ++DI) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000264 FunctionDecl *Fun = dyn_cast<FunctionDecl>(*DI);
265 if (Fun && (std::find(FBegin, FEnd, Fun) != FEnd)) { /* Skip.*/ }
266 else DEnd = std::remove(DI, DEnd, *DI);
267 }
268
269 for (DI = FoundDecls.begin(); DI != DEnd; ++DI)
270 FoundOverloaded->addOverload(cast<FunctionDecl>(*DI));
271
272 return LResult::CreateLookupResult(Context, FoundOverloaded);
273 } else if (std::size_t FoundLen = std::distance(FoundDecls.begin(), DEnd)) {
274 // We might found multiple TagDecls pointing at same definition.
275 if (TagDecl *R = dyn_cast<TagDecl>(*FoundDecls.begin())) {
276 TagDecl *Canonical = Context.getCanonicalDecl(R);
277 DeclsVecTy::iterator RI = FoundDecls.begin(), REnd = DEnd;
278 for (;;) {
279 ++RI;
280 if (RI == REnd) {
281 FoundLen = 1;
282 break;
283 }
284 R = dyn_cast<TagDecl>(*RI);
285 if (R && Canonical == Context.getCanonicalDecl(R)) { /* Skip */}
286 else break;
287 }
288 }
289
290 // We might find FunctionDecls in two (or more) distinct DeclContexts.
291 // 3.4.1.p1 ... Name lookup may associate more than one declaration with
292 // a name if it finds the name to be a function name; the declarations
293 // are said to form a set of overloaded functions (13.1).
294 // Overload resolution (13.3) takes place after name lookup has succeeded.
295
296 Decl *D = MaybeConstructOverloadSet(Context, DI, DEnd);
297 if ((FoundLen == 1) || isa<OverloadedFunctionDecl>(D))
298 return LResult::CreateLookupResult(Context, D);
299
300 // Found multiple Decls, it is ambiguous reference.
301 return LResult::CreateLookupResult(Context, FoundDecls.begin(), FoundLen);
302 }
303
304 LResult Result = LResult::CreateLookupResult(Context, 0);
305 return Result;
306}
307
308// Retrieve the set of identifier namespaces that correspond to a
309// specific kind of name lookup.
310inline unsigned
311getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
312 bool CPlusPlus) {
313 unsigned IDNS = 0;
314 switch (NameKind) {
315 case Sema::LookupOrdinaryName:
316 IDNS = Decl::IDNS_Ordinary;
317 if (CPlusPlus)
318 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
319 break;
320
321 case Sema::LookupTagName:
322 IDNS = Decl::IDNS_Tag;
323 break;
324
325 case Sema::LookupMemberName:
326 IDNS = Decl::IDNS_Member;
327 if (CPlusPlus)
328 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
329 break;
330
331 case Sema::LookupNestedNameSpecifierName:
332 case Sema::LookupNamespaceName:
333 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
334 break;
335 }
336 return IDNS;
337}
338
339// Return qualified name for Decl D, like A::B::i, for i being member of
340// namespace A::B.
341std::string
342getQualifiedName(Decl *D) {
343 std::vector<std::string> Names;
344 std::string QualName;
345 DeclContext *Ctx = D->getDeclContext();
346
347 if (Ctx->isFunctionOrMethod())
348 return cast<NamedDecl>(D)->getNameAsString();
349
350 while (Ctx) {
351 if (Ctx->isFunctionOrMethod()) {
352 // FIXME: That probably is happend, because D was member of local
353 // scope class/struct/union. How do we handle this case?
354 break;
355 }
356 if (NamedDecl *ND = dyn_cast<NamedDecl>(Ctx)) {
357 Names.push_back(ND->getNameAsString());
358 } else {
359 break;
360 }
361 Ctx = Ctx->getParent();
362 }
363 for (std::vector<std::string>::reverse_iterator I= Names.rbegin(), End =Names.rend(); I!=End; ++I)
364 QualName += *I + "::";
365 QualName += cast<NamedDecl>(D)->getNameAsString();
366 return QualName;
367}
368
369Sema::LookupResult
370Sema::LookupResult::CreateLookupResult(ASTContext &Context, Decl *D) {
371 LookupResult Result;
372 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
373 OverloadedDeclSingleDecl : SingleDecl;
374 Result.First = reinterpret_cast<uintptr_t>(D);
375 Result.Last = 0;
376 Result.Context = &Context;
377 return Result;
378}
379
Douglas Gregor6beddfe2009-01-15 02:19:31 +0000380/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregord07474b2009-01-17 01:13:24 +0000381Sema::LookupResult
382Sema::LookupResult::CreateLookupResult(ASTContext &Context,
383 IdentifierResolver::iterator F,
384 IdentifierResolver::iterator L) {
385 LookupResult Result;
386 Result.Context = &Context;
387
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000388 if (F != L && isa<FunctionDecl>(*F)) {
389 IdentifierResolver::iterator Next = F;
390 ++Next;
391 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000392 Result.StoredKind = OverloadedDeclFromIdResolver;
393 Result.First = F.getAsOpaqueValue();
394 Result.Last = L.getAsOpaqueValue();
395 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000396 }
397 }
398
Douglas Gregord07474b2009-01-17 01:13:24 +0000399 Result.StoredKind = SingleDecl;
400 Result.First = reinterpret_cast<uintptr_t>(*F);
401 Result.Last = 0;
402 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000403}
404
Douglas Gregord07474b2009-01-17 01:13:24 +0000405Sema::LookupResult
406Sema::LookupResult::CreateLookupResult(ASTContext &Context,
407 DeclContext::lookup_iterator F,
408 DeclContext::lookup_iterator L) {
409 LookupResult Result;
410 Result.Context = &Context;
411
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000412 if (F != L && isa<FunctionDecl>(*F)) {
413 DeclContext::lookup_iterator Next = F;
414 ++Next;
415 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000416 Result.StoredKind = OverloadedDeclFromDeclContext;
417 Result.First = reinterpret_cast<uintptr_t>(F);
418 Result.Last = reinterpret_cast<uintptr_t>(L);
419 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000420 }
421 }
422
Douglas Gregord07474b2009-01-17 01:13:24 +0000423 Result.StoredKind = SingleDecl;
424 Result.First = reinterpret_cast<uintptr_t>(*F);
425 Result.Last = 0;
426 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000427}
428
Douglas Gregor78d70132009-01-14 22:20:51 +0000429/// @brief Determine the result of name lookup.
430Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
431 switch (StoredKind) {
432 case SingleDecl:
433 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
434
Douglas Gregor7a7be652009-02-03 19:21:40 +0000435 case OverloadedDeclSingleDecl:
Douglas Gregor78d70132009-01-14 22:20:51 +0000436 case OverloadedDeclFromIdResolver:
437 case OverloadedDeclFromDeclContext:
438 return FoundOverloaded;
439
Douglas Gregor7a7be652009-02-03 19:21:40 +0000440 case AmbiguousLookupStoresBasePaths:
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000441 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000442
443 case AmbiguousLookupStoresDecls:
444 return AmbiguousReference;
Douglas Gregor78d70132009-01-14 22:20:51 +0000445 }
446
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000447 // We can't ever get here.
448 return NotFound;
Douglas Gregor78d70132009-01-14 22:20:51 +0000449}
450
451/// @brief Converts the result of name lookup into a single (possible
452/// NULL) pointer to a declaration.
453///
454/// The resulting declaration will either be the declaration we found
455/// (if only a single declaration was found), an
456/// OverloadedFunctionDecl (if an overloaded function was found), or
457/// NULL (if no declaration was found). This conversion must not be
458/// used anywhere where name lookup could result in an ambiguity.
459///
460/// The OverloadedFunctionDecl conversion is meant as a stop-gap
461/// solution, since it causes the OverloadedFunctionDecl to be
462/// leaked. FIXME: Eventually, there will be a better way to iterate
463/// over the set of overloaded functions returned by name lookup.
464Decl *Sema::LookupResult::getAsDecl() const {
465 switch (StoredKind) {
466 case SingleDecl:
467 return reinterpret_cast<Decl *>(First);
468
469 case OverloadedDeclFromIdResolver:
470 return MaybeConstructOverloadSet(*Context,
471 IdentifierResolver::iterator::getFromOpaqueValue(First),
472 IdentifierResolver::iterator::getFromOpaqueValue(Last));
473
474 case OverloadedDeclFromDeclContext:
475 return MaybeConstructOverloadSet(*Context,
476 reinterpret_cast<DeclContext::lookup_iterator>(First),
477 reinterpret_cast<DeclContext::lookup_iterator>(Last));
478
Douglas Gregor7a7be652009-02-03 19:21:40 +0000479 case OverloadedDeclSingleDecl:
480 return reinterpret_cast<OverloadedFunctionDecl*>(First);
481
482 case AmbiguousLookupStoresDecls:
483 case AmbiguousLookupStoresBasePaths:
Douglas Gregor78d70132009-01-14 22:20:51 +0000484 assert(false &&
485 "Name lookup returned an ambiguity that could not be handled");
486 break;
487 }
488
489 return 0;
490}
491
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000492/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor7a7be652009-02-03 19:21:40 +0000493/// name lookup, or null.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000494BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000495 if (StoredKind == AmbiguousLookupStoresBasePaths)
496 return reinterpret_cast<BasePaths *>(First);
497 return 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000498}
499
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000500Sema::LookupResult::iterator::reference
501Sema::LookupResult::iterator::operator*() const {
502 switch (Result->StoredKind) {
503 case SingleDecl:
504 return reinterpret_cast<Decl*>(Current);
505
Douglas Gregor7a7be652009-02-03 19:21:40 +0000506 case OverloadedDeclSingleDecl:
507 return *reinterpret_cast<Decl**>(Current);
508
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000509 case OverloadedDeclFromIdResolver:
510 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
511
512 case OverloadedDeclFromDeclContext:
513 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000514
515 case AmbiguousLookupStoresDecls:
516 case AmbiguousLookupStoresBasePaths:
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000517 assert(false && "Cannot look into ambiguous lookup results");
518 break;
519 }
520
521 return 0;
522}
523
524Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
525 switch (Result->StoredKind) {
526 case SingleDecl:
527 Current = reinterpret_cast<uintptr_t>((Decl*)0);
528 break;
529
Douglas Gregor7a7be652009-02-03 19:21:40 +0000530 case OverloadedDeclSingleDecl: {
531 Decl ** I = reinterpret_cast<Decl**>(Current);
532 ++I;
533 Current = reinterpret_cast<uintptr_t>(I);
534 }
535
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000536 case OverloadedDeclFromIdResolver: {
537 IdentifierResolver::iterator I
538 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
539 ++I;
540 Current = I.getAsOpaqueValue();
541 break;
542 }
543
544 case OverloadedDeclFromDeclContext: {
545 DeclContext::lookup_iterator I
546 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
547 ++I;
548 Current = reinterpret_cast<uintptr_t>(I);
549 break;
550 }
551
Douglas Gregor7a7be652009-02-03 19:21:40 +0000552 case AmbiguousLookupStoresDecls:
553 case AmbiguousLookupStoresBasePaths:
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000554 assert(false && "Cannot look into ambiguous lookup results");
555 break;
556 }
557
558 return *this;
559}
560
561Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000562 assert(!isAmbiguous() && "Lookup into an ambiguous result");
563 if (StoredKind != OverloadedDeclSingleDecl)
564 return iterator(this, First);
565 OverloadedFunctionDecl * Ovl =
566 reinterpret_cast<OverloadedFunctionDecl*>(First);
567 return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000568}
569
570Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000571 assert(!isAmbiguous() && "Lookup into an ambiguous result");
572 if (StoredKind != OverloadedDeclSingleDecl)
573 return iterator(this, Last);
574 OverloadedFunctionDecl * Ovl =
575 reinterpret_cast<OverloadedFunctionDecl*>(First);
576 return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000577}
578
Douglas Gregor7a7be652009-02-03 19:21:40 +0000579static bool isFunctionLocalScope(Scope *S) {
580 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
581 return Ctx->isFunctionOrMethod();
582 return true;
583}
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000584
Douglas Gregor7a7be652009-02-03 19:21:40 +0000585std::pair<bool, Sema::LookupResult>
586Sema::CppLookupName(Scope *S, DeclarationName Name,
587 LookupNameKind NameKind, bool RedeclarationOnly) {
588 assert(getLangOptions().CPlusPlus &&
589 "Can perform only C++ lookup");
590unsigned IDNS
591 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
592 Scope *Initial = S;
593 IdentifierResolver::iterator
594 I = IdResolver.begin(Name),
595 IEnd = IdResolver.end();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000596
Douglas Gregor7a7be652009-02-03 19:21:40 +0000597 // First we lookup local scope.
598 // We don't consider using-dirctives, as per 7.3.4.p1 [namespace.udir]
599 // ...During unqualified name lookup (3.4.1), the names appear as if
600 // they were declared in the nearest enclosing namespace which contains
601 // both the using-directive and the nominated namespace.
602 // [Note: in this context, “contains” means “contains directly or
603 // indirectly”.
604 //
605 // For example:
606 // namespace A { int i; }
607 // void foo() {
608 // int i;
609 // {
610 // using namespace A;
611 // ++i; // finds local 'i', A::i appears at global scope
612 // }
613 // }
614 //
615 for (; S && isFunctionLocalScope(S); S = S->getParent()) {
616 // Check whether the IdResolver has anything in this scope.
617 for (; I != IEnd && S->isDeclScope(*I); ++I) {
618 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
619 // We found something. Look for anything else in our scope
620 // with this same name and in an acceptable identifier
621 // namespace, so that we can construct an overload set if we
622 // need to.
623 IdentifierResolver::iterator LastI = I;
624 for (++LastI; LastI != IEnd; ++LastI) {
625 if (!S->isDeclScope(*LastI))
626 break;
627 }
628 LookupResult Result =
629 LookupResult::CreateLookupResult(Context, I, LastI);
630 return std::make_pair(true, Result);
631 }
632 }
633 // NB: Icky, we need to look in function scope, but we need to check its
634 // parent DeclContext (instead S->getParent()) for member name lookup,
635 // in case it is out of line method definition. Like in:
636 //
637 // class C {
638 // int i;
639 // void foo();
640 // };
641 //
642 // C::foo() {
643 // (void) i;
644 // }
645 //
646 // FIXME: Maybe we should do member name lookup here instead?
647 if (S->getEntity() && isFunctionLocalScope(S))
648 break;
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000649 }
Douglas Gregor7a7be652009-02-03 19:21:40 +0000650
651 // Collect UsingDirectiveDecls in all scopes, and recursivly all
652 // nominated namespaces by those using-directives.
653 // UsingDirectives are pushed to heap, in common ancestor pointer
654 // value order.
655 // FIXME: Cache this sorted list in Scope structure, and maybe
656 // DeclContext, so we don't build it for each lookup!
657 UsingDirectivesTy UDirs;
658 for (Scope *SC = Initial; SC; SC = SC->getParent())
659 AddScopeUsingDirectives(SC, UDirs);
660
661 // Sort heapified UsingDirectiveDecls.
662 std::sort_heap(UDirs.begin(), UDirs.end());
663
664 // Lookup namespace scope, global scope, or possibly (CXX)Record DeclContext
665 // for member name lookup.
666 // Unqualified name lookup in C++ requires looking into scopes
667 // that aren't strictly lexical, and therefore we walk through the
668 // context as well as walking through the scopes.
669 for (; S; S = S->getParent()) {
670 LookupResultsTy LookupResults;
671 bool LookedInCtx = false;
672
673 // Check whether the IdResolver has anything in this scope.
674 for (; I != IEnd && S->isDeclScope(*I); ++I) {
675 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
676 // We found something. Look for anything else in our scope
677 // with this same name and in an acceptable identifier
678 // namespace, so that we can construct an overload set if we
679 // need to.
680 IdentifierResolver::iterator LastI = I;
681 for (++LastI; LastI != IEnd; ++LastI) {
682 if (!S->isDeclScope(*LastI))
683 break;
684 }
685
686 // We store name lookup result, and continue trying to look into
687 // associated context, and maybe namespaces nominated by
688 // using-directives.
689 LookupResults.push_back(
690 LookupResult::CreateLookupResult(Context, I, LastI));
691 break;
692 }
693 }
694
695 // If there is an entity associated with this scope, it's a
696 // DeclContext. We might need to perform qualified lookup into
697 // it, or namespaces nominated by using-directives.
698 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
699
700 if (Ctx && isa<TranslationUnitDecl>(Ctx)) {
701 UsingDirectivesTy::const_iterator UI, UEnd;
702 // For each UsingDirectiveDecl, which common ancestor is equal
703 // to Ctx, we preform qualified name lookup into namespace nominated
704 // by it.
705 llvm::tie(UI, UEnd) =
706 std::equal_range(UDirs.begin(), UDirs.end(), Ctx,
707 UsingDirAncestorCompare());
708 for (; UI != UEnd; ++UI) {
709 // FIXME: We will have to ensure, that we won't consider
710 // again using-directives during qualified name lookup!
711 // (Once using-directives support for qualified name lookup gets
712 // implemented).
713 if (LookupResult R = LookupQualifiedName((*UI)->getNominatedNamespace(),
714 Name, NameKind, RedeclarationOnly))
715 LookupResults.push_back(R);
716 }
717 LookupResult Result;
718 if ((Result = MergeLookupResults(Context, LookupResults)) ||
719 RedeclarationOnly) {
720 return std::make_pair(true, Result);
721 }
722 }
723
724 // FIXME: We're performing redundant lookups here, where the
725 // scope stack mirrors the semantic nested of classes and
726 // namespaces. We can save some work by checking the lexical
727 // scope against the semantic scope and avoiding any lookups
728 // when they are the same.
729 // FIXME: In some cases, we know that every name that could be
730 // found by this qualified name lookup will also be on the
731 // identifier chain. For example, inside a class without any
732 // base classes, we never need to perform qualified lookup
733 // because all of the members are on top of the identifier
734 // chain. However, we cannot perform this optimization when the
735 // lexical and semantic scopes don't line up, e.g., in an
736 // out-of-line member definition.
737 while (Ctx && Ctx->isFunctionOrMethod())
738 Ctx = Ctx->getParent();
739 while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
740 LookedInCtx = true;
741 // Look for declarations of this name in this scope.
742 if (LookupResult R = LookupQualifiedName(Ctx, Name, NameKind,
743 RedeclarationOnly))
744 // We store that, to investigate futher, wheather reference
745 // to this Decl is no ambiguous.
746 LookupResults.push_back(R);
747
748 if (Ctx->isNamespace()) {
749 // For each UsingDirectiveDecl, which common ancestor is equal
750 // to Ctx, we preform qualified name lookup into namespace nominated
751 // by it.
752 UsingDirectivesTy::const_iterator UI, UEnd;
753 llvm::tie(UI, UEnd) =
754 std::equal_range(UDirs.begin(), UDirs.end(), Ctx,
755 UsingDirAncestorCompare());
756 for (; UI != UEnd; ++UI) {
757 // FIXME: We will have to ensure, that we won't consider
758 // again using-directives during qualified name lookup!
759 // (Once using-directives support for qualified name lookup gets
760 // implemented).
761 LookupResult R = LookupQualifiedName((*UI)->getNominatedNamespace(),
762 Name, NameKind,
763 RedeclarationOnly);
764 if (R)
765 LookupResults.push_back(R);
766 }
767 }
768 LookupResult Result;
769 if ((Result = MergeLookupResults(Context, LookupResults)) ||
770 (RedeclarationOnly && !Ctx->isTransparentContext())) {
771 return std::make_pair(true, Result);
772 }
773 Ctx = Ctx->getParent();
774 }
775
776 if (!(LookedInCtx || LookupResults.empty())) {
777 // We didn't Performed lookup in Scope entity, so we return
778 // result form IdentifierResolver.
779 assert((LookupResults.size() == 1) && "Wrong size!");
780 return std::make_pair(true, LookupResults.front());
781 }
782 }
783 return std::make_pair(false, LookupResult());
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000784}
785
Douglas Gregor78d70132009-01-14 22:20:51 +0000786/// @brief Perform unqualified name lookup starting from a given
787/// scope.
788///
789/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
790/// used to find names within the current scope. For example, 'x' in
791/// @code
792/// int x;
793/// int f() {
794/// return x; // unqualified name look finds 'x' in the global scope
795/// }
796/// @endcode
797///
798/// Different lookup criteria can find different names. For example, a
799/// particular scope can have both a struct and a function of the same
800/// name, and each can be found by certain lookup criteria. For more
801/// information about lookup criteria, see the documentation for the
802/// class LookupCriteria.
803///
804/// @param S The scope from which unqualified name lookup will
805/// begin. If the lookup criteria permits, name lookup may also search
806/// in the parent scopes.
807///
808/// @param Name The name of the entity that we are searching for.
809///
810/// @param Criteria The criteria that this routine will use to
811/// determine which names are visible and which names will be
812/// found. Note that name lookup will find a name that is visible by
813/// the given criteria, but the entity itself may not be semantically
814/// correct or even the kind of entity expected based on the
815/// lookup. For example, searching for a nested-name-specifier name
816/// might result in an EnumDecl, which is visible but is not permitted
817/// as a nested-name-specifier in C++03.
818///
819/// @returns The result of name lookup, which includes zero or more
820/// declarations and possibly additional information used to diagnose
821/// ambiguities.
822Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000823Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
824 bool RedeclarationOnly) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000825 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000826
827 if (!getLangOptions().CPlusPlus) {
828 // Unqualified name lookup in C/Objective-C is purely lexical, so
829 // search in the declarations attached to the name.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000830 unsigned IDNS = 0;
831 switch (NameKind) {
832 case Sema::LookupOrdinaryName:
833 IDNS = Decl::IDNS_Ordinary;
834 break;
Douglas Gregor78d70132009-01-14 22:20:51 +0000835
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000836 case Sema::LookupTagName:
837 IDNS = Decl::IDNS_Tag;
838 break;
839
840 case Sema::LookupMemberName:
841 IDNS = Decl::IDNS_Member;
842 break;
843
844 case Sema::LookupNestedNameSpecifierName:
845 case Sema::LookupNamespaceName:
846 assert(false && "C does not perform these kinds of name lookup");
847 break;
848 }
849
Douglas Gregor78d70132009-01-14 22:20:51 +0000850 // Scan up the scope chain looking for a decl that matches this
851 // identifier that is in the appropriate namespace. This search
852 // should not take long, as shadowing of names is uncommon, and
853 // deep shadowing is extremely uncommon.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000854 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
855 IEnd = IdResolver.end();
856 I != IEnd; ++I)
857 if ((*I)->isInIdentifierNamespace(IDNS))
Douglas Gregord07474b2009-01-17 01:13:24 +0000858 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregor78d70132009-01-14 22:20:51 +0000859 } else {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000860 // Perform C++ unqualified name lookup.
861 std::pair<bool, LookupResult> MaybeResult =
862 CppLookupName(S, Name, NameKind, RedeclarationOnly);
863 if (MaybeResult.first)
864 return MaybeResult.second;
Douglas Gregor78d70132009-01-14 22:20:51 +0000865 }
866
867 // If we didn't find a use of this identifier, and if the identifier
868 // corresponds to a compiler builtin, create the decl object for the builtin
869 // now, injecting it into translation unit scope, and return it.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000870 if (NameKind == LookupOrdinaryName) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000871 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000872 if (II) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000873 // If this is a builtin on this (or all) targets, create the decl.
874 if (unsigned BuiltinID = II->getBuiltinID())
Douglas Gregord07474b2009-01-17 01:13:24 +0000875 return LookupResult::CreateLookupResult(Context,
Douglas Gregor78d70132009-01-14 22:20:51 +0000876 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
877 S));
878 }
879 if (getLangOptions().ObjC1 && II) {
880 // @interface and @compatibility_alias introduce typedef-like names.
881 // Unlike typedef's, they can only be introduced at file-scope (and are
882 // therefore not scoped decls). They can, however, be shadowed by
883 // other names in IDNS_Ordinary.
884 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
885 if (IDI != ObjCInterfaceDecls.end())
Douglas Gregord07474b2009-01-17 01:13:24 +0000886 return LookupResult::CreateLookupResult(Context, IDI->second);
Douglas Gregor78d70132009-01-14 22:20:51 +0000887 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
888 if (I != ObjCAliasDecls.end())
Douglas Gregord07474b2009-01-17 01:13:24 +0000889 return LookupResult::CreateLookupResult(Context,
890 I->second->getClassInterface());
Douglas Gregor78d70132009-01-14 22:20:51 +0000891 }
892 }
Douglas Gregord07474b2009-01-17 01:13:24 +0000893 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000894}
895
896/// @brief Perform qualified name lookup into a given context.
897///
898/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
899/// names when the context of those names is explicit specified, e.g.,
900/// "std::vector" or "x->member".
901///
902/// Different lookup criteria can find different names. For example, a
903/// particular scope can have both a struct and a function of the same
904/// name, and each can be found by certain lookup criteria. For more
905/// information about lookup criteria, see the documentation for the
906/// class LookupCriteria.
907///
908/// @param LookupCtx The context in which qualified name lookup will
909/// search. If the lookup criteria permits, name lookup may also search
910/// in the parent contexts or (for C++ classes) base classes.
911///
912/// @param Name The name of the entity that we are searching for.
913///
914/// @param Criteria The criteria that this routine will use to
915/// determine which names are visible and which names will be
916/// found. Note that name lookup will find a name that is visible by
917/// the given criteria, but the entity itself may not be semantically
918/// correct or even the kind of entity expected based on the
919/// lookup. For example, searching for a nested-name-specifier name
920/// might result in an EnumDecl, which is visible but is not permitted
921/// as a nested-name-specifier in C++03.
922///
923/// @returns The result of name lookup, which includes zero or more
924/// declarations and possibly additional information used to diagnose
925/// ambiguities.
926Sema::LookupResult
927Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000928 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000929 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
930
Douglas Gregord07474b2009-01-17 01:13:24 +0000931 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000932
933 // If we're performing qualified name lookup (e.g., lookup into a
934 // struct), find fields as part of ordinary name lookup.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000935 unsigned IDNS
936 = getIdentifierNamespacesFromLookupNameKind(NameKind,
937 getLangOptions().CPlusPlus);
938 if (NameKind == LookupOrdinaryName)
939 IDNS |= Decl::IDNS_Member;
Douglas Gregor78d70132009-01-14 22:20:51 +0000940
941 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor78d70132009-01-14 22:20:51 +0000942 DeclContext::lookup_iterator I, E;
943 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000944 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregord07474b2009-01-17 01:13:24 +0000945 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregor78d70132009-01-14 22:20:51 +0000946
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000947 // If this isn't a C++ class or we aren't allowed to look into base
948 // classes, we're done.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000949 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregord07474b2009-01-17 01:13:24 +0000950 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000951
952 // Perform lookup into our base classes.
953 BasePaths Paths;
Douglas Gregorb9ef0552009-01-16 00:38:09 +0000954 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000955
956 // Look for this member in our base classes
957 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000958 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregord07474b2009-01-17 01:13:24 +0000959 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000960
961 // C++ [class.member.lookup]p2:
962 // [...] If the resulting set of declarations are not all from
963 // sub-objects of the same type, or the set has a nonstatic member
964 // and includes members from distinct sub-objects, there is an
965 // ambiguity and the program is ill-formed. Otherwise that set is
966 // the result of the lookup.
967 // FIXME: support using declarations!
968 QualType SubobjectType;
Daniel Dunbarddebeca2009-01-15 18:32:35 +0000969 int SubobjectNumber = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000970 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
971 Path != PathEnd; ++Path) {
972 const BasePathElement &PathElement = Path->back();
973
974 // Determine whether we're looking at a distinct sub-object or not.
975 if (SubobjectType.isNull()) {
976 // This is the first subobject we've looked at. Record it's type.
977 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
978 SubobjectNumber = PathElement.SubobjectNumber;
979 } else if (SubobjectType
980 != Context.getCanonicalType(PathElement.Base->getType())) {
981 // We found members of the given name in two subobjects of
982 // different types. This lookup is ambiguous.
983 BasePaths *PathsOnHeap = new BasePaths;
984 PathsOnHeap->swap(Paths);
Douglas Gregord07474b2009-01-17 01:13:24 +0000985 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000986 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
987 // We have a different subobject of the same type.
988
989 // C++ [class.member.lookup]p5:
990 // A static member, a nested type or an enumerator defined in
991 // a base class T can unambiguously be found even if an object
992 // has more than one base class subobject of type T.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000993 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000994 if (isa<VarDecl>(FirstDecl) ||
995 isa<TypeDecl>(FirstDecl) ||
996 isa<EnumConstantDecl>(FirstDecl))
997 continue;
998
999 if (isa<CXXMethodDecl>(FirstDecl)) {
1000 // Determine whether all of the methods are static.
1001 bool AllMethodsAreStatic = true;
1002 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1003 Func != Path->Decls.second; ++Func) {
1004 if (!isa<CXXMethodDecl>(*Func)) {
1005 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1006 break;
1007 }
1008
1009 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1010 AllMethodsAreStatic = false;
1011 break;
1012 }
1013 }
1014
1015 if (AllMethodsAreStatic)
1016 continue;
1017 }
1018
1019 // We have found a nonstatic member name in multiple, distinct
1020 // subobjects. Name lookup is ambiguous.
1021 BasePaths *PathsOnHeap = new BasePaths;
1022 PathsOnHeap->swap(Paths);
Douglas Gregord07474b2009-01-17 01:13:24 +00001023 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001024 }
1025 }
1026
1027 // Lookup in a base class succeeded; return these results.
1028
1029 // If we found a function declaration, return an overload set.
1030 if (isa<FunctionDecl>(*Paths.front().Decls.first))
Douglas Gregord07474b2009-01-17 01:13:24 +00001031 return LookupResult::CreateLookupResult(Context,
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001032 Paths.front().Decls.first, Paths.front().Decls.second);
1033
1034 // We found a non-function declaration; return a single declaration.
Douglas Gregord07474b2009-01-17 01:13:24 +00001035 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregor78d70132009-01-14 22:20:51 +00001036}
1037
1038/// @brief Performs name lookup for a name that was parsed in the
1039/// source code, and may contain a C++ scope specifier.
1040///
1041/// This routine is a convenience routine meant to be called from
1042/// contexts that receive a name and an optional C++ scope specifier
1043/// (e.g., "N::M::x"). It will then perform either qualified or
1044/// unqualified name lookup (with LookupQualifiedName or LookupName,
1045/// respectively) on the given name and return those results.
1046///
1047/// @param S The scope from which unqualified name lookup will
1048/// begin.
1049///
1050/// @param SS An optional C++ scope-specified, e.g., "::N::M".
1051///
1052/// @param Name The name of the entity that name lookup will
1053/// search for.
1054///
Douglas Gregor78d70132009-01-14 22:20:51 +00001055/// @returns The result of qualified or unqualified name lookup.
1056Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001057Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1058 DeclarationName Name, LookupNameKind NameKind,
1059 bool RedeclarationOnly) {
1060 if (SS) {
1061 if (SS->isInvalid())
1062 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +00001063
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001064 if (SS->isSet())
1065 return LookupQualifiedName(static_cast<DeclContext *>(SS->getScopeRep()),
1066 Name, NameKind, RedeclarationOnly);
1067 }
1068
1069 return LookupName(S, Name, NameKind, RedeclarationOnly);
Douglas Gregor78d70132009-01-14 22:20:51 +00001070}
1071
Douglas Gregor7a7be652009-02-03 19:21:40 +00001072
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001073/// @brief Produce a diagnostic describing the ambiguity that resulted
1074/// from name lookup.
1075///
1076/// @param Result The ambiguous name lookup result.
1077///
1078/// @param Name The name of the entity that name lookup was
1079/// searching for.
1080///
1081/// @param NameLoc The location of the name within the source code.
1082///
1083/// @param LookupRange A source range that provides more
1084/// source-location information concerning the lookup itself. For
1085/// example, this range might highlight a nested-name-specifier that
1086/// precedes the name.
1087///
1088/// @returns true
1089bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1090 SourceLocation NameLoc,
1091 SourceRange LookupRange) {
1092 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1093
Douglas Gregor7a7be652009-02-03 19:21:40 +00001094 if (BasePaths *Paths = Result.getBasePaths())
1095 {
1096 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1097 QualType SubobjectType = Paths->front().back().Base->getType();
1098 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1099 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1100 << LookupRange;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001101
Douglas Gregor7a7be652009-02-03 19:21:40 +00001102 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1103 while (isa<CXXMethodDecl>(*Found) && cast<CXXMethodDecl>(*Found)->isStatic())
1104 ++Found;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001105
Douglas Gregor7a7be652009-02-03 19:21:40 +00001106 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1107
1108 return true;
1109 }
1110
1111 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1112 "Unhandled form of name lookup ambiguity");
1113
1114 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1115 << Name << LookupRange;
1116
1117 std::set<Decl *> DeclsPrinted;
1118 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1119 Path != PathEnd; ++Path) {
1120 Decl *D = *Path->Decls.first;
1121 if (DeclsPrinted.insert(D).second)
1122 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1123 }
1124
1125 delete Paths;
1126 return true;
1127 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
1128
1129 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1130
1131 Decl **DI = reinterpret_cast<Decl **>(Result.First),
1132 **DEnd = reinterpret_cast<Decl **>(Result.Last);
1133
Chris Lattnerb02f5f22009-02-03 21:29:32 +00001134 for (; DI != DEnd; ++DI)
Douglas Gregor7a7be652009-02-03 19:21:40 +00001135 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate)
1136 << getQualifiedName(*DI);
1137
1138 delete[] reinterpret_cast<Decl **>(Result.First);
Douglas Gregor98b27542009-01-17 00:42:38 +00001139
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001140 return true;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001141 }
1142
Douglas Gregor7a7be652009-02-03 19:21:40 +00001143 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregord07474b2009-01-17 01:13:24 +00001144
Douglas Gregor7a7be652009-02-03 19:21:40 +00001145 // We can't reach here.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001146 return true;
1147}
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001148
1149// \brief Add the associated classes and namespaces for
1150// argument-dependent lookup with an argument of class type
1151// (C++ [basic.lookup.koenig]p2).
1152static void
1153addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1154 ASTContext &Context,
1155 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1156 Sema::AssociatedClassSet &AssociatedClasses) {
1157 // C++ [basic.lookup.koenig]p2:
1158 // [...]
1159 // -- If T is a class type (including unions), its associated
1160 // classes are: the class itself; the class of which it is a
1161 // member, if any; and its direct and indirect base
1162 // classes. Its associated namespaces are the namespaces in
1163 // which its associated classes are defined.
1164
1165 // Add the class of which it is a member, if any.
1166 DeclContext *Ctx = Class->getDeclContext();
1167 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1168 AssociatedClasses.insert(EnclosingClass);
1169
1170 // Add the associated namespace for this class.
1171 while (Ctx->isRecord())
1172 Ctx = Ctx->getParent();
1173 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1174 AssociatedNamespaces.insert(EnclosingNamespace);
1175
1176 // Add the class itself. If we've already seen this class, we don't
1177 // need to visit base classes.
1178 if (!AssociatedClasses.insert(Class))
1179 return;
1180
1181 // FIXME: Handle class template specializations
1182
1183 // Add direct and indirect base classes along with their associated
1184 // namespaces.
1185 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1186 Bases.push_back(Class);
1187 while (!Bases.empty()) {
1188 // Pop this class off the stack.
1189 Class = Bases.back();
1190 Bases.pop_back();
1191
1192 // Visit the base classes.
1193 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1194 BaseEnd = Class->bases_end();
1195 Base != BaseEnd; ++Base) {
1196 const RecordType *BaseType = Base->getType()->getAsRecordType();
1197 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1198 if (AssociatedClasses.insert(BaseDecl)) {
1199 // Find the associated namespace for this base class.
1200 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1201 while (BaseCtx->isRecord())
1202 BaseCtx = BaseCtx->getParent();
1203 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1204 AssociatedNamespaces.insert(EnclosingNamespace);
1205
1206 // Make sure we visit the bases of this base class.
1207 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1208 Bases.push_back(BaseDecl);
1209 }
1210 }
1211 }
1212}
1213
1214// \brief Add the associated classes and namespaces for
1215// argument-dependent lookup with an argument of type T
1216// (C++ [basic.lookup.koenig]p2).
1217static void
1218addAssociatedClassesAndNamespaces(QualType T,
1219 ASTContext &Context,
1220 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1221 Sema::AssociatedClassSet &AssociatedClasses) {
1222 // C++ [basic.lookup.koenig]p2:
1223 //
1224 // For each argument type T in the function call, there is a set
1225 // of zero or more associated namespaces and a set of zero or more
1226 // associated classes to be considered. The sets of namespaces and
1227 // classes is determined entirely by the types of the function
1228 // arguments (and the namespace of any template template
1229 // argument). Typedef names and using-declarations used to specify
1230 // the types do not contribute to this set. The sets of namespaces
1231 // and classes are determined in the following way:
1232 T = Context.getCanonicalType(T).getUnqualifiedType();
1233
1234 // -- If T is a pointer to U or an array of U, its associated
1235 // namespaces and classes are those associated with U.
1236 //
1237 // We handle this by unwrapping pointer and array types immediately,
1238 // to avoid unnecessary recursion.
1239 while (true) {
1240 if (const PointerType *Ptr = T->getAsPointerType())
1241 T = Ptr->getPointeeType();
1242 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1243 T = Ptr->getElementType();
1244 else
1245 break;
1246 }
1247
1248 // -- If T is a fundamental type, its associated sets of
1249 // namespaces and classes are both empty.
1250 if (T->getAsBuiltinType())
1251 return;
1252
1253 // -- If T is a class type (including unions), its associated
1254 // classes are: the class itself; the class of which it is a
1255 // member, if any; and its direct and indirect base
1256 // classes. Its associated namespaces are the namespaces in
1257 // which its associated classes are defined.
1258 if (const CXXRecordType *ClassType
1259 = dyn_cast_or_null<CXXRecordType>(T->getAsRecordType())) {
1260 addAssociatedClassesAndNamespaces(ClassType->getDecl(),
1261 Context, AssociatedNamespaces,
1262 AssociatedClasses);
1263 return;
1264 }
1265
1266 // -- If T is an enumeration type, its associated namespace is
1267 // the namespace in which it is defined. If it is class
1268 // member, its associated class is the member’s class; else
1269 // it has no associated class.
1270 if (const EnumType *EnumT = T->getAsEnumType()) {
1271 EnumDecl *Enum = EnumT->getDecl();
1272
1273 DeclContext *Ctx = Enum->getDeclContext();
1274 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1275 AssociatedClasses.insert(EnclosingClass);
1276
1277 // Add the associated namespace for this class.
1278 while (Ctx->isRecord())
1279 Ctx = Ctx->getParent();
1280 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1281 AssociatedNamespaces.insert(EnclosingNamespace);
1282
1283 return;
1284 }
1285
1286 // -- If T is a function type, its associated namespaces and
1287 // classes are those associated with the function parameter
1288 // types and those associated with the return type.
1289 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1290 // Return type
1291 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1292 Context,
1293 AssociatedNamespaces, AssociatedClasses);
1294
1295 const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FunctionType);
1296 if (!Proto)
1297 return;
1298
1299 // Argument types
1300 for (FunctionTypeProto::arg_type_iterator Arg = Proto->arg_type_begin(),
1301 ArgEnd = Proto->arg_type_end();
1302 Arg != ArgEnd; ++Arg)
1303 addAssociatedClassesAndNamespaces(*Arg, Context,
1304 AssociatedNamespaces, AssociatedClasses);
1305
1306 return;
1307 }
1308
1309 // -- If T is a pointer to a member function of a class X, its
1310 // associated namespaces and classes are those associated
1311 // with the function parameter types and return type,
1312 // together with those associated with X.
1313 //
1314 // -- If T is a pointer to a data member of class X, its
1315 // associated namespaces and classes are those associated
1316 // with the member type together with those associated with
1317 // X.
1318 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1319 // Handle the type that the pointer to member points to.
1320 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1321 Context,
1322 AssociatedNamespaces, AssociatedClasses);
1323
1324 // Handle the class type into which this points.
1325 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1326 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1327 Context,
1328 AssociatedNamespaces, AssociatedClasses);
1329
1330 return;
1331 }
1332
1333 // FIXME: What about block pointers?
1334 // FIXME: What about Objective-C message sends?
1335}
1336
1337/// \brief Find the associated classes and namespaces for
1338/// argument-dependent lookup for a call with the given set of
1339/// arguments.
1340///
1341/// This routine computes the sets of associated classes and associated
1342/// namespaces searched by argument-dependent lookup
1343/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1344void
1345Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1346 AssociatedNamespaceSet &AssociatedNamespaces,
1347 AssociatedClassSet &AssociatedClasses) {
1348 AssociatedNamespaces.clear();
1349 AssociatedClasses.clear();
1350
1351 // C++ [basic.lookup.koenig]p2:
1352 // For each argument type T in the function call, there is a set
1353 // of zero or more associated namespaces and a set of zero or more
1354 // associated classes to be considered. The sets of namespaces and
1355 // classes is determined entirely by the types of the function
1356 // arguments (and the namespace of any template template
1357 // argument).
1358 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1359 Expr *Arg = Args[ArgIdx];
1360
1361 if (Arg->getType() != Context.OverloadTy) {
1362 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
1363 AssociatedNamespaces, AssociatedClasses);
1364 continue;
1365 }
1366
1367 // [...] In addition, if the argument is the name or address of a
1368 // set of overloaded functions and/or function templates, its
1369 // associated classes and namespaces are the union of those
1370 // associated with each of the members of the set: the namespace
1371 // in which the function or function template is defined and the
1372 // classes and namespaces associated with its (non-dependent)
1373 // parameter types and return type.
1374 DeclRefExpr *DRE = 0;
1375 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1376 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1377 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1378 } else
1379 DRE = dyn_cast<DeclRefExpr>(Arg);
1380 if (!DRE)
1381 continue;
1382
1383 OverloadedFunctionDecl *Ovl
1384 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1385 if (!Ovl)
1386 continue;
1387
1388 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1389 FuncEnd = Ovl->function_end();
1390 Func != FuncEnd; ++Func) {
1391 FunctionDecl *FDecl = cast<FunctionDecl>(*Func);
1392
1393 // Add the namespace in which this function was defined. Note
1394 // that, if this is a member function, we do *not* consider the
1395 // enclosing namespace of its class.
1396 DeclContext *Ctx = FDecl->getDeclContext();
1397 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1398 AssociatedNamespaces.insert(EnclosingNamespace);
1399
1400 // Add the classes and namespaces associated with the parameter
1401 // types and return type of this function.
1402 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
1403 AssociatedNamespaces, AssociatedClasses);
1404 }
1405 }
1406}