blob: c8ecc171fd587c779dd427b2e6f039f4b46945bc [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"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Basic/LangOptions.h"
22#include "llvm/ADT/STLExtras.h"
Douglas Gregorb9ef0552009-01-16 00:38:09 +000023#include <set>
Douglas Gregor7a7be652009-02-03 19:21:40 +000024#include <vector>
25#include <iterator>
26#include <utility>
27#include <algorithm>
Douglas Gregor78d70132009-01-14 22:20:51 +000028
29using namespace clang;
30
Douglas Gregor7a7be652009-02-03 19:21:40 +000031typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy;
32typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet;
33typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy;
34
35/// UsingDirAncestorCompare - Implements strict weak ordering of
36/// UsingDirectives. It orders them by address of its common ancestor.
37struct UsingDirAncestorCompare {
38
39 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
40 bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const {
41 return U->getCommonAncestor() < Ctx;
42 }
43
44 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
45 bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const {
46 return Ctx < U->getCommonAncestor();
47 }
48
49 /// @brief Compares UsingDirectiveDecl common ancestors.
50 bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const {
51 return U1->getCommonAncestor() < U2->getCommonAncestor();
52 }
53};
54
55/// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs
56/// (ordered by common ancestors), found in namespace NS,
57/// including all found (recursively) in their nominated namespaces.
58void AddNamespaceUsingDirectives(DeclContext *NS,
59 UsingDirectivesTy &UDirs,
60 NamespaceSet &Visited) {
61 DeclContext::udir_iterator I, End;
62
63 for (llvm::tie(I, End) = NS->getUsingDirectives(); I !=End; ++I) {
64 UDirs.push_back(*I);
65 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
66 NamespaceDecl *Nominated = (*I)->getNominatedNamespace();
67 if (Visited.insert(Nominated).second)
68 AddNamespaceUsingDirectives(Nominated, UDirs, /*ref*/ Visited);
69 }
70}
71
72/// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S,
73/// including all found in the namespaces they nominate.
74static void AddScopeUsingDirectives(Scope *S, UsingDirectivesTy &UDirs) {
75 NamespaceSet VisitedNS;
76
77 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
78
79 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx))
80 VisitedNS.insert(NS);
81
82 AddNamespaceUsingDirectives(Ctx, UDirs, /*ref*/ VisitedNS);
83
84 } else {
85 Scope::udir_iterator
86 I = S->using_directives_begin(),
87 End = S->using_directives_end();
88
89 for (; I != End; ++I) {
90 UsingDirectiveDecl * UD = static_cast<UsingDirectiveDecl*>(*I);
91 UDirs.push_back(UD);
92 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
93
94 NamespaceDecl *Nominated = UD->getNominatedNamespace();
95 if (!VisitedNS.count(Nominated)) {
96 VisitedNS.insert(Nominated);
97 AddNamespaceUsingDirectives(Nominated, UDirs, /*ref*/ VisitedNS);
98 }
99 }
100 }
101}
102
Douglas Gregor78d70132009-01-14 22:20:51 +0000103/// MaybeConstructOverloadSet - Name lookup has determined that the
104/// elements in [I, IEnd) have the name that we are looking for, and
105/// *I is a match for the namespace. This routine returns an
106/// appropriate Decl for name lookup, which may either be *I or an
Douglas Gregor7a7be652009-02-03 19:21:40 +0000107/// OverloadedFunctionDecl that represents the overloaded functions in
Douglas Gregor78d70132009-01-14 22:20:51 +0000108/// [I, IEnd).
109///
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000110/// The existance of this routine is temporary; users of LookupResult
111/// should be able to handle multiple results, to deal with cases of
Douglas Gregor78d70132009-01-14 22:20:51 +0000112/// ambiguity and overloaded functions without needing to create a
113/// Decl node.
114template<typename DeclIterator>
115static Decl *
116MaybeConstructOverloadSet(ASTContext &Context,
117 DeclIterator I, DeclIterator IEnd) {
118 assert(I != IEnd && "Iterator range cannot be empty");
119 assert(!isa<OverloadedFunctionDecl>(*I) &&
120 "Cannot have an overloaded function");
121
122 if (isa<FunctionDecl>(*I)) {
123 // If we found a function, there might be more functions. If
124 // so, collect them into an overload set.
125 DeclIterator Last = I;
126 OverloadedFunctionDecl *Ovl = 0;
127 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
128 if (!Ovl) {
129 // FIXME: We leak this overload set. Eventually, we want to
130 // stop building the declarations for these overload sets, so
131 // there will be nothing to leak.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000132 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
Douglas Gregor78d70132009-01-14 22:20:51 +0000133 (*I)->getDeclName());
134 Ovl->addOverload(cast<FunctionDecl>(*I));
135 }
136 Ovl->addOverload(cast<FunctionDecl>(*Last));
137 }
138
139 // If we had more than one function, we built an overload
140 // set. Return it.
141 if (Ovl)
142 return Ovl;
143 }
144
145 return *I;
146}
147
Douglas Gregor7a7be652009-02-03 19:21:40 +0000148/// Merges together multiple LookupResults dealing with duplicated Decl's.
149static Sema::LookupResult
150MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
151 typedef Sema::LookupResult LResult;
152 typedef llvm::SmallVector<NamedDecl*, 3> DeclsVecTy;
153
154 DeclsVecTy FoundDecls;
155 OverloadedFunctionDecl *FoundOverloaded = 0;
156
157 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
158 for (; I != End; ++I) {
159
160 switch (I->getKind()) {
161 case LResult::NotFound:
162 assert(false &&
163 "Should be always successful name lookup result here.");
164 break;
165
166 case LResult::AmbiguousReference:
167 assert(false &&
168 "Shouldn't get ambiguous reference here.");
169 break;
170
171 case LResult::Found:
172 FoundDecls.push_back(cast<NamedDecl>(I->getAsDecl()));
173 break;
174
175 case LResult::AmbiguousBaseSubobjectTypes:
176 case LResult::AmbiguousBaseSubobjects: {
177 LResult Ambig = *I;
178 // Free rest of OverloadedFunctionDecl, and other BasePaths
179 // stored in LookupResults.
180#if 0
181 // FIXME:
182 // It should not happen, when we look start in each DeclContext only once.
183 // See FIXME in CppLookupName.
184 assert(Results.size() == 1 && "Multiple LookupResults should be not case "
185 "here, since using-directives can't occur at class scope.");
186#else
187 if (FoundOverloaded)
188 FoundOverloaded->Destroy(Context);
189
190 for (++I; I != End; ++I) {
191 if (I->getKind() == LResult::FoundOverloaded)
192 cast<OverloadedFunctionDecl>(I->getAsDecl())->Destroy(Context);
193 else if (BasePaths *Paths = I->getBasePaths())
194 delete Paths;
195 assert(I->getKind() != LResult::AmbiguousReference &&
196 "Shouldn't get ambiguous reference here.");
197 }
198#endif
199 return Ambig;
200 }
201
202 case LResult::FoundOverloaded:
203 if (FoundOverloaded) {
204 // We have one spare OverloadedFunctionDecl already, so we store
205 // its function decls.
206#if 0
207 FIXME: As soon as, stop call MaybeConstructOverloadSet here,
208 which requires iterator::reference of type NamedDecl*, FoundDecls
209 can be SmallVector<Decl*, >
210 or when Lookup*Name() starts return NamedDecl's* instead of Decl's
211
212 this will work:
213 std::copy(I->begin(), I->end(), std::back_inserter(FoundDecls));
214#else
215 Sema::LookupResult::iterator OI = I->begin(), OEnd = I->end();
216 for (; OI != OEnd; ++OI)
217 FoundDecls.push_back(cast<NamedDecl>(*OI));
218#endif
219 } else {
220 // First time we found OverloadedFunctionDecl, we want to conserve
221 // it, and possibly add other found Decls later.
222 FoundOverloaded = cast<OverloadedFunctionDecl>(I->getAsDecl());
223 }
224 break;
225 }
226 }
227
228 // Remove duplicated Decl pointing at same Decl, this might be case
229 // for code like:
230 //
231 // namespace A { int i; }
232 // namespace B { using namespace A; }
233 // namespace C { using namespace A; }
234 //
235 // void foo() {
236 // using namespace B;
237 // using namespace C;
238 // ++i; // finds A::i, from both namespace B and C at global scope
239 // }
240 //
241 // C++ [namespace.qual].p3:
242 // The same declaration found more than once is not an ambiguity
243 // (because it is still a unique declaration).
244 //
245 // FIXME: At this point happens too, because we are doing redundant lookups.
246 //
247 DeclsVecTy::iterator DI = FoundDecls.begin(), DEnd = FoundDecls.end();
248 // FIXME: Using SmallPtrSet instead would be better, once OverloadedFunctionDecl
249 // dies.
250 std::sort(DI, DEnd);
251 DEnd = std::unique(DI, DEnd);
252
253 if (FoundOverloaded) {
254 // We found overloaded functions result. We want to add any other
255 // found decls, that are not already in FoundOverloaded, and are functions
256 // or methods.
257 OverloadedFunctionDecl::function_iterator
258 FBegin = FoundOverloaded->function_begin(),
259 FEnd = FoundOverloaded->function_end();
260 // FIXME: This is O(n^2)!
Chris Lattnerb02f5f22009-02-03 21:29:32 +0000261 for (; DI < DEnd; ++DI) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000262 FunctionDecl *Fun = dyn_cast<FunctionDecl>(*DI);
263 if (Fun && (std::find(FBegin, FEnd, Fun) != FEnd)) { /* Skip.*/ }
264 else DEnd = std::remove(DI, DEnd, *DI);
265 }
266
267 for (DI = FoundDecls.begin(); DI != DEnd; ++DI)
268 FoundOverloaded->addOverload(cast<FunctionDecl>(*DI));
269
270 return LResult::CreateLookupResult(Context, FoundOverloaded);
271 } else if (std::size_t FoundLen = std::distance(FoundDecls.begin(), DEnd)) {
272 // We might found multiple TagDecls pointing at same definition.
273 if (TagDecl *R = dyn_cast<TagDecl>(*FoundDecls.begin())) {
274 TagDecl *Canonical = Context.getCanonicalDecl(R);
275 DeclsVecTy::iterator RI = FoundDecls.begin(), REnd = DEnd;
276 for (;;) {
277 ++RI;
278 if (RI == REnd) {
279 FoundLen = 1;
280 break;
281 }
282 R = dyn_cast<TagDecl>(*RI);
283 if (R && Canonical == Context.getCanonicalDecl(R)) { /* Skip */}
284 else break;
285 }
286 }
287
288 // We might find FunctionDecls in two (or more) distinct DeclContexts.
289 // 3.4.1.p1 ... Name lookup may associate more than one declaration with
290 // a name if it finds the name to be a function name; the declarations
291 // are said to form a set of overloaded functions (13.1).
292 // Overload resolution (13.3) takes place after name lookup has succeeded.
293
294 Decl *D = MaybeConstructOverloadSet(Context, DI, DEnd);
295 if ((FoundLen == 1) || isa<OverloadedFunctionDecl>(D))
296 return LResult::CreateLookupResult(Context, D);
297
298 // Found multiple Decls, it is ambiguous reference.
299 return LResult::CreateLookupResult(Context, FoundDecls.begin(), FoundLen);
300 }
301
302 LResult Result = LResult::CreateLookupResult(Context, 0);
303 return Result;
304}
305
306// Retrieve the set of identifier namespaces that correspond to a
307// specific kind of name lookup.
308inline unsigned
309getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
310 bool CPlusPlus) {
311 unsigned IDNS = 0;
312 switch (NameKind) {
313 case Sema::LookupOrdinaryName:
314 IDNS = Decl::IDNS_Ordinary;
315 if (CPlusPlus)
316 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
317 break;
318
319 case Sema::LookupTagName:
320 IDNS = Decl::IDNS_Tag;
321 break;
322
323 case Sema::LookupMemberName:
324 IDNS = Decl::IDNS_Member;
325 if (CPlusPlus)
326 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
327 break;
328
329 case Sema::LookupNestedNameSpecifierName:
330 case Sema::LookupNamespaceName:
331 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
332 break;
333 }
334 return IDNS;
335}
336
337// Return qualified name for Decl D, like A::B::i, for i being member of
338// namespace A::B.
339std::string
340getQualifiedName(Decl *D) {
341 std::vector<std::string> Names;
342 std::string QualName;
343 DeclContext *Ctx = D->getDeclContext();
344
345 if (Ctx->isFunctionOrMethod())
346 return cast<NamedDecl>(D)->getNameAsString();
347
348 while (Ctx) {
349 if (Ctx->isFunctionOrMethod()) {
350 // FIXME: That probably is happend, because D was member of local
351 // scope class/struct/union. How do we handle this case?
352 break;
353 }
354 if (NamedDecl *ND = dyn_cast<NamedDecl>(Ctx)) {
355 Names.push_back(ND->getNameAsString());
356 } else {
357 break;
358 }
359 Ctx = Ctx->getParent();
360 }
361 for (std::vector<std::string>::reverse_iterator I= Names.rbegin(), End =Names.rend(); I!=End; ++I)
362 QualName += *I + "::";
363 QualName += cast<NamedDecl>(D)->getNameAsString();
364 return QualName;
365}
366
367Sema::LookupResult
368Sema::LookupResult::CreateLookupResult(ASTContext &Context, Decl *D) {
369 LookupResult Result;
370 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
371 OverloadedDeclSingleDecl : SingleDecl;
372 Result.First = reinterpret_cast<uintptr_t>(D);
373 Result.Last = 0;
374 Result.Context = &Context;
375 return Result;
376}
377
Douglas Gregor6beddfe2009-01-15 02:19:31 +0000378/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregord07474b2009-01-17 01:13:24 +0000379Sema::LookupResult
380Sema::LookupResult::CreateLookupResult(ASTContext &Context,
381 IdentifierResolver::iterator F,
382 IdentifierResolver::iterator L) {
383 LookupResult Result;
384 Result.Context = &Context;
385
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000386 if (F != L && isa<FunctionDecl>(*F)) {
387 IdentifierResolver::iterator Next = F;
388 ++Next;
389 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000390 Result.StoredKind = OverloadedDeclFromIdResolver;
391 Result.First = F.getAsOpaqueValue();
392 Result.Last = L.getAsOpaqueValue();
393 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000394 }
395 }
396
Douglas Gregord07474b2009-01-17 01:13:24 +0000397 Result.StoredKind = SingleDecl;
398 Result.First = reinterpret_cast<uintptr_t>(*F);
399 Result.Last = 0;
400 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000401}
402
Douglas Gregord07474b2009-01-17 01:13:24 +0000403Sema::LookupResult
404Sema::LookupResult::CreateLookupResult(ASTContext &Context,
405 DeclContext::lookup_iterator F,
406 DeclContext::lookup_iterator L) {
407 LookupResult Result;
408 Result.Context = &Context;
409
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000410 if (F != L && isa<FunctionDecl>(*F)) {
411 DeclContext::lookup_iterator Next = F;
412 ++Next;
413 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000414 Result.StoredKind = OverloadedDeclFromDeclContext;
415 Result.First = reinterpret_cast<uintptr_t>(F);
416 Result.Last = reinterpret_cast<uintptr_t>(L);
417 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000418 }
419 }
420
Douglas Gregord07474b2009-01-17 01:13:24 +0000421 Result.StoredKind = SingleDecl;
422 Result.First = reinterpret_cast<uintptr_t>(*F);
423 Result.Last = 0;
424 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000425}
426
Douglas Gregor78d70132009-01-14 22:20:51 +0000427/// @brief Determine the result of name lookup.
428Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
429 switch (StoredKind) {
430 case SingleDecl:
431 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
432
Douglas Gregor7a7be652009-02-03 19:21:40 +0000433 case OverloadedDeclSingleDecl:
Douglas Gregor78d70132009-01-14 22:20:51 +0000434 case OverloadedDeclFromIdResolver:
435 case OverloadedDeclFromDeclContext:
436 return FoundOverloaded;
437
Douglas Gregor7a7be652009-02-03 19:21:40 +0000438 case AmbiguousLookupStoresBasePaths:
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000439 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000440
441 case AmbiguousLookupStoresDecls:
442 return AmbiguousReference;
Douglas Gregor78d70132009-01-14 22:20:51 +0000443 }
444
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000445 // We can't ever get here.
446 return NotFound;
Douglas Gregor78d70132009-01-14 22:20:51 +0000447}
448
449/// @brief Converts the result of name lookup into a single (possible
450/// NULL) pointer to a declaration.
451///
452/// The resulting declaration will either be the declaration we found
453/// (if only a single declaration was found), an
454/// OverloadedFunctionDecl (if an overloaded function was found), or
455/// NULL (if no declaration was found). This conversion must not be
456/// used anywhere where name lookup could result in an ambiguity.
457///
458/// The OverloadedFunctionDecl conversion is meant as a stop-gap
459/// solution, since it causes the OverloadedFunctionDecl to be
460/// leaked. FIXME: Eventually, there will be a better way to iterate
461/// over the set of overloaded functions returned by name lookup.
462Decl *Sema::LookupResult::getAsDecl() const {
463 switch (StoredKind) {
464 case SingleDecl:
465 return reinterpret_cast<Decl *>(First);
466
467 case OverloadedDeclFromIdResolver:
468 return MaybeConstructOverloadSet(*Context,
469 IdentifierResolver::iterator::getFromOpaqueValue(First),
470 IdentifierResolver::iterator::getFromOpaqueValue(Last));
471
472 case OverloadedDeclFromDeclContext:
473 return MaybeConstructOverloadSet(*Context,
474 reinterpret_cast<DeclContext::lookup_iterator>(First),
475 reinterpret_cast<DeclContext::lookup_iterator>(Last));
476
Douglas Gregor7a7be652009-02-03 19:21:40 +0000477 case OverloadedDeclSingleDecl:
478 return reinterpret_cast<OverloadedFunctionDecl*>(First);
479
480 case AmbiguousLookupStoresDecls:
481 case AmbiguousLookupStoresBasePaths:
Douglas Gregor78d70132009-01-14 22:20:51 +0000482 assert(false &&
483 "Name lookup returned an ambiguity that could not be handled");
484 break;
485 }
486
487 return 0;
488}
489
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000490/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor7a7be652009-02-03 19:21:40 +0000491/// name lookup, or null.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000492BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000493 if (StoredKind == AmbiguousLookupStoresBasePaths)
494 return reinterpret_cast<BasePaths *>(First);
495 return 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000496}
497
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000498Sema::LookupResult::iterator::reference
499Sema::LookupResult::iterator::operator*() const {
500 switch (Result->StoredKind) {
501 case SingleDecl:
502 return reinterpret_cast<Decl*>(Current);
503
Douglas Gregor7a7be652009-02-03 19:21:40 +0000504 case OverloadedDeclSingleDecl:
505 return *reinterpret_cast<Decl**>(Current);
506
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000507 case OverloadedDeclFromIdResolver:
508 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
509
510 case OverloadedDeclFromDeclContext:
511 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000512
513 case AmbiguousLookupStoresDecls:
514 case AmbiguousLookupStoresBasePaths:
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000515 assert(false && "Cannot look into ambiguous lookup results");
516 break;
517 }
518
519 return 0;
520}
521
522Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
523 switch (Result->StoredKind) {
524 case SingleDecl:
525 Current = reinterpret_cast<uintptr_t>((Decl*)0);
526 break;
527
Douglas Gregor7a7be652009-02-03 19:21:40 +0000528 case OverloadedDeclSingleDecl: {
529 Decl ** I = reinterpret_cast<Decl**>(Current);
530 ++I;
531 Current = reinterpret_cast<uintptr_t>(I);
532 }
533
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000534 case OverloadedDeclFromIdResolver: {
535 IdentifierResolver::iterator I
536 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
537 ++I;
538 Current = I.getAsOpaqueValue();
539 break;
540 }
541
542 case OverloadedDeclFromDeclContext: {
543 DeclContext::lookup_iterator I
544 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
545 ++I;
546 Current = reinterpret_cast<uintptr_t>(I);
547 break;
548 }
549
Douglas Gregor7a7be652009-02-03 19:21:40 +0000550 case AmbiguousLookupStoresDecls:
551 case AmbiguousLookupStoresBasePaths:
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000552 assert(false && "Cannot look into ambiguous lookup results");
553 break;
554 }
555
556 return *this;
557}
558
559Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000560 assert(!isAmbiguous() && "Lookup into an ambiguous result");
561 if (StoredKind != OverloadedDeclSingleDecl)
562 return iterator(this, First);
563 OverloadedFunctionDecl * Ovl =
564 reinterpret_cast<OverloadedFunctionDecl*>(First);
565 return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000566}
567
568Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000569 assert(!isAmbiguous() && "Lookup into an ambiguous result");
570 if (StoredKind != OverloadedDeclSingleDecl)
571 return iterator(this, Last);
572 OverloadedFunctionDecl * Ovl =
573 reinterpret_cast<OverloadedFunctionDecl*>(First);
574 return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000575}
576
Douglas Gregor7a7be652009-02-03 19:21:40 +0000577static bool isFunctionLocalScope(Scope *S) {
578 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
579 return Ctx->isFunctionOrMethod();
580 return true;
581}
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000582
Douglas Gregor7a7be652009-02-03 19:21:40 +0000583std::pair<bool, Sema::LookupResult>
584Sema::CppLookupName(Scope *S, DeclarationName Name,
585 LookupNameKind NameKind, bool RedeclarationOnly) {
586 assert(getLangOptions().CPlusPlus &&
587 "Can perform only C++ lookup");
588unsigned IDNS
589 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
590 Scope *Initial = S;
591 IdentifierResolver::iterator
592 I = IdResolver.begin(Name),
593 IEnd = IdResolver.end();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000594
Douglas Gregor7a7be652009-02-03 19:21:40 +0000595 // First we lookup local scope.
596 // We don't consider using-dirctives, as per 7.3.4.p1 [namespace.udir]
597 // ...During unqualified name lookup (3.4.1), the names appear as if
598 // they were declared in the nearest enclosing namespace which contains
599 // both the using-directive and the nominated namespace.
600 // [Note: in this context, “contains” means “contains directly or
601 // indirectly”.
602 //
603 // For example:
604 // namespace A { int i; }
605 // void foo() {
606 // int i;
607 // {
608 // using namespace A;
609 // ++i; // finds local 'i', A::i appears at global scope
610 // }
611 // }
612 //
613 for (; S && isFunctionLocalScope(S); S = S->getParent()) {
614 // Check whether the IdResolver has anything in this scope.
615 for (; I != IEnd && S->isDeclScope(*I); ++I) {
616 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
617 // We found something. Look for anything else in our scope
618 // with this same name and in an acceptable identifier
619 // namespace, so that we can construct an overload set if we
620 // need to.
621 IdentifierResolver::iterator LastI = I;
622 for (++LastI; LastI != IEnd; ++LastI) {
623 if (!S->isDeclScope(*LastI))
624 break;
625 }
626 LookupResult Result =
627 LookupResult::CreateLookupResult(Context, I, LastI);
628 return std::make_pair(true, Result);
629 }
630 }
631 // NB: Icky, we need to look in function scope, but we need to check its
632 // parent DeclContext (instead S->getParent()) for member name lookup,
633 // in case it is out of line method definition. Like in:
634 //
635 // class C {
636 // int i;
637 // void foo();
638 // };
639 //
640 // C::foo() {
641 // (void) i;
642 // }
643 //
644 // FIXME: Maybe we should do member name lookup here instead?
645 if (S->getEntity() && isFunctionLocalScope(S))
646 break;
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000647 }
Douglas Gregor7a7be652009-02-03 19:21:40 +0000648
649 // Collect UsingDirectiveDecls in all scopes, and recursivly all
650 // nominated namespaces by those using-directives.
651 // UsingDirectives are pushed to heap, in common ancestor pointer
652 // value order.
653 // FIXME: Cache this sorted list in Scope structure, and maybe
654 // DeclContext, so we don't build it for each lookup!
655 UsingDirectivesTy UDirs;
656 for (Scope *SC = Initial; SC; SC = SC->getParent())
657 AddScopeUsingDirectives(SC, UDirs);
658
659 // Sort heapified UsingDirectiveDecls.
660 std::sort_heap(UDirs.begin(), UDirs.end());
661
662 // Lookup namespace scope, global scope, or possibly (CXX)Record DeclContext
663 // for member name lookup.
664 // Unqualified name lookup in C++ requires looking into scopes
665 // that aren't strictly lexical, and therefore we walk through the
666 // context as well as walking through the scopes.
667 for (; S; S = S->getParent()) {
668 LookupResultsTy LookupResults;
669 bool LookedInCtx = false;
670
671 // Check whether the IdResolver has anything in this scope.
672 for (; I != IEnd && S->isDeclScope(*I); ++I) {
673 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
674 // We found something. Look for anything else in our scope
675 // with this same name and in an acceptable identifier
676 // namespace, so that we can construct an overload set if we
677 // need to.
678 IdentifierResolver::iterator LastI = I;
679 for (++LastI; LastI != IEnd; ++LastI) {
680 if (!S->isDeclScope(*LastI))
681 break;
682 }
683
684 // We store name lookup result, and continue trying to look into
685 // associated context, and maybe namespaces nominated by
686 // using-directives.
687 LookupResults.push_back(
688 LookupResult::CreateLookupResult(Context, I, LastI));
689 break;
690 }
691 }
692
693 // If there is an entity associated with this scope, it's a
694 // DeclContext. We might need to perform qualified lookup into
695 // it, or namespaces nominated by using-directives.
696 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
697
698 if (Ctx && isa<TranslationUnitDecl>(Ctx)) {
699 UsingDirectivesTy::const_iterator UI, UEnd;
700 // For each UsingDirectiveDecl, which common ancestor is equal
701 // to Ctx, we preform qualified name lookup into namespace nominated
702 // by it.
703 llvm::tie(UI, UEnd) =
704 std::equal_range(UDirs.begin(), UDirs.end(), Ctx,
705 UsingDirAncestorCompare());
706 for (; UI != UEnd; ++UI) {
707 // FIXME: We will have to ensure, that we won't consider
708 // again using-directives during qualified name lookup!
709 // (Once using-directives support for qualified name lookup gets
710 // implemented).
711 if (LookupResult R = LookupQualifiedName((*UI)->getNominatedNamespace(),
712 Name, NameKind, RedeclarationOnly))
713 LookupResults.push_back(R);
714 }
715 LookupResult Result;
716 if ((Result = MergeLookupResults(Context, LookupResults)) ||
717 RedeclarationOnly) {
718 return std::make_pair(true, Result);
719 }
720 }
721
722 // FIXME: We're performing redundant lookups here, where the
723 // scope stack mirrors the semantic nested of classes and
724 // namespaces. We can save some work by checking the lexical
725 // scope against the semantic scope and avoiding any lookups
726 // when they are the same.
727 // FIXME: In some cases, we know that every name that could be
728 // found by this qualified name lookup will also be on the
729 // identifier chain. For example, inside a class without any
730 // base classes, we never need to perform qualified lookup
731 // because all of the members are on top of the identifier
732 // chain. However, we cannot perform this optimization when the
733 // lexical and semantic scopes don't line up, e.g., in an
734 // out-of-line member definition.
735 while (Ctx && Ctx->isFunctionOrMethod())
736 Ctx = Ctx->getParent();
737 while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
738 LookedInCtx = true;
739 // Look for declarations of this name in this scope.
740 if (LookupResult R = LookupQualifiedName(Ctx, Name, NameKind,
741 RedeclarationOnly))
742 // We store that, to investigate futher, wheather reference
743 // to this Decl is no ambiguous.
744 LookupResults.push_back(R);
745
746 if (Ctx->isNamespace()) {
747 // For each UsingDirectiveDecl, which common ancestor is equal
748 // to Ctx, we preform qualified name lookup into namespace nominated
749 // by it.
750 UsingDirectivesTy::const_iterator UI, UEnd;
751 llvm::tie(UI, UEnd) =
752 std::equal_range(UDirs.begin(), UDirs.end(), Ctx,
753 UsingDirAncestorCompare());
754 for (; UI != UEnd; ++UI) {
755 // FIXME: We will have to ensure, that we won't consider
756 // again using-directives during qualified name lookup!
757 // (Once using-directives support for qualified name lookup gets
758 // implemented).
759 LookupResult R = LookupQualifiedName((*UI)->getNominatedNamespace(),
760 Name, NameKind,
761 RedeclarationOnly);
762 if (R)
763 LookupResults.push_back(R);
764 }
765 }
766 LookupResult Result;
767 if ((Result = MergeLookupResults(Context, LookupResults)) ||
768 (RedeclarationOnly && !Ctx->isTransparentContext())) {
769 return std::make_pair(true, Result);
770 }
771 Ctx = Ctx->getParent();
772 }
773
774 if (!(LookedInCtx || LookupResults.empty())) {
775 // We didn't Performed lookup in Scope entity, so we return
776 // result form IdentifierResolver.
777 assert((LookupResults.size() == 1) && "Wrong size!");
778 return std::make_pair(true, LookupResults.front());
779 }
780 }
781 return std::make_pair(false, LookupResult());
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000782}
783
Douglas Gregor78d70132009-01-14 22:20:51 +0000784/// @brief Perform unqualified name lookup starting from a given
785/// scope.
786///
787/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
788/// used to find names within the current scope. For example, 'x' in
789/// @code
790/// int x;
791/// int f() {
792/// return x; // unqualified name look finds 'x' in the global scope
793/// }
794/// @endcode
795///
796/// Different lookup criteria can find different names. For example, a
797/// particular scope can have both a struct and a function of the same
798/// name, and each can be found by certain lookup criteria. For more
799/// information about lookup criteria, see the documentation for the
800/// class LookupCriteria.
801///
802/// @param S The scope from which unqualified name lookup will
803/// begin. If the lookup criteria permits, name lookup may also search
804/// in the parent scopes.
805///
806/// @param Name The name of the entity that we are searching for.
807///
808/// @param Criteria The criteria that this routine will use to
809/// determine which names are visible and which names will be
810/// found. Note that name lookup will find a name that is visible by
811/// the given criteria, but the entity itself may not be semantically
812/// correct or even the kind of entity expected based on the
813/// lookup. For example, searching for a nested-name-specifier name
814/// might result in an EnumDecl, which is visible but is not permitted
815/// as a nested-name-specifier in C++03.
816///
817/// @returns The result of name lookup, which includes zero or more
818/// declarations and possibly additional information used to diagnose
819/// ambiguities.
820Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000821Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
822 bool RedeclarationOnly) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000823 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000824
825 if (!getLangOptions().CPlusPlus) {
826 // Unqualified name lookup in C/Objective-C is purely lexical, so
827 // search in the declarations attached to the name.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000828 unsigned IDNS = 0;
829 switch (NameKind) {
830 case Sema::LookupOrdinaryName:
831 IDNS = Decl::IDNS_Ordinary;
832 break;
Douglas Gregor78d70132009-01-14 22:20:51 +0000833
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000834 case Sema::LookupTagName:
835 IDNS = Decl::IDNS_Tag;
836 break;
837
838 case Sema::LookupMemberName:
839 IDNS = Decl::IDNS_Member;
840 break;
841
842 case Sema::LookupNestedNameSpecifierName:
843 case Sema::LookupNamespaceName:
844 assert(false && "C does not perform these kinds of name lookup");
845 break;
846 }
847
Douglas Gregor78d70132009-01-14 22:20:51 +0000848 // Scan up the scope chain looking for a decl that matches this
849 // identifier that is in the appropriate namespace. This search
850 // should not take long, as shadowing of names is uncommon, and
851 // deep shadowing is extremely uncommon.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000852 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
853 IEnd = IdResolver.end();
854 I != IEnd; ++I)
855 if ((*I)->isInIdentifierNamespace(IDNS))
Douglas Gregord07474b2009-01-17 01:13:24 +0000856 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregor78d70132009-01-14 22:20:51 +0000857 } else {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000858 // Perform C++ unqualified name lookup.
859 std::pair<bool, LookupResult> MaybeResult =
860 CppLookupName(S, Name, NameKind, RedeclarationOnly);
861 if (MaybeResult.first)
862 return MaybeResult.second;
Douglas Gregor78d70132009-01-14 22:20:51 +0000863 }
864
865 // If we didn't find a use of this identifier, and if the identifier
866 // corresponds to a compiler builtin, create the decl object for the builtin
867 // now, injecting it into translation unit scope, and return it.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000868 if (NameKind == LookupOrdinaryName) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000869 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000870 if (II) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000871 // If this is a builtin on this (or all) targets, create the decl.
872 if (unsigned BuiltinID = II->getBuiltinID())
Douglas Gregord07474b2009-01-17 01:13:24 +0000873 return LookupResult::CreateLookupResult(Context,
Douglas Gregor78d70132009-01-14 22:20:51 +0000874 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
875 S));
876 }
877 if (getLangOptions().ObjC1 && II) {
878 // @interface and @compatibility_alias introduce typedef-like names.
879 // Unlike typedef's, they can only be introduced at file-scope (and are
880 // therefore not scoped decls). They can, however, be shadowed by
881 // other names in IDNS_Ordinary.
882 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
883 if (IDI != ObjCInterfaceDecls.end())
Douglas Gregord07474b2009-01-17 01:13:24 +0000884 return LookupResult::CreateLookupResult(Context, IDI->second);
Douglas Gregor78d70132009-01-14 22:20:51 +0000885 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
886 if (I != ObjCAliasDecls.end())
Douglas Gregord07474b2009-01-17 01:13:24 +0000887 return LookupResult::CreateLookupResult(Context,
888 I->second->getClassInterface());
Douglas Gregor78d70132009-01-14 22:20:51 +0000889 }
890 }
Douglas Gregord07474b2009-01-17 01:13:24 +0000891 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000892}
893
894/// @brief Perform qualified name lookup into a given context.
895///
896/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
897/// names when the context of those names is explicit specified, e.g.,
898/// "std::vector" or "x->member".
899///
900/// Different lookup criteria can find different names. For example, a
901/// particular scope can have both a struct and a function of the same
902/// name, and each can be found by certain lookup criteria. For more
903/// information about lookup criteria, see the documentation for the
904/// class LookupCriteria.
905///
906/// @param LookupCtx The context in which qualified name lookup will
907/// search. If the lookup criteria permits, name lookup may also search
908/// in the parent contexts or (for C++ classes) base classes.
909///
910/// @param Name The name of the entity that we are searching for.
911///
912/// @param Criteria The criteria that this routine will use to
913/// determine which names are visible and which names will be
914/// found. Note that name lookup will find a name that is visible by
915/// the given criteria, but the entity itself may not be semantically
916/// correct or even the kind of entity expected based on the
917/// lookup. For example, searching for a nested-name-specifier name
918/// might result in an EnumDecl, which is visible but is not permitted
919/// as a nested-name-specifier in C++03.
920///
921/// @returns The result of name lookup, which includes zero or more
922/// declarations and possibly additional information used to diagnose
923/// ambiguities.
924Sema::LookupResult
925Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000926 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000927 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
928
Douglas Gregord07474b2009-01-17 01:13:24 +0000929 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000930
931 // If we're performing qualified name lookup (e.g., lookup into a
932 // struct), find fields as part of ordinary name lookup.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000933 unsigned IDNS
934 = getIdentifierNamespacesFromLookupNameKind(NameKind,
935 getLangOptions().CPlusPlus);
936 if (NameKind == LookupOrdinaryName)
937 IDNS |= Decl::IDNS_Member;
Douglas Gregor78d70132009-01-14 22:20:51 +0000938
939 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor78d70132009-01-14 22:20:51 +0000940 DeclContext::lookup_iterator I, E;
941 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000942 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregord07474b2009-01-17 01:13:24 +0000943 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregor78d70132009-01-14 22:20:51 +0000944
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000945 // If this isn't a C++ class or we aren't allowed to look into base
946 // classes, we're done.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000947 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregord07474b2009-01-17 01:13:24 +0000948 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000949
950 // Perform lookup into our base classes.
951 BasePaths Paths;
Douglas Gregorb9ef0552009-01-16 00:38:09 +0000952 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000953
954 // Look for this member in our base classes
955 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000956 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregord07474b2009-01-17 01:13:24 +0000957 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000958
959 // C++ [class.member.lookup]p2:
960 // [...] If the resulting set of declarations are not all from
961 // sub-objects of the same type, or the set has a nonstatic member
962 // and includes members from distinct sub-objects, there is an
963 // ambiguity and the program is ill-formed. Otherwise that set is
964 // the result of the lookup.
965 // FIXME: support using declarations!
966 QualType SubobjectType;
Daniel Dunbarddebeca2009-01-15 18:32:35 +0000967 int SubobjectNumber = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000968 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
969 Path != PathEnd; ++Path) {
970 const BasePathElement &PathElement = Path->back();
971
972 // Determine whether we're looking at a distinct sub-object or not.
973 if (SubobjectType.isNull()) {
974 // This is the first subobject we've looked at. Record it's type.
975 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
976 SubobjectNumber = PathElement.SubobjectNumber;
977 } else if (SubobjectType
978 != Context.getCanonicalType(PathElement.Base->getType())) {
979 // We found members of the given name in two subobjects of
980 // different types. This lookup is ambiguous.
981 BasePaths *PathsOnHeap = new BasePaths;
982 PathsOnHeap->swap(Paths);
Douglas Gregord07474b2009-01-17 01:13:24 +0000983 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000984 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
985 // We have a different subobject of the same type.
986
987 // C++ [class.member.lookup]p5:
988 // A static member, a nested type or an enumerator defined in
989 // a base class T can unambiguously be found even if an object
990 // has more than one base class subobject of type T.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000991 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000992 if (isa<VarDecl>(FirstDecl) ||
993 isa<TypeDecl>(FirstDecl) ||
994 isa<EnumConstantDecl>(FirstDecl))
995 continue;
996
997 if (isa<CXXMethodDecl>(FirstDecl)) {
998 // Determine whether all of the methods are static.
999 bool AllMethodsAreStatic = true;
1000 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1001 Func != Path->Decls.second; ++Func) {
1002 if (!isa<CXXMethodDecl>(*Func)) {
1003 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1004 break;
1005 }
1006
1007 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1008 AllMethodsAreStatic = false;
1009 break;
1010 }
1011 }
1012
1013 if (AllMethodsAreStatic)
1014 continue;
1015 }
1016
1017 // We have found a nonstatic member name in multiple, distinct
1018 // subobjects. Name lookup is ambiguous.
1019 BasePaths *PathsOnHeap = new BasePaths;
1020 PathsOnHeap->swap(Paths);
Douglas Gregord07474b2009-01-17 01:13:24 +00001021 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001022 }
1023 }
1024
1025 // Lookup in a base class succeeded; return these results.
1026
1027 // If we found a function declaration, return an overload set.
1028 if (isa<FunctionDecl>(*Paths.front().Decls.first))
Douglas Gregord07474b2009-01-17 01:13:24 +00001029 return LookupResult::CreateLookupResult(Context,
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001030 Paths.front().Decls.first, Paths.front().Decls.second);
1031
1032 // We found a non-function declaration; return a single declaration.
Douglas Gregord07474b2009-01-17 01:13:24 +00001033 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregor78d70132009-01-14 22:20:51 +00001034}
1035
1036/// @brief Performs name lookup for a name that was parsed in the
1037/// source code, and may contain a C++ scope specifier.
1038///
1039/// This routine is a convenience routine meant to be called from
1040/// contexts that receive a name and an optional C++ scope specifier
1041/// (e.g., "N::M::x"). It will then perform either qualified or
1042/// unqualified name lookup (with LookupQualifiedName or LookupName,
1043/// respectively) on the given name and return those results.
1044///
1045/// @param S The scope from which unqualified name lookup will
1046/// begin.
1047///
1048/// @param SS An optional C++ scope-specified, e.g., "::N::M".
1049///
1050/// @param Name The name of the entity that name lookup will
1051/// search for.
1052///
Douglas Gregor78d70132009-01-14 22:20:51 +00001053/// @returns The result of qualified or unqualified name lookup.
1054Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001055Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1056 DeclarationName Name, LookupNameKind NameKind,
1057 bool RedeclarationOnly) {
1058 if (SS) {
1059 if (SS->isInvalid())
1060 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +00001061
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001062 if (SS->isSet())
1063 return LookupQualifiedName(static_cast<DeclContext *>(SS->getScopeRep()),
1064 Name, NameKind, RedeclarationOnly);
1065 }
1066
1067 return LookupName(S, Name, NameKind, RedeclarationOnly);
Douglas Gregor78d70132009-01-14 22:20:51 +00001068}
1069
Douglas Gregor7a7be652009-02-03 19:21:40 +00001070
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001071/// @brief Produce a diagnostic describing the ambiguity that resulted
1072/// from name lookup.
1073///
1074/// @param Result The ambiguous name lookup result.
1075///
1076/// @param Name The name of the entity that name lookup was
1077/// searching for.
1078///
1079/// @param NameLoc The location of the name within the source code.
1080///
1081/// @param LookupRange A source range that provides more
1082/// source-location information concerning the lookup itself. For
1083/// example, this range might highlight a nested-name-specifier that
1084/// precedes the name.
1085///
1086/// @returns true
1087bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1088 SourceLocation NameLoc,
1089 SourceRange LookupRange) {
1090 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1091
Douglas Gregor7a7be652009-02-03 19:21:40 +00001092 if (BasePaths *Paths = Result.getBasePaths())
1093 {
1094 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1095 QualType SubobjectType = Paths->front().back().Base->getType();
1096 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1097 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1098 << LookupRange;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001099
Douglas Gregor7a7be652009-02-03 19:21:40 +00001100 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1101 while (isa<CXXMethodDecl>(*Found) && cast<CXXMethodDecl>(*Found)->isStatic())
1102 ++Found;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001103
Douglas Gregor7a7be652009-02-03 19:21:40 +00001104 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1105
1106 return true;
1107 }
1108
1109 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1110 "Unhandled form of name lookup ambiguity");
1111
1112 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1113 << Name << LookupRange;
1114
1115 std::set<Decl *> DeclsPrinted;
1116 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1117 Path != PathEnd; ++Path) {
1118 Decl *D = *Path->Decls.first;
1119 if (DeclsPrinted.insert(D).second)
1120 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1121 }
1122
1123 delete Paths;
1124 return true;
1125 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
1126
1127 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1128
1129 Decl **DI = reinterpret_cast<Decl **>(Result.First),
1130 **DEnd = reinterpret_cast<Decl **>(Result.Last);
1131
Chris Lattnerb02f5f22009-02-03 21:29:32 +00001132 for (; DI != DEnd; ++DI)
Douglas Gregor7a7be652009-02-03 19:21:40 +00001133 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate)
1134 << getQualifiedName(*DI);
1135
1136 delete[] reinterpret_cast<Decl **>(Result.First);
Douglas Gregor98b27542009-01-17 00:42:38 +00001137
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001138 return true;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001139 }
1140
Douglas Gregor7a7be652009-02-03 19:21:40 +00001141 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregord07474b2009-01-17 01:13:24 +00001142
Douglas Gregor7a7be652009-02-03 19:21:40 +00001143 // We can't reach here.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001144 return true;
1145}