blob: 65dd9490d26d7e602bbdb39f01e130caf62e99b1 [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000015#include "SemaInherit.h"
16#include "clang/AST/ASTContext.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000020#include "clang/AST/Expr.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000021#include "clang/Parse/DeclSpec.h"
22#include "clang/Basic/LangOptions.h"
23#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000025#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000026#include <vector>
27#include <iterator>
28#include <utility>
29#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000030
31using namespace clang;
32
Douglas Gregor2a3009a2009-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 Gregoreb11cd02009-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 Gregor2a3009a2009-02-03 19:21:40 +0000109/// OverloadedFunctionDecl that represents the overloaded functions in
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000110/// [I, IEnd).
111///
Douglas Gregor4c921ae2009-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 Gregoreb11cd02009-01-14 22:20:51 +0000114/// ambiguity and overloaded functions without needing to create a
115/// Decl node.
116template<typename DeclIterator>
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000117static NamedDecl *
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000118MaybeConstructOverloadSet(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 Gregor4afa39d2009-01-20 01:17:11 +0000134 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
Douglas Gregoreb11cd02009-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 Gregor2a3009a2009-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;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000154 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000155
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000156 DeclsSetTy FoundDecls;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000157 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:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000174 FoundDecls.insert(I->getAsDecl());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000175 break;
176
177 case LResult::AmbiguousBaseSubobjectTypes:
178 case LResult::AmbiguousBaseSubobjects: {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000179 assert(Results.size() == 1 && "Multiple LookupResults should be not case "
180 "here, since using-directives can't occur at class scope.");
181 return *I;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000182 }
183
184 case LResult::FoundOverloaded:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000185 if (FoundOverloaded)
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000186 // We have one spare OverloadedFunctionDecl already, so we store
187 // its function decls.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000188 for (LResult::iterator
189 FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
190 FoundDecls.insert(*FI);
191 else
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000192 // First time we found OverloadedFunctionDecl, we want to conserve
193 // it, and possibly add other found Decls later.
194 FoundOverloaded = cast<OverloadedFunctionDecl>(I->getAsDecl());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000195 break;
196 }
197 }
198
199 // Remove duplicated Decl pointing at same Decl, this might be case
200 // for code like:
201 //
202 // namespace A { int i; }
203 // namespace B { using namespace A; }
204 // namespace C { using namespace A; }
205 //
206 // void foo() {
207 // using namespace B;
208 // using namespace C;
209 // ++i; // finds A::i, from both namespace B and C at global scope
210 // }
211 //
212 // C++ [namespace.qual].p3:
213 // The same declaration found more than once is not an ambiguity
214 // (because it is still a unique declaration).
215 //
216 // FIXME: At this point happens too, because we are doing redundant lookups.
217 //
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000218 DeclsSetTy::iterator DI = FoundDecls.begin(), DEnd = FoundDecls.end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000219
220 if (FoundOverloaded) {
221 // We found overloaded functions result. We want to add any other
222 // found decls, that are not already in FoundOverloaded, and are functions
223 // or methods.
224 OverloadedFunctionDecl::function_iterator
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000225 FI = FoundOverloaded->function_begin(),
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000226 FEnd = FoundOverloaded->function_end();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000227
228 for (; FI < FEnd; ++FI) {
229 if (FoundDecls.count(*FI))
230 FoundDecls.erase(*FI);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000231 }
232
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000233 DI = FoundDecls.begin(), DEnd = FoundDecls.end();
234
235 for (; DI != DEnd; ++DI)
236 if (FunctionDecl *Fun = dyn_cast<FunctionDecl>(*DI))
237 FoundOverloaded->addOverload(Fun);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000238
239 return LResult::CreateLookupResult(Context, FoundOverloaded);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000240 } else if (std::size_t FoundLen = FoundDecls.size()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000241 // We might found multiple TagDecls pointing at same definition.
242 if (TagDecl *R = dyn_cast<TagDecl>(*FoundDecls.begin())) {
243 TagDecl *Canonical = Context.getCanonicalDecl(R);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000244 DeclsSetTy::iterator RI = FoundDecls.begin(), REnd = DEnd;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000245 for (;;) {
246 ++RI;
247 if (RI == REnd) {
248 FoundLen = 1;
249 break;
250 }
251 R = dyn_cast<TagDecl>(*RI);
252 if (R && Canonical == Context.getCanonicalDecl(R)) { /* Skip */}
253 else break;
254 }
255 }
256
257 // We might find FunctionDecls in two (or more) distinct DeclContexts.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000258 //
259 // C++ [basic.lookup].p1:
260 // ... Name lookup may associate more than one declaration with
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000261 // a name if it finds the name to be a function name; the declarations
262 // are said to form a set of overloaded functions (13.1).
263 // Overload resolution (13.3) takes place after name lookup has succeeded.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000264 //
265 NamedDecl *D = MaybeConstructOverloadSet(Context, DI, DEnd);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000266 if ((FoundLen == 1) || isa<OverloadedFunctionDecl>(D))
267 return LResult::CreateLookupResult(Context, D);
268
269 // Found multiple Decls, it is ambiguous reference.
270 return LResult::CreateLookupResult(Context, FoundDecls.begin(), FoundLen);
271 }
272
273 LResult Result = LResult::CreateLookupResult(Context, 0);
274 return Result;
275}
276
277// Retrieve the set of identifier namespaces that correspond to a
278// specific kind of name lookup.
279inline unsigned
280getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
281 bool CPlusPlus) {
282 unsigned IDNS = 0;
283 switch (NameKind) {
284 case Sema::LookupOrdinaryName:
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000285 case Sema::LookupOperatorName:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000286 IDNS = Decl::IDNS_Ordinary;
287 if (CPlusPlus)
288 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
289 break;
290
291 case Sema::LookupTagName:
292 IDNS = Decl::IDNS_Tag;
293 break;
294
295 case Sema::LookupMemberName:
296 IDNS = Decl::IDNS_Member;
297 if (CPlusPlus)
298 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
299 break;
300
301 case Sema::LookupNestedNameSpecifierName:
302 case Sema::LookupNamespaceName:
303 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
304 break;
305 }
306 return IDNS;
307}
308
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000309Sema::LookupResult
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000310Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000311 LookupResult Result;
312 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
313 OverloadedDeclSingleDecl : SingleDecl;
314 Result.First = reinterpret_cast<uintptr_t>(D);
315 Result.Last = 0;
316 Result.Context = &Context;
317 return Result;
318}
319
Douglas Gregor4bb64e72009-01-15 02:19:31 +0000320/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000321Sema::LookupResult
322Sema::LookupResult::CreateLookupResult(ASTContext &Context,
323 IdentifierResolver::iterator F,
324 IdentifierResolver::iterator L) {
325 LookupResult Result;
326 Result.Context = &Context;
327
Douglas Gregor7176fff2009-01-15 00:26:24 +0000328 if (F != L && isa<FunctionDecl>(*F)) {
329 IdentifierResolver::iterator Next = F;
330 ++Next;
331 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000332 Result.StoredKind = OverloadedDeclFromIdResolver;
333 Result.First = F.getAsOpaqueValue();
334 Result.Last = L.getAsOpaqueValue();
335 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000336 }
337 }
338
Douglas Gregor69d993a2009-01-17 01:13:24 +0000339 Result.StoredKind = SingleDecl;
340 Result.First = reinterpret_cast<uintptr_t>(*F);
341 Result.Last = 0;
342 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000343}
344
Douglas Gregor69d993a2009-01-17 01:13:24 +0000345Sema::LookupResult
346Sema::LookupResult::CreateLookupResult(ASTContext &Context,
347 DeclContext::lookup_iterator F,
348 DeclContext::lookup_iterator L) {
349 LookupResult Result;
350 Result.Context = &Context;
351
Douglas Gregor7176fff2009-01-15 00:26:24 +0000352 if (F != L && isa<FunctionDecl>(*F)) {
353 DeclContext::lookup_iterator Next = F;
354 ++Next;
355 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000356 Result.StoredKind = OverloadedDeclFromDeclContext;
357 Result.First = reinterpret_cast<uintptr_t>(F);
358 Result.Last = reinterpret_cast<uintptr_t>(L);
359 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000360 }
361 }
362
Douglas Gregor69d993a2009-01-17 01:13:24 +0000363 Result.StoredKind = SingleDecl;
364 Result.First = reinterpret_cast<uintptr_t>(*F);
365 Result.Last = 0;
366 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000367}
368
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000369/// @brief Determine the result of name lookup.
370Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
371 switch (StoredKind) {
372 case SingleDecl:
373 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
374
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000375 case OverloadedDeclSingleDecl:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000376 case OverloadedDeclFromIdResolver:
377 case OverloadedDeclFromDeclContext:
378 return FoundOverloaded;
379
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000380 case AmbiguousLookupStoresBasePaths:
Douglas Gregor7176fff2009-01-15 00:26:24 +0000381 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000382
383 case AmbiguousLookupStoresDecls:
384 return AmbiguousReference;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000385 }
386
Douglas Gregor7176fff2009-01-15 00:26:24 +0000387 // We can't ever get here.
388 return NotFound;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000389}
390
391/// @brief Converts the result of name lookup into a single (possible
392/// NULL) pointer to a declaration.
393///
394/// The resulting declaration will either be the declaration we found
395/// (if only a single declaration was found), an
396/// OverloadedFunctionDecl (if an overloaded function was found), or
397/// NULL (if no declaration was found). This conversion must not be
398/// used anywhere where name lookup could result in an ambiguity.
399///
400/// The OverloadedFunctionDecl conversion is meant as a stop-gap
401/// solution, since it causes the OverloadedFunctionDecl to be
402/// leaked. FIXME: Eventually, there will be a better way to iterate
403/// over the set of overloaded functions returned by name lookup.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000404NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000405 switch (StoredKind) {
406 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000407 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000408
409 case OverloadedDeclFromIdResolver:
410 return MaybeConstructOverloadSet(*Context,
411 IdentifierResolver::iterator::getFromOpaqueValue(First),
412 IdentifierResolver::iterator::getFromOpaqueValue(Last));
413
414 case OverloadedDeclFromDeclContext:
415 return MaybeConstructOverloadSet(*Context,
416 reinterpret_cast<DeclContext::lookup_iterator>(First),
417 reinterpret_cast<DeclContext::lookup_iterator>(Last));
418
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000419 case OverloadedDeclSingleDecl:
420 return reinterpret_cast<OverloadedFunctionDecl*>(First);
421
422 case AmbiguousLookupStoresDecls:
423 case AmbiguousLookupStoresBasePaths:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000424 assert(false &&
425 "Name lookup returned an ambiguity that could not be handled");
426 break;
427 }
428
429 return 0;
430}
431
Douglas Gregor7176fff2009-01-15 00:26:24 +0000432/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000433/// name lookup, or null.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000434BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000435 if (StoredKind == AmbiguousLookupStoresBasePaths)
436 return reinterpret_cast<BasePaths *>(First);
437 return 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000438}
439
Douglas Gregord8635172009-02-02 21:35:47 +0000440Sema::LookupResult::iterator::reference
441Sema::LookupResult::iterator::operator*() const {
442 switch (Result->StoredKind) {
443 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000444 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000445
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000446 case OverloadedDeclSingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000447 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000448
Douglas Gregord8635172009-02-02 21:35:47 +0000449 case OverloadedDeclFromIdResolver:
450 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
451
452 case OverloadedDeclFromDeclContext:
453 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000454
455 case AmbiguousLookupStoresDecls:
456 case AmbiguousLookupStoresBasePaths:
Douglas Gregord8635172009-02-02 21:35:47 +0000457 assert(false && "Cannot look into ambiguous lookup results");
458 break;
459 }
460
461 return 0;
462}
463
464Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
465 switch (Result->StoredKind) {
466 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000467 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregord8635172009-02-02 21:35:47 +0000468 break;
469
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000470 case OverloadedDeclSingleDecl: {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000471 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000472 ++I;
473 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000474 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000475 }
476
Douglas Gregord8635172009-02-02 21:35:47 +0000477 case OverloadedDeclFromIdResolver: {
478 IdentifierResolver::iterator I
479 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
480 ++I;
481 Current = I.getAsOpaqueValue();
482 break;
483 }
484
485 case OverloadedDeclFromDeclContext: {
486 DeclContext::lookup_iterator I
487 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
488 ++I;
489 Current = reinterpret_cast<uintptr_t>(I);
490 break;
491 }
492
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000493 case AmbiguousLookupStoresDecls:
494 case AmbiguousLookupStoresBasePaths:
Douglas Gregord8635172009-02-02 21:35:47 +0000495 assert(false && "Cannot look into ambiguous lookup results");
496 break;
497 }
498
499 return *this;
500}
501
502Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000503 assert(!isAmbiguous() && "Lookup into an ambiguous result");
504 if (StoredKind != OverloadedDeclSingleDecl)
505 return iterator(this, First);
506 OverloadedFunctionDecl * Ovl =
507 reinterpret_cast<OverloadedFunctionDecl*>(First);
508 return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
Douglas Gregord8635172009-02-02 21:35:47 +0000509}
510
511Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000512 assert(!isAmbiguous() && "Lookup into an ambiguous result");
513 if (StoredKind != OverloadedDeclSingleDecl)
514 return iterator(this, Last);
515 OverloadedFunctionDecl * Ovl =
516 reinterpret_cast<OverloadedFunctionDecl*>(First);
517 return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
Douglas Gregord8635172009-02-02 21:35:47 +0000518}
519
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000520static bool isFunctionLocalScope(Scope *S) {
521 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
522 return Ctx->isFunctionOrMethod();
523 return true;
524}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000525
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000526std::pair<bool, Sema::LookupResult>
527Sema::CppLookupName(Scope *S, DeclarationName Name,
528 LookupNameKind NameKind, bool RedeclarationOnly) {
529 assert(getLangOptions().CPlusPlus &&
530 "Can perform only C++ lookup");
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000531 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000532 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000533 Scope *Initial = S;
534 IdentifierResolver::iterator
535 I = IdResolver.begin(Name),
536 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000537
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000538 // First we lookup local scope.
539 // We don't consider using-dirctives, as per 7.3.4.p1 [namespace.udir]
540 // ...During unqualified name lookup (3.4.1), the names appear as if
541 // they were declared in the nearest enclosing namespace which contains
542 // both the using-directive and the nominated namespace.
543 // [Note: in this context, “contains” means “contains directly or
544 // indirectly”.
545 //
546 // For example:
547 // namespace A { int i; }
548 // void foo() {
549 // int i;
550 // {
551 // using namespace A;
552 // ++i; // finds local 'i', A::i appears at global scope
553 // }
554 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000555 //
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000556 for (; S && isFunctionLocalScope(S); S = S->getParent()) {
557 // Check whether the IdResolver has anything in this scope.
558 for (; I != IEnd && S->isDeclScope(*I); ++I) {
559 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
560 // We found something. Look for anything else in our scope
561 // with this same name and in an acceptable identifier
562 // namespace, so that we can construct an overload set if we
563 // need to.
564 IdentifierResolver::iterator LastI = I;
565 for (++LastI; LastI != IEnd; ++LastI) {
566 if (!S->isDeclScope(*LastI))
567 break;
568 }
569 LookupResult Result =
570 LookupResult::CreateLookupResult(Context, I, LastI);
571 return std::make_pair(true, Result);
572 }
573 }
574 // NB: Icky, we need to look in function scope, but we need to check its
575 // parent DeclContext (instead S->getParent()) for member name lookup,
576 // in case it is out of line method definition. Like in:
577 //
578 // class C {
579 // int i;
580 // void foo();
581 // };
582 //
583 // C::foo() {
584 // (void) i;
585 // }
586 //
587 // FIXME: Maybe we should do member name lookup here instead?
588 if (S->getEntity() && isFunctionLocalScope(S))
589 break;
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000590 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000591
592 // Collect UsingDirectiveDecls in all scopes, and recursivly all
593 // nominated namespaces by those using-directives.
594 // UsingDirectives are pushed to heap, in common ancestor pointer
595 // value order.
596 // FIXME: Cache this sorted list in Scope structure, and maybe
597 // DeclContext, so we don't build it for each lookup!
598 UsingDirectivesTy UDirs;
599 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000600 if (SC->getFlags() & Scope::DeclScope)
601 AddScopeUsingDirectives(SC, UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000602
603 // Sort heapified UsingDirectiveDecls.
604 std::sort_heap(UDirs.begin(), UDirs.end());
605
606 // Lookup namespace scope, global scope, or possibly (CXX)Record DeclContext
607 // for member name lookup.
608 // Unqualified name lookup in C++ requires looking into scopes
609 // that aren't strictly lexical, and therefore we walk through the
610 // context as well as walking through the scopes.
611 for (; S; S = S->getParent()) {
612 LookupResultsTy LookupResults;
613 bool LookedInCtx = false;
614
615 // Check whether the IdResolver has anything in this scope.
616 for (; I != IEnd && S->isDeclScope(*I); ++I) {
617 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
618 // We found something. Look for anything else in our scope
619 // with this same name and in an acceptable identifier
620 // namespace, so that we can construct an overload set if we
621 // need to.
622 IdentifierResolver::iterator LastI = I;
623 for (++LastI; LastI != IEnd; ++LastI) {
624 if (!S->isDeclScope(*LastI))
625 break;
626 }
627
628 // We store name lookup result, and continue trying to look into
629 // associated context, and maybe namespaces nominated by
630 // using-directives.
631 LookupResults.push_back(
632 LookupResult::CreateLookupResult(Context, I, LastI));
633 break;
634 }
635 }
636
637 // If there is an entity associated with this scope, it's a
638 // DeclContext. We might need to perform qualified lookup into
639 // it, or namespaces nominated by using-directives.
640 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
641
642 if (Ctx && isa<TranslationUnitDecl>(Ctx)) {
643 UsingDirectivesTy::const_iterator UI, UEnd;
644 // For each UsingDirectiveDecl, which common ancestor is equal
645 // to Ctx, we preform qualified name lookup into namespace nominated
646 // by it.
647 llvm::tie(UI, UEnd) =
648 std::equal_range(UDirs.begin(), UDirs.end(), Ctx,
649 UsingDirAncestorCompare());
650 for (; UI != UEnd; ++UI) {
651 // FIXME: We will have to ensure, that we won't consider
652 // again using-directives during qualified name lookup!
653 // (Once using-directives support for qualified name lookup gets
654 // implemented).
655 if (LookupResult R = LookupQualifiedName((*UI)->getNominatedNamespace(),
656 Name, NameKind, RedeclarationOnly))
657 LookupResults.push_back(R);
658 }
659 LookupResult Result;
660 if ((Result = MergeLookupResults(Context, LookupResults)) ||
661 RedeclarationOnly) {
662 return std::make_pair(true, Result);
663 }
664 }
665
666 // FIXME: We're performing redundant lookups here, where the
667 // scope stack mirrors the semantic nested of classes and
668 // namespaces. We can save some work by checking the lexical
669 // scope against the semantic scope and avoiding any lookups
670 // when they are the same.
671 // FIXME: In some cases, we know that every name that could be
672 // found by this qualified name lookup will also be on the
673 // identifier chain. For example, inside a class without any
674 // base classes, we never need to perform qualified lookup
675 // because all of the members are on top of the identifier
676 // chain. However, we cannot perform this optimization when the
677 // lexical and semantic scopes don't line up, e.g., in an
678 // out-of-line member definition.
679 while (Ctx && Ctx->isFunctionOrMethod())
680 Ctx = Ctx->getParent();
681 while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
682 LookedInCtx = true;
683 // Look for declarations of this name in this scope.
684 if (LookupResult R = LookupQualifiedName(Ctx, Name, NameKind,
685 RedeclarationOnly))
686 // We store that, to investigate futher, wheather reference
687 // to this Decl is no ambiguous.
688 LookupResults.push_back(R);
689
690 if (Ctx->isNamespace()) {
691 // For each UsingDirectiveDecl, which common ancestor is equal
692 // to Ctx, we preform qualified name lookup into namespace nominated
693 // by it.
694 UsingDirectivesTy::const_iterator UI, UEnd;
695 llvm::tie(UI, UEnd) =
696 std::equal_range(UDirs.begin(), UDirs.end(), Ctx,
697 UsingDirAncestorCompare());
698 for (; UI != UEnd; ++UI) {
699 // FIXME: We will have to ensure, that we won't consider
700 // again using-directives during qualified name lookup!
701 // (Once using-directives support for qualified name lookup gets
702 // implemented).
703 LookupResult R = LookupQualifiedName((*UI)->getNominatedNamespace(),
704 Name, NameKind,
705 RedeclarationOnly);
706 if (R)
707 LookupResults.push_back(R);
708 }
709 }
710 LookupResult Result;
711 if ((Result = MergeLookupResults(Context, LookupResults)) ||
712 (RedeclarationOnly && !Ctx->isTransparentContext())) {
713 return std::make_pair(true, Result);
714 }
715 Ctx = Ctx->getParent();
716 }
717
718 if (!(LookedInCtx || LookupResults.empty())) {
719 // We didn't Performed lookup in Scope entity, so we return
720 // result form IdentifierResolver.
721 assert((LookupResults.size() == 1) && "Wrong size!");
722 return std::make_pair(true, LookupResults.front());
723 }
724 }
725 return std::make_pair(false, LookupResult());
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000726}
727
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000728/// @brief Perform unqualified name lookup starting from a given
729/// scope.
730///
731/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
732/// used to find names within the current scope. For example, 'x' in
733/// @code
734/// int x;
735/// int f() {
736/// return x; // unqualified name look finds 'x' in the global scope
737/// }
738/// @endcode
739///
740/// Different lookup criteria can find different names. For example, a
741/// particular scope can have both a struct and a function of the same
742/// name, and each can be found by certain lookup criteria. For more
743/// information about lookup criteria, see the documentation for the
744/// class LookupCriteria.
745///
746/// @param S The scope from which unqualified name lookup will
747/// begin. If the lookup criteria permits, name lookup may also search
748/// in the parent scopes.
749///
750/// @param Name The name of the entity that we are searching for.
751///
752/// @param Criteria The criteria that this routine will use to
753/// determine which names are visible and which names will be
754/// found. Note that name lookup will find a name that is visible by
755/// the given criteria, but the entity itself may not be semantically
756/// correct or even the kind of entity expected based on the
757/// lookup. For example, searching for a nested-name-specifier name
758/// might result in an EnumDecl, which is visible but is not permitted
759/// as a nested-name-specifier in C++03.
760///
761/// @returns The result of name lookup, which includes zero or more
762/// declarations and possibly additional information used to diagnose
763/// ambiguities.
764Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000765Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
766 bool RedeclarationOnly) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000767 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000768
769 if (!getLangOptions().CPlusPlus) {
770 // Unqualified name lookup in C/Objective-C is purely lexical, so
771 // search in the declarations attached to the name.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000772 unsigned IDNS = 0;
773 switch (NameKind) {
774 case Sema::LookupOrdinaryName:
775 IDNS = Decl::IDNS_Ordinary;
776 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000777
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000778 case Sema::LookupTagName:
779 IDNS = Decl::IDNS_Tag;
780 break;
781
782 case Sema::LookupMemberName:
783 IDNS = Decl::IDNS_Member;
784 break;
785
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000786 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000787 case Sema::LookupNestedNameSpecifierName:
788 case Sema::LookupNamespaceName:
789 assert(false && "C does not perform these kinds of name lookup");
790 break;
791 }
792
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000793 // Scan up the scope chain looking for a decl that matches this
794 // identifier that is in the appropriate namespace. This search
795 // should not take long, as shadowing of names is uncommon, and
796 // deep shadowing is extremely uncommon.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000797 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
798 IEnd = IdResolver.end();
799 I != IEnd; ++I)
800 if ((*I)->isInIdentifierNamespace(IDNS))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000801 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000802 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000803 // Perform C++ unqualified name lookup.
804 std::pair<bool, LookupResult> MaybeResult =
805 CppLookupName(S, Name, NameKind, RedeclarationOnly);
806 if (MaybeResult.first)
807 return MaybeResult.second;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000808 }
809
810 // If we didn't find a use of this identifier, and if the identifier
811 // corresponds to a compiler builtin, create the decl object for the builtin
812 // now, injecting it into translation unit scope, and return it.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000813 if (NameKind == LookupOrdinaryName) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000814 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000815 if (II) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000816 // If this is a builtin on this (or all) targets, create the decl.
817 if (unsigned BuiltinID = II->getBuiltinID())
Douglas Gregor69d993a2009-01-17 01:13:24 +0000818 return LookupResult::CreateLookupResult(Context,
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000819 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
820 S));
821 }
822 if (getLangOptions().ObjC1 && II) {
823 // @interface and @compatibility_alias introduce typedef-like names.
824 // Unlike typedef's, they can only be introduced at file-scope (and are
825 // therefore not scoped decls). They can, however, be shadowed by
826 // other names in IDNS_Ordinary.
827 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
828 if (IDI != ObjCInterfaceDecls.end())
Douglas Gregor69d993a2009-01-17 01:13:24 +0000829 return LookupResult::CreateLookupResult(Context, IDI->second);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000830 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
831 if (I != ObjCAliasDecls.end())
Douglas Gregor69d993a2009-01-17 01:13:24 +0000832 return LookupResult::CreateLookupResult(Context,
833 I->second->getClassInterface());
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000834 }
835 }
Douglas Gregor69d993a2009-01-17 01:13:24 +0000836 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000837}
838
839/// @brief Perform qualified name lookup into a given context.
840///
841/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
842/// names when the context of those names is explicit specified, e.g.,
843/// "std::vector" or "x->member".
844///
845/// Different lookup criteria can find different names. For example, a
846/// particular scope can have both a struct and a function of the same
847/// name, and each can be found by certain lookup criteria. For more
848/// information about lookup criteria, see the documentation for the
849/// class LookupCriteria.
850///
851/// @param LookupCtx The context in which qualified name lookup will
852/// search. If the lookup criteria permits, name lookup may also search
853/// in the parent contexts or (for C++ classes) base classes.
854///
855/// @param Name The name of the entity that we are searching for.
856///
857/// @param Criteria The criteria that this routine will use to
858/// determine which names are visible and which names will be
859/// found. Note that name lookup will find a name that is visible by
860/// the given criteria, but the entity itself may not be semantically
861/// correct or even the kind of entity expected based on the
862/// lookup. For example, searching for a nested-name-specifier name
863/// might result in an EnumDecl, which is visible but is not permitted
864/// as a nested-name-specifier in C++03.
865///
866/// @returns The result of name lookup, which includes zero or more
867/// declarations and possibly additional information used to diagnose
868/// ambiguities.
869Sema::LookupResult
870Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000871 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000872 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
873
Douglas Gregor69d993a2009-01-17 01:13:24 +0000874 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000875
876 // If we're performing qualified name lookup (e.g., lookup into a
877 // struct), find fields as part of ordinary name lookup.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000878 unsigned IDNS
879 = getIdentifierNamespacesFromLookupNameKind(NameKind,
880 getLangOptions().CPlusPlus);
881 if (NameKind == LookupOrdinaryName)
882 IDNS |= Decl::IDNS_Member;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000883
884 // Perform qualified name lookup into the LookupCtx.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000885 DeclContext::lookup_iterator I, E;
886 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000887 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000888 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000889
Douglas Gregor7176fff2009-01-15 00:26:24 +0000890 // If this isn't a C++ class or we aren't allowed to look into base
891 // classes, we're done.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000892 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000893 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000894
895 // Perform lookup into our base classes.
896 BasePaths Paths;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +0000897 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor7176fff2009-01-15 00:26:24 +0000898
899 // Look for this member in our base classes
900 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000901 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000902 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000903
904 // C++ [class.member.lookup]p2:
905 // [...] If the resulting set of declarations are not all from
906 // sub-objects of the same type, or the set has a nonstatic member
907 // and includes members from distinct sub-objects, there is an
908 // ambiguity and the program is ill-formed. Otherwise that set is
909 // the result of the lookup.
910 // FIXME: support using declarations!
911 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +0000912 int SubobjectNumber = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000913 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
914 Path != PathEnd; ++Path) {
915 const BasePathElement &PathElement = Path->back();
916
917 // Determine whether we're looking at a distinct sub-object or not.
918 if (SubobjectType.isNull()) {
919 // This is the first subobject we've looked at. Record it's type.
920 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
921 SubobjectNumber = PathElement.SubobjectNumber;
922 } else if (SubobjectType
923 != Context.getCanonicalType(PathElement.Base->getType())) {
924 // We found members of the given name in two subobjects of
925 // different types. This lookup is ambiguous.
926 BasePaths *PathsOnHeap = new BasePaths;
927 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000928 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000929 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
930 // We have a different subobject of the same type.
931
932 // C++ [class.member.lookup]p5:
933 // A static member, a nested type or an enumerator defined in
934 // a base class T can unambiguously be found even if an object
935 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000936 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000937 if (isa<VarDecl>(FirstDecl) ||
938 isa<TypeDecl>(FirstDecl) ||
939 isa<EnumConstantDecl>(FirstDecl))
940 continue;
941
942 if (isa<CXXMethodDecl>(FirstDecl)) {
943 // Determine whether all of the methods are static.
944 bool AllMethodsAreStatic = true;
945 for (DeclContext::lookup_iterator Func = Path->Decls.first;
946 Func != Path->Decls.second; ++Func) {
947 if (!isa<CXXMethodDecl>(*Func)) {
948 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
949 break;
950 }
951
952 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
953 AllMethodsAreStatic = false;
954 break;
955 }
956 }
957
958 if (AllMethodsAreStatic)
959 continue;
960 }
961
962 // We have found a nonstatic member name in multiple, distinct
963 // subobjects. Name lookup is ambiguous.
964 BasePaths *PathsOnHeap = new BasePaths;
965 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000966 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000967 }
968 }
969
970 // Lookup in a base class succeeded; return these results.
971
972 // If we found a function declaration, return an overload set.
973 if (isa<FunctionDecl>(*Paths.front().Decls.first))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000974 return LookupResult::CreateLookupResult(Context,
Douglas Gregor7176fff2009-01-15 00:26:24 +0000975 Paths.front().Decls.first, Paths.front().Decls.second);
976
977 // We found a non-function declaration; return a single declaration.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000978 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000979}
980
981/// @brief Performs name lookup for a name that was parsed in the
982/// source code, and may contain a C++ scope specifier.
983///
984/// This routine is a convenience routine meant to be called from
985/// contexts that receive a name and an optional C++ scope specifier
986/// (e.g., "N::M::x"). It will then perform either qualified or
987/// unqualified name lookup (with LookupQualifiedName or LookupName,
988/// respectively) on the given name and return those results.
989///
990/// @param S The scope from which unqualified name lookup will
991/// begin.
992///
993/// @param SS An optional C++ scope-specified, e.g., "::N::M".
994///
995/// @param Name The name of the entity that name lookup will
996/// search for.
997///
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000998/// @returns The result of qualified or unqualified name lookup.
999Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001000Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1001 DeclarationName Name, LookupNameKind NameKind,
1002 bool RedeclarationOnly) {
1003 if (SS) {
1004 if (SS->isInvalid())
1005 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001006
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001007 if (SS->isSet())
1008 return LookupQualifiedName(static_cast<DeclContext *>(SS->getScopeRep()),
1009 Name, NameKind, RedeclarationOnly);
1010 }
1011
1012 return LookupName(S, Name, NameKind, RedeclarationOnly);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001013}
1014
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001015
Douglas Gregor7176fff2009-01-15 00:26:24 +00001016/// @brief Produce a diagnostic describing the ambiguity that resulted
1017/// from name lookup.
1018///
1019/// @param Result The ambiguous name lookup result.
1020///
1021/// @param Name The name of the entity that name lookup was
1022/// searching for.
1023///
1024/// @param NameLoc The location of the name within the source code.
1025///
1026/// @param LookupRange A source range that provides more
1027/// source-location information concerning the lookup itself. For
1028/// example, this range might highlight a nested-name-specifier that
1029/// precedes the name.
1030///
1031/// @returns true
1032bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1033 SourceLocation NameLoc,
1034 SourceRange LookupRange) {
1035 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1036
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001037 if (BasePaths *Paths = Result.getBasePaths())
1038 {
1039 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1040 QualType SubobjectType = Paths->front().back().Base->getType();
1041 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1042 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1043 << LookupRange;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001044
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001045 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1046 while (isa<CXXMethodDecl>(*Found) && cast<CXXMethodDecl>(*Found)->isStatic())
1047 ++Found;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001048
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001049 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1050
1051 return true;
1052 }
1053
1054 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1055 "Unhandled form of name lookup ambiguity");
1056
1057 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1058 << Name << LookupRange;
1059
1060 std::set<Decl *> DeclsPrinted;
1061 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1062 Path != PathEnd; ++Path) {
1063 Decl *D = *Path->Decls.first;
1064 if (DeclsPrinted.insert(D).second)
1065 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1066 }
1067
1068 delete Paths;
1069 return true;
1070 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
1071
1072 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1073
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001074 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
1075 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001076
Chris Lattner48458d22009-02-03 21:29:32 +00001077 for (; DI != DEnd; ++DI)
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001078 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001079
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001080 delete[] reinterpret_cast<NamedDecl **>(Result.First);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00001081
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001082 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001083 }
1084
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001085 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregor69d993a2009-01-17 01:13:24 +00001086
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001087 // We can't reach here.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001088 return true;
1089}
Douglas Gregorfa047642009-02-04 00:32:51 +00001090
1091// \brief Add the associated classes and namespaces for
1092// argument-dependent lookup with an argument of class type
1093// (C++ [basic.lookup.koenig]p2).
1094static void
1095addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1096 ASTContext &Context,
1097 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1098 Sema::AssociatedClassSet &AssociatedClasses) {
1099 // C++ [basic.lookup.koenig]p2:
1100 // [...]
1101 // -- If T is a class type (including unions), its associated
1102 // classes are: the class itself; the class of which it is a
1103 // member, if any; and its direct and indirect base
1104 // classes. Its associated namespaces are the namespaces in
1105 // which its associated classes are defined.
1106
1107 // Add the class of which it is a member, if any.
1108 DeclContext *Ctx = Class->getDeclContext();
1109 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1110 AssociatedClasses.insert(EnclosingClass);
1111
1112 // Add the associated namespace for this class.
1113 while (Ctx->isRecord())
1114 Ctx = Ctx->getParent();
1115 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1116 AssociatedNamespaces.insert(EnclosingNamespace);
1117
1118 // Add the class itself. If we've already seen this class, we don't
1119 // need to visit base classes.
1120 if (!AssociatedClasses.insert(Class))
1121 return;
1122
1123 // FIXME: Handle class template specializations
1124
1125 // Add direct and indirect base classes along with their associated
1126 // namespaces.
1127 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1128 Bases.push_back(Class);
1129 while (!Bases.empty()) {
1130 // Pop this class off the stack.
1131 Class = Bases.back();
1132 Bases.pop_back();
1133
1134 // Visit the base classes.
1135 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1136 BaseEnd = Class->bases_end();
1137 Base != BaseEnd; ++Base) {
1138 const RecordType *BaseType = Base->getType()->getAsRecordType();
1139 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1140 if (AssociatedClasses.insert(BaseDecl)) {
1141 // Find the associated namespace for this base class.
1142 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1143 while (BaseCtx->isRecord())
1144 BaseCtx = BaseCtx->getParent();
1145 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1146 AssociatedNamespaces.insert(EnclosingNamespace);
1147
1148 // Make sure we visit the bases of this base class.
1149 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1150 Bases.push_back(BaseDecl);
1151 }
1152 }
1153 }
1154}
1155
1156// \brief Add the associated classes and namespaces for
1157// argument-dependent lookup with an argument of type T
1158// (C++ [basic.lookup.koenig]p2).
1159static void
1160addAssociatedClassesAndNamespaces(QualType T,
1161 ASTContext &Context,
1162 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1163 Sema::AssociatedClassSet &AssociatedClasses) {
1164 // C++ [basic.lookup.koenig]p2:
1165 //
1166 // For each argument type T in the function call, there is a set
1167 // of zero or more associated namespaces and a set of zero or more
1168 // associated classes to be considered. The sets of namespaces and
1169 // classes is determined entirely by the types of the function
1170 // arguments (and the namespace of any template template
1171 // argument). Typedef names and using-declarations used to specify
1172 // the types do not contribute to this set. The sets of namespaces
1173 // and classes are determined in the following way:
1174 T = Context.getCanonicalType(T).getUnqualifiedType();
1175
1176 // -- If T is a pointer to U or an array of U, its associated
1177 // namespaces and classes are those associated with U.
1178 //
1179 // We handle this by unwrapping pointer and array types immediately,
1180 // to avoid unnecessary recursion.
1181 while (true) {
1182 if (const PointerType *Ptr = T->getAsPointerType())
1183 T = Ptr->getPointeeType();
1184 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1185 T = Ptr->getElementType();
1186 else
1187 break;
1188 }
1189
1190 // -- If T is a fundamental type, its associated sets of
1191 // namespaces and classes are both empty.
1192 if (T->getAsBuiltinType())
1193 return;
1194
1195 // -- If T is a class type (including unions), its associated
1196 // classes are: the class itself; the class of which it is a
1197 // member, if any; and its direct and indirect base
1198 // classes. Its associated namespaces are the namespaces in
1199 // which its associated classes are defined.
1200 if (const CXXRecordType *ClassType
1201 = dyn_cast_or_null<CXXRecordType>(T->getAsRecordType())) {
1202 addAssociatedClassesAndNamespaces(ClassType->getDecl(),
1203 Context, AssociatedNamespaces,
1204 AssociatedClasses);
1205 return;
1206 }
1207
1208 // -- If T is an enumeration type, its associated namespace is
1209 // the namespace in which it is defined. If it is class
1210 // member, its associated class is the member’s class; else
1211 // it has no associated class.
1212 if (const EnumType *EnumT = T->getAsEnumType()) {
1213 EnumDecl *Enum = EnumT->getDecl();
1214
1215 DeclContext *Ctx = Enum->getDeclContext();
1216 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1217 AssociatedClasses.insert(EnclosingClass);
1218
1219 // Add the associated namespace for this class.
1220 while (Ctx->isRecord())
1221 Ctx = Ctx->getParent();
1222 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1223 AssociatedNamespaces.insert(EnclosingNamespace);
1224
1225 return;
1226 }
1227
1228 // -- If T is a function type, its associated namespaces and
1229 // classes are those associated with the function parameter
1230 // types and those associated with the return type.
1231 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1232 // Return type
1233 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1234 Context,
1235 AssociatedNamespaces, AssociatedClasses);
1236
1237 const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FunctionType);
1238 if (!Proto)
1239 return;
1240
1241 // Argument types
1242 for (FunctionTypeProto::arg_type_iterator Arg = Proto->arg_type_begin(),
1243 ArgEnd = Proto->arg_type_end();
1244 Arg != ArgEnd; ++Arg)
1245 addAssociatedClassesAndNamespaces(*Arg, Context,
1246 AssociatedNamespaces, AssociatedClasses);
1247
1248 return;
1249 }
1250
1251 // -- If T is a pointer to a member function of a class X, its
1252 // associated namespaces and classes are those associated
1253 // with the function parameter types and return type,
1254 // together with those associated with X.
1255 //
1256 // -- If T is a pointer to a data member of class X, its
1257 // associated namespaces and classes are those associated
1258 // with the member type together with those associated with
1259 // X.
1260 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1261 // Handle the type that the pointer to member points to.
1262 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1263 Context,
1264 AssociatedNamespaces, AssociatedClasses);
1265
1266 // Handle the class type into which this points.
1267 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1268 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1269 Context,
1270 AssociatedNamespaces, AssociatedClasses);
1271
1272 return;
1273 }
1274
1275 // FIXME: What about block pointers?
1276 // FIXME: What about Objective-C message sends?
1277}
1278
1279/// \brief Find the associated classes and namespaces for
1280/// argument-dependent lookup for a call with the given set of
1281/// arguments.
1282///
1283/// This routine computes the sets of associated classes and associated
1284/// namespaces searched by argument-dependent lookup
1285/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1286void
1287Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1288 AssociatedNamespaceSet &AssociatedNamespaces,
1289 AssociatedClassSet &AssociatedClasses) {
1290 AssociatedNamespaces.clear();
1291 AssociatedClasses.clear();
1292
1293 // C++ [basic.lookup.koenig]p2:
1294 // For each argument type T in the function call, there is a set
1295 // of zero or more associated namespaces and a set of zero or more
1296 // associated classes to be considered. The sets of namespaces and
1297 // classes is determined entirely by the types of the function
1298 // arguments (and the namespace of any template template
1299 // argument).
1300 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1301 Expr *Arg = Args[ArgIdx];
1302
1303 if (Arg->getType() != Context.OverloadTy) {
1304 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
1305 AssociatedNamespaces, AssociatedClasses);
1306 continue;
1307 }
1308
1309 // [...] In addition, if the argument is the name or address of a
1310 // set of overloaded functions and/or function templates, its
1311 // associated classes and namespaces are the union of those
1312 // associated with each of the members of the set: the namespace
1313 // in which the function or function template is defined and the
1314 // classes and namespaces associated with its (non-dependent)
1315 // parameter types and return type.
1316 DeclRefExpr *DRE = 0;
1317 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1318 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1319 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1320 } else
1321 DRE = dyn_cast<DeclRefExpr>(Arg);
1322 if (!DRE)
1323 continue;
1324
1325 OverloadedFunctionDecl *Ovl
1326 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1327 if (!Ovl)
1328 continue;
1329
1330 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1331 FuncEnd = Ovl->function_end();
1332 Func != FuncEnd; ++Func) {
1333 FunctionDecl *FDecl = cast<FunctionDecl>(*Func);
1334
1335 // Add the namespace in which this function was defined. Note
1336 // that, if this is a member function, we do *not* consider the
1337 // enclosing namespace of its class.
1338 DeclContext *Ctx = FDecl->getDeclContext();
1339 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1340 AssociatedNamespaces.insert(EnclosingNamespace);
1341
1342 // Add the classes and namespaces associated with the parameter
1343 // types and return type of this function.
1344 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
1345 AssociatedNamespaces, AssociatedClasses);
1346 }
1347 }
1348}