blob: f4bfe5ca3c8ccb332ed210344e166317dfe2401f [file] [log] [blame]
Douglas Gregor78d70132009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000015#include "SemaInherit.h"
16#include "clang/AST/ASTContext.h"
Douglas Gregor78d70132009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
Douglas Gregoraa1da4a2009-02-04 00:32:51 +000020#include "clang/AST/Expr.h"
Douglas Gregor78d70132009-01-14 22:20:51 +000021#include "clang/Parse/DeclSpec.h"
22#include "clang/Basic/LangOptions.h"
23#include "llvm/ADT/STLExtras.h"
Douglas Gregoraa1da4a2009-02-04 00:32:51 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorb9ef0552009-01-16 00:38:09 +000025#include <set>
Douglas Gregor7a7be652009-02-03 19:21:40 +000026#include <vector>
27#include <iterator>
28#include <utility>
29#include <algorithm>
Douglas Gregor78d70132009-01-14 22:20:51 +000030
31using namespace clang;
32
Douglas Gregor7a7be652009-02-03 19:21:40 +000033typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy;
34typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet;
35typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy;
36
37/// UsingDirAncestorCompare - Implements strict weak ordering of
38/// UsingDirectives. It orders them by address of its common ancestor.
39struct UsingDirAncestorCompare {
40
41 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
42 bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const {
43 return U->getCommonAncestor() < Ctx;
44 }
45
46 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
47 bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const {
48 return Ctx < U->getCommonAncestor();
49 }
50
51 /// @brief Compares UsingDirectiveDecl common ancestors.
52 bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const {
53 return U1->getCommonAncestor() < U2->getCommonAncestor();
54 }
55};
56
57/// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs
58/// (ordered by common ancestors), found in namespace NS,
59/// including all found (recursively) in their nominated namespaces.
60void AddNamespaceUsingDirectives(DeclContext *NS,
61 UsingDirectivesTy &UDirs,
62 NamespaceSet &Visited) {
63 DeclContext::udir_iterator I, End;
64
65 for (llvm::tie(I, End) = NS->getUsingDirectives(); I !=End; ++I) {
66 UDirs.push_back(*I);
67 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
68 NamespaceDecl *Nominated = (*I)->getNominatedNamespace();
69 if (Visited.insert(Nominated).second)
70 AddNamespaceUsingDirectives(Nominated, UDirs, /*ref*/ Visited);
71 }
72}
73
74/// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S,
75/// including all found in the namespaces they nominate.
76static void AddScopeUsingDirectives(Scope *S, UsingDirectivesTy &UDirs) {
77 NamespaceSet VisitedNS;
78
79 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
80
81 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx))
82 VisitedNS.insert(NS);
83
84 AddNamespaceUsingDirectives(Ctx, UDirs, /*ref*/ VisitedNS);
85
86 } else {
87 Scope::udir_iterator
88 I = S->using_directives_begin(),
89 End = S->using_directives_end();
90
91 for (; I != End; ++I) {
92 UsingDirectiveDecl * UD = static_cast<UsingDirectiveDecl*>(*I);
93 UDirs.push_back(UD);
94 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
95
96 NamespaceDecl *Nominated = UD->getNominatedNamespace();
97 if (!VisitedNS.count(Nominated)) {
98 VisitedNS.insert(Nominated);
99 AddNamespaceUsingDirectives(Nominated, UDirs, /*ref*/ VisitedNS);
100 }
101 }
102 }
103}
104
Douglas Gregor78d70132009-01-14 22:20:51 +0000105/// MaybeConstructOverloadSet - Name lookup has determined that the
106/// elements in [I, IEnd) have the name that we are looking for, and
107/// *I is a match for the namespace. This routine returns an
108/// appropriate Decl for name lookup, which may either be *I or an
Douglas Gregor7a7be652009-02-03 19:21:40 +0000109/// OverloadedFunctionDecl that represents the overloaded functions in
Douglas Gregor78d70132009-01-14 22:20:51 +0000110/// [I, IEnd).
111///
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000112/// The existance of this routine is temporary; users of LookupResult
113/// should be able to handle multiple results, to deal with cases of
Douglas Gregor78d70132009-01-14 22:20:51 +0000114/// ambiguity and overloaded functions without needing to create a
115/// Decl node.
116template<typename DeclIterator>
Douglas Gregor09be81b2009-02-04 17:27:36 +0000117static NamedDecl *
Douglas Gregor78d70132009-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 Gregoraf8ad2b2009-01-20 01:17:11 +0000134 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
Douglas Gregor78d70132009-01-14 22:20:51 +0000135 (*I)->getDeclName());
136 Ovl->addOverload(cast<FunctionDecl>(*I));
137 }
138 Ovl->addOverload(cast<FunctionDecl>(*Last));
139 }
140
141 // If we had more than one function, we built an overload
142 // set. Return it.
143 if (Ovl)
144 return Ovl;
145 }
146
147 return *I;
148}
149
Douglas Gregor7a7be652009-02-03 19:21:40 +0000150/// Merges together multiple LookupResults dealing with duplicated Decl's.
151static Sema::LookupResult
152MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
153 typedef Sema::LookupResult LResult;
Douglas Gregor09be81b2009-02-04 17:27:36 +0000154 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000155
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000156 // Remove duplicated Decl pointing at same Decl, by storing them in
157 // associative collection. This might be case for code like:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000158 //
159 // namespace A { int i; }
160 // namespace B { using namespace A; }
161 // namespace C { using namespace A; }
162 //
163 // void foo() {
164 // using namespace B;
165 // using namespace C;
166 // ++i; // finds A::i, from both namespace B and C at global scope
167 // }
168 //
169 // C++ [namespace.qual].p3:
170 // The same declaration found more than once is not an ambiguity
171 // (because it is still a unique declaration).
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000172 DeclsSetTy FoundDecls;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000173
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000174 // Counter of tag names, and functions for resolving ambiguity
175 // and name hiding.
176 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
Douglas Gregor09be81b2009-02-04 17:27:36 +0000177
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000178 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
179
180 // No name lookup results, return early.
181 if (I == End) return LResult::CreateLookupResult(Context, 0);
182
183 // Keep track of the tag declaration we found. We only use this if
184 // we find a single tag declaration.
185 TagDecl *TagFound = 0;
186
187 for (; I != End; ++I) {
188 switch (I->getKind()) {
189 case LResult::NotFound:
190 assert(false &&
191 "Should be always successful name lookup result here.");
192 break;
193
194 case LResult::AmbiguousReference:
195 case LResult::AmbiguousBaseSubobjectTypes:
196 case LResult::AmbiguousBaseSubobjects:
197 assert(false && "Shouldn't get ambiguous lookup here.");
198 break;
199
200 case LResult::Found: {
201 NamedDecl *ND = I->getAsDecl();
202 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
203 TagFound = Context.getCanonicalDecl(TD);
204 TagNames += FoundDecls.insert(TagFound)? 1 : 0;
205 } else if (isa<FunctionDecl>(ND))
206 Functions += FoundDecls.insert(ND)? 1 : 0;
207 else
208 FoundDecls.insert(ND);
209 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000210 }
211
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000212 case LResult::FoundOverloaded:
213 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
214 Functions += FoundDecls.insert(*FI)? 1 : 0;
215 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000216 }
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000217 }
218 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
219 bool Ambiguous = false, NameHidesTags = false;
220
221 if (FoundDecls.size() == 1) {
222 // 1) Exactly one result.
223 } else if (TagNames > 1) {
224 // 2) Multiple tag names (even though they may be hidden by an
225 // object name).
226 Ambiguous = true;
227 } else if (FoundDecls.size() - TagNames == 1) {
228 // 3) Ordinary name hides (optional) tag.
229 NameHidesTags = TagFound;
230 } else if (Functions) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000231 // C++ [basic.lookup].p1:
232 // ... Name lookup may associate more than one declaration with
Douglas Gregor7a7be652009-02-03 19:21:40 +0000233 // a name if it finds the name to be a function name; the declarations
234 // are said to form a set of overloaded functions (13.1).
235 // Overload resolution (13.3) takes place after name lookup has succeeded.
Douglas Gregor09be81b2009-02-04 17:27:36 +0000236 //
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000237 if (!OrdinaryNonFunc) {
238 // 4) Functions hide tag names.
239 NameHidesTags = TagFound;
240 } else {
241 // 5) Functions + ordinary names.
242 Ambiguous = true;
243 }
244 } else {
245 // 6) Multiple non-tag names
246 Ambiguous = true;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000247 }
248
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000249 if (Ambiguous)
250 return LResult::CreateLookupResult(Context,
251 FoundDecls.begin(), FoundDecls.size());
252 if (NameHidesTags) {
253 // There's only one tag, TagFound. Remove it.
254 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
255 FoundDecls.erase(TagFound);
256 }
257
258 // Return successful name lookup result.
259 return LResult::CreateLookupResult(Context,
260 MaybeConstructOverloadSet(Context,
261 FoundDecls.begin(),
262 FoundDecls.end()));
Douglas Gregor7a7be652009-02-03 19:21:40 +0000263}
264
265// Retrieve the set of identifier namespaces that correspond to a
266// specific kind of name lookup.
267inline unsigned
268getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
269 bool CPlusPlus) {
270 unsigned IDNS = 0;
271 switch (NameKind) {
272 case Sema::LookupOrdinaryName:
Douglas Gregor48a87322009-02-04 16:44:47 +0000273 case Sema::LookupOperatorName:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000274 IDNS = Decl::IDNS_Ordinary;
275 if (CPlusPlus)
276 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
277 break;
278
279 case Sema::LookupTagName:
280 IDNS = Decl::IDNS_Tag;
281 break;
282
283 case Sema::LookupMemberName:
284 IDNS = Decl::IDNS_Member;
285 if (CPlusPlus)
286 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
287 break;
288
289 case Sema::LookupNestedNameSpecifierName:
290 case Sema::LookupNamespaceName:
291 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
292 break;
293 }
294 return IDNS;
295}
296
Douglas Gregor7a7be652009-02-03 19:21:40 +0000297Sema::LookupResult
Douglas Gregor09be81b2009-02-04 17:27:36 +0000298Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000299 LookupResult Result;
300 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
301 OverloadedDeclSingleDecl : SingleDecl;
302 Result.First = reinterpret_cast<uintptr_t>(D);
303 Result.Last = 0;
304 Result.Context = &Context;
305 return Result;
306}
307
Douglas Gregor6beddfe2009-01-15 02:19:31 +0000308/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregord07474b2009-01-17 01:13:24 +0000309Sema::LookupResult
310Sema::LookupResult::CreateLookupResult(ASTContext &Context,
311 IdentifierResolver::iterator F,
312 IdentifierResolver::iterator L) {
313 LookupResult Result;
314 Result.Context = &Context;
315
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000316 if (F != L && isa<FunctionDecl>(*F)) {
317 IdentifierResolver::iterator Next = F;
318 ++Next;
319 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000320 Result.StoredKind = OverloadedDeclFromIdResolver;
321 Result.First = F.getAsOpaqueValue();
322 Result.Last = L.getAsOpaqueValue();
323 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000324 }
325 }
326
Douglas Gregord07474b2009-01-17 01:13:24 +0000327 Result.StoredKind = SingleDecl;
328 Result.First = reinterpret_cast<uintptr_t>(*F);
329 Result.Last = 0;
330 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000331}
332
Douglas Gregord07474b2009-01-17 01:13:24 +0000333Sema::LookupResult
334Sema::LookupResult::CreateLookupResult(ASTContext &Context,
335 DeclContext::lookup_iterator F,
336 DeclContext::lookup_iterator L) {
337 LookupResult Result;
338 Result.Context = &Context;
339
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000340 if (F != L && isa<FunctionDecl>(*F)) {
341 DeclContext::lookup_iterator Next = F;
342 ++Next;
343 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000344 Result.StoredKind = OverloadedDeclFromDeclContext;
345 Result.First = reinterpret_cast<uintptr_t>(F);
346 Result.Last = reinterpret_cast<uintptr_t>(L);
347 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000348 }
349 }
350
Douglas Gregord07474b2009-01-17 01:13:24 +0000351 Result.StoredKind = SingleDecl;
352 Result.First = reinterpret_cast<uintptr_t>(*F);
353 Result.Last = 0;
354 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000355}
356
Douglas Gregor78d70132009-01-14 22:20:51 +0000357/// @brief Determine the result of name lookup.
358Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
359 switch (StoredKind) {
360 case SingleDecl:
361 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
362
Douglas Gregor7a7be652009-02-03 19:21:40 +0000363 case OverloadedDeclSingleDecl:
Douglas Gregor78d70132009-01-14 22:20:51 +0000364 case OverloadedDeclFromIdResolver:
365 case OverloadedDeclFromDeclContext:
366 return FoundOverloaded;
367
Douglas Gregor7a7be652009-02-03 19:21:40 +0000368 case AmbiguousLookupStoresBasePaths:
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000369 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000370
371 case AmbiguousLookupStoresDecls:
372 return AmbiguousReference;
Douglas Gregor78d70132009-01-14 22:20:51 +0000373 }
374
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000375 // We can't ever get here.
376 return NotFound;
Douglas Gregor78d70132009-01-14 22:20:51 +0000377}
378
379/// @brief Converts the result of name lookup into a single (possible
380/// NULL) pointer to a declaration.
381///
382/// The resulting declaration will either be the declaration we found
383/// (if only a single declaration was found), an
384/// OverloadedFunctionDecl (if an overloaded function was found), or
385/// NULL (if no declaration was found). This conversion must not be
386/// used anywhere where name lookup could result in an ambiguity.
387///
388/// The OverloadedFunctionDecl conversion is meant as a stop-gap
389/// solution, since it causes the OverloadedFunctionDecl to be
390/// leaked. FIXME: Eventually, there will be a better way to iterate
391/// over the set of overloaded functions returned by name lookup.
Douglas Gregor09be81b2009-02-04 17:27:36 +0000392NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregor78d70132009-01-14 22:20:51 +0000393 switch (StoredKind) {
394 case SingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000395 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregor78d70132009-01-14 22:20:51 +0000396
397 case OverloadedDeclFromIdResolver:
398 return MaybeConstructOverloadSet(*Context,
399 IdentifierResolver::iterator::getFromOpaqueValue(First),
400 IdentifierResolver::iterator::getFromOpaqueValue(Last));
401
402 case OverloadedDeclFromDeclContext:
403 return MaybeConstructOverloadSet(*Context,
404 reinterpret_cast<DeclContext::lookup_iterator>(First),
405 reinterpret_cast<DeclContext::lookup_iterator>(Last));
406
Douglas Gregor7a7be652009-02-03 19:21:40 +0000407 case OverloadedDeclSingleDecl:
408 return reinterpret_cast<OverloadedFunctionDecl*>(First);
409
410 case AmbiguousLookupStoresDecls:
411 case AmbiguousLookupStoresBasePaths:
Douglas Gregor78d70132009-01-14 22:20:51 +0000412 assert(false &&
413 "Name lookup returned an ambiguity that could not be handled");
414 break;
415 }
416
417 return 0;
418}
419
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000420/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor7a7be652009-02-03 19:21:40 +0000421/// name lookup, or null.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000422BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000423 if (StoredKind == AmbiguousLookupStoresBasePaths)
424 return reinterpret_cast<BasePaths *>(First);
425 return 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000426}
427
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000428Sema::LookupResult::iterator::reference
429Sema::LookupResult::iterator::operator*() const {
430 switch (Result->StoredKind) {
431 case SingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000432 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000433
Douglas Gregor7a7be652009-02-03 19:21:40 +0000434 case OverloadedDeclSingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000435 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000436
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000437 case OverloadedDeclFromIdResolver:
438 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
439
440 case OverloadedDeclFromDeclContext:
441 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000442
443 case AmbiguousLookupStoresDecls:
444 case AmbiguousLookupStoresBasePaths:
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000445 assert(false && "Cannot look into ambiguous lookup results");
446 break;
447 }
448
449 return 0;
450}
451
452Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
453 switch (Result->StoredKind) {
454 case SingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000455 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000456 break;
457
Douglas Gregor7a7be652009-02-03 19:21:40 +0000458 case OverloadedDeclSingleDecl: {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000459 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000460 ++I;
461 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregor48a87322009-02-04 16:44:47 +0000462 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000463 }
464
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000465 case OverloadedDeclFromIdResolver: {
466 IdentifierResolver::iterator I
467 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
468 ++I;
469 Current = I.getAsOpaqueValue();
470 break;
471 }
472
473 case OverloadedDeclFromDeclContext: {
474 DeclContext::lookup_iterator I
475 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
476 ++I;
477 Current = reinterpret_cast<uintptr_t>(I);
478 break;
479 }
480
Douglas Gregor7a7be652009-02-03 19:21:40 +0000481 case AmbiguousLookupStoresDecls:
482 case AmbiguousLookupStoresBasePaths:
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000483 assert(false && "Cannot look into ambiguous lookup results");
484 break;
485 }
486
487 return *this;
488}
489
490Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000491 assert(!isAmbiguous() && "Lookup into an ambiguous result");
492 if (StoredKind != OverloadedDeclSingleDecl)
493 return iterator(this, First);
494 OverloadedFunctionDecl * Ovl =
495 reinterpret_cast<OverloadedFunctionDecl*>(First);
496 return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000497}
498
499Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000500 assert(!isAmbiguous() && "Lookup into an ambiguous result");
501 if (StoredKind != OverloadedDeclSingleDecl)
502 return iterator(this, Last);
503 OverloadedFunctionDecl * Ovl =
504 reinterpret_cast<OverloadedFunctionDecl*>(First);
505 return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000506}
507
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000508static void
509CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
510 DeclarationName Name, Sema::LookupNameKind NameKind,
511 unsigned IDNS, LookupResultsTy &Results,
512 UsingDirectivesTy *UDirs = 0) {
513
514 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
515
516 // Perform qualified name lookup into the LookupCtx.
517 DeclContext::lookup_iterator I, E;
518 for (llvm::tie(I, E) = NS->lookup(Name); I != E; ++I)
519 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
520 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
521 break;
522 }
523
524 if (UDirs) {
525 // For each UsingDirectiveDecl, which common ancestor is equal
526 // to NS, we preform qualified name lookup into namespace nominated by it.
527 UsingDirectivesTy::const_iterator UI, UEnd;
528 llvm::tie(UI, UEnd) =
529 std::equal_range(UDirs->begin(), UDirs->end(), NS,
530 UsingDirAncestorCompare());
531
532 for (; UI != UEnd; ++UI)
533 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
534 Name, NameKind, IDNS, Results);
535 }
536}
537
538static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000539 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000540 return Ctx->isFileContext();
541 return false;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000542}
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000543
Douglas Gregor7a7be652009-02-03 19:21:40 +0000544std::pair<bool, Sema::LookupResult>
545Sema::CppLookupName(Scope *S, DeclarationName Name,
546 LookupNameKind NameKind, bool RedeclarationOnly) {
547 assert(getLangOptions().CPlusPlus &&
548 "Can perform only C++ lookup");
Douglas Gregor48a87322009-02-04 16:44:47 +0000549 unsigned IDNS
Douglas Gregor09be81b2009-02-04 17:27:36 +0000550 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000551 Scope *Initial = S;
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000552 DeclContext *OutOfLineCtx = 0;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000553 IdentifierResolver::iterator
554 I = IdResolver.begin(Name),
555 IEnd = IdResolver.end();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000556
Douglas Gregor7a7be652009-02-03 19:21:40 +0000557 // First we lookup local scope.
Douglas Gregor279272e2009-02-04 19:02:06 +0000558 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor7a7be652009-02-03 19:21:40 +0000559 // ...During unqualified name lookup (3.4.1), the names appear as if
560 // they were declared in the nearest enclosing namespace which contains
561 // both the using-directive and the nominated namespace.
562 // [Note: in this context, “contains” means “contains directly or
563 // indirectly”.
564 //
565 // For example:
566 // namespace A { int i; }
567 // void foo() {
568 // int i;
569 // {
570 // using namespace A;
571 // ++i; // finds local 'i', A::i appears at global scope
572 // }
573 // }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000574 //
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000575 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000576 // Check whether the IdResolver has anything in this scope.
577 for (; I != IEnd && S->isDeclScope(*I); ++I) {
578 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
579 // We found something. Look for anything else in our scope
580 // with this same name and in an acceptable identifier
581 // namespace, so that we can construct an overload set if we
582 // need to.
583 IdentifierResolver::iterator LastI = I;
584 for (++LastI; LastI != IEnd; ++LastI) {
585 if (!S->isDeclScope(*LastI))
586 break;
587 }
588 LookupResult Result =
589 LookupResult::CreateLookupResult(Context, I, LastI);
590 return std::make_pair(true, Result);
591 }
592 }
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000593 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
594 LookupResult R;
595 // Perform member lookup into struct.
596 // FIXME: In some cases, we know that every name that could be
597 // found by this qualified name lookup will also be on the
598 // identifier chain. For example, inside a class without any
599 // base classes, we never need to perform qualified lookup
600 // because all of the members are on top of the identifier
601 // chain.
602 if (isa<RecordDecl>(Ctx) &&
603 (R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly)))
604 return std::make_pair(true, R);
605
606 if (Ctx->getParent() != Ctx->getLexicalParent()) {
607 // It is out of line defined C++ method or struct, we continue
608 // doing name lookup in parent context. Once we will find namespace
609 // or translation-unit we save it for possible checking
610 // using-directives later.
611 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
612 OutOfLineCtx = OutOfLineCtx->getParent()) {
Sebastian Redl95216a62009-02-07 00:15:38 +0000613 if ((R = LookupQualifiedName(OutOfLineCtx, Name, NameKind,
614 RedeclarationOnly)))
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000615 return std::make_pair(true, R);
616 }
617 }
618 }
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000619 }
Douglas Gregor7a7be652009-02-03 19:21:40 +0000620
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000621 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor7a7be652009-02-03 19:21:40 +0000622 // nominated namespaces by those using-directives.
623 // UsingDirectives are pushed to heap, in common ancestor pointer
624 // value order.
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000625 // FIXME: Cache this sorted list in Scope structure, and DeclContext,
626 // so we don't build it for each lookup!
Douglas Gregor7a7be652009-02-03 19:21:40 +0000627 UsingDirectivesTy UDirs;
628 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor09be81b2009-02-04 17:27:36 +0000629 if (SC->getFlags() & Scope::DeclScope)
630 AddScopeUsingDirectives(SC, UDirs);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000631
632 // Sort heapified UsingDirectiveDecls.
633 std::sort_heap(UDirs.begin(), UDirs.end());
634
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000635 // Lookup namespace scope, and global scope.
Douglas Gregor7a7be652009-02-03 19:21:40 +0000636 // Unqualified name lookup in C++ requires looking into scopes
637 // that aren't strictly lexical, and therefore we walk through the
638 // context as well as walking through the scopes.
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000639
640 LookupResultsTy LookupResults;
Sebastian Redl95216a62009-02-07 00:15:38 +0000641 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000642 "We should have been looking only at file context here already.");
643 bool LookedInCtx = false;
644 LookupResult Result;
645 while (OutOfLineCtx &&
646 OutOfLineCtx != S->getEntity() &&
647 OutOfLineCtx->isNamespace()) {
648 LookedInCtx = true;
649
650 // Look into context considering using-directives.
651 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
652 LookupResults, &UDirs);
653
654 if ((Result = MergeLookupResults(Context, LookupResults)) ||
655 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
656 return std::make_pair(true, Result);
657
658 OutOfLineCtx = OutOfLineCtx->getParent();
659 }
660
Douglas Gregor7a7be652009-02-03 19:21:40 +0000661 for (; S; S = S->getParent()) {
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000662 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
663 assert(Ctx && Ctx->isFileContext() &&
664 "We should have been looking only at file context here already.");
Douglas Gregor7a7be652009-02-03 19:21:40 +0000665
666 // Check whether the IdResolver has anything in this scope.
667 for (; I != IEnd && S->isDeclScope(*I); ++I) {
668 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
669 // We found something. Look for anything else in our scope
670 // with this same name and in an acceptable identifier
671 // namespace, so that we can construct an overload set if we
672 // need to.
673 IdentifierResolver::iterator LastI = I;
674 for (++LastI; LastI != IEnd; ++LastI) {
675 if (!S->isDeclScope(*LastI))
676 break;
677 }
678
679 // We store name lookup result, and continue trying to look into
680 // associated context, and maybe namespaces nominated by
681 // using-directives.
682 LookupResults.push_back(
683 LookupResult::CreateLookupResult(Context, I, LastI));
684 break;
685 }
686 }
687
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000688 LookedInCtx = true;
689 // Look into context considering using-directives.
690 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
691 LookupResults, &UDirs);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000692
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000693 if ((Result = MergeLookupResults(Context, LookupResults)) ||
694 (RedeclarationOnly && !Ctx->isTransparentContext()))
695 return std::make_pair(true, Result);
696 }
Douglas Gregor7a7be652009-02-03 19:21:40 +0000697
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000698 if (!(LookedInCtx || LookupResults.empty())) {
699 // We didn't Performed lookup in Scope entity, so we return
700 // result form IdentifierResolver.
701 assert((LookupResults.size() == 1) && "Wrong size!");
702 return std::make_pair(true, LookupResults.front());
Douglas Gregor7a7be652009-02-03 19:21:40 +0000703 }
704 return std::make_pair(false, LookupResult());
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000705}
706
Douglas Gregor78d70132009-01-14 22:20:51 +0000707/// @brief Perform unqualified name lookup starting from a given
708/// scope.
709///
710/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
711/// used to find names within the current scope. For example, 'x' in
712/// @code
713/// int x;
714/// int f() {
715/// return x; // unqualified name look finds 'x' in the global scope
716/// }
717/// @endcode
718///
719/// Different lookup criteria can find different names. For example, a
720/// particular scope can have both a struct and a function of the same
721/// name, and each can be found by certain lookup criteria. For more
722/// information about lookup criteria, see the documentation for the
723/// class LookupCriteria.
724///
725/// @param S The scope from which unqualified name lookup will
726/// begin. If the lookup criteria permits, name lookup may also search
727/// in the parent scopes.
728///
729/// @param Name The name of the entity that we are searching for.
730///
731/// @param Criteria The criteria that this routine will use to
732/// determine which names are visible and which names will be
733/// found. Note that name lookup will find a name that is visible by
734/// the given criteria, but the entity itself may not be semantically
735/// correct or even the kind of entity expected based on the
736/// lookup. For example, searching for a nested-name-specifier name
737/// might result in an EnumDecl, which is visible but is not permitted
738/// as a nested-name-specifier in C++03.
739///
740/// @returns The result of name lookup, which includes zero or more
741/// declarations and possibly additional information used to diagnose
742/// ambiguities.
743Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000744Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
745 bool RedeclarationOnly) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000746 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000747
748 if (!getLangOptions().CPlusPlus) {
749 // Unqualified name lookup in C/Objective-C is purely lexical, so
750 // search in the declarations attached to the name.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000751 unsigned IDNS = 0;
752 switch (NameKind) {
753 case Sema::LookupOrdinaryName:
754 IDNS = Decl::IDNS_Ordinary;
755 break;
Douglas Gregor78d70132009-01-14 22:20:51 +0000756
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000757 case Sema::LookupTagName:
758 IDNS = Decl::IDNS_Tag;
759 break;
760
761 case Sema::LookupMemberName:
762 IDNS = Decl::IDNS_Member;
763 break;
764
Douglas Gregor48a87322009-02-04 16:44:47 +0000765 case Sema::LookupOperatorName:
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000766 case Sema::LookupNestedNameSpecifierName:
767 case Sema::LookupNamespaceName:
768 assert(false && "C does not perform these kinds of name lookup");
769 break;
770 }
771
Douglas Gregor78d70132009-01-14 22:20:51 +0000772 // Scan up the scope chain looking for a decl that matches this
773 // identifier that is in the appropriate namespace. This search
774 // should not take long, as shadowing of names is uncommon, and
775 // deep shadowing is extremely uncommon.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000776 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
777 IEnd = IdResolver.end();
778 I != IEnd; ++I)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000779 if ((*I)->isInIdentifierNamespace(IDNS)) {
780 if ((*I)->getAttr<OverloadableAttr>()) {
781 // If this declaration has the "overloadable" attribute, we
782 // might have a set of overloaded functions.
783
784 // Figure out what scope the identifier is in.
785 while (!(S->getFlags() & Scope::DeclScope) || !S->isDeclScope(*I))
786 S = S->getParent();
787
788 // Find the last declaration in this scope (with the same
789 // name, naturally).
790 IdentifierResolver::iterator LastI = I;
791 for (++LastI; LastI != IEnd; ++LastI) {
792 if (!S->isDeclScope(*LastI))
793 break;
794 }
795
796 return LookupResult::CreateLookupResult(Context, I, LastI);
797 }
798
799 // We have a single lookup result.
Douglas Gregord07474b2009-01-17 01:13:24 +0000800 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregorfcb19192009-02-11 23:02:49 +0000801 }
Douglas Gregor78d70132009-01-14 22:20:51 +0000802 } else {
Douglas Gregor7a7be652009-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 Gregor78d70132009-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 Gregor52ae30c2009-01-30 01:04:22 +0000813 if (NameKind == LookupOrdinaryName) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000814 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000815 if (II) {
Douglas Gregor78d70132009-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 Gregord07474b2009-01-17 01:13:24 +0000818 return LookupResult::CreateLookupResult(Context,
Douglas Gregor78d70132009-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 Gregord07474b2009-01-17 01:13:24 +0000829 return LookupResult::CreateLookupResult(Context, IDI->second);
Douglas Gregor78d70132009-01-14 22:20:51 +0000830 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
831 if (I != ObjCAliasDecls.end())
Douglas Gregord07474b2009-01-17 01:13:24 +0000832 return LookupResult::CreateLookupResult(Context,
833 I->second->getClassInterface());
Douglas Gregor78d70132009-01-14 22:20:51 +0000834 }
835 }
Douglas Gregord07474b2009-01-17 01:13:24 +0000836 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-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 Gregor52ae30c2009-01-30 01:04:22 +0000871 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000872 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
873
Douglas Gregord07474b2009-01-17 01:13:24 +0000874 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-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 Gregor52ae30c2009-01-30 01:04:22 +0000878 unsigned IDNS
879 = getIdentifierNamespacesFromLookupNameKind(NameKind,
880 getLangOptions().CPlusPlus);
881 if (NameKind == LookupOrdinaryName)
882 IDNS |= Decl::IDNS_Member;
Douglas Gregor78d70132009-01-14 22:20:51 +0000883
884 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor78d70132009-01-14 22:20:51 +0000885 DeclContext::lookup_iterator I, E;
886 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000887 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregord07474b2009-01-17 01:13:24 +0000888 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregor78d70132009-01-14 22:20:51 +0000889
Douglas Gregor29dfa2f2009-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 Gregor52ae30c2009-01-30 01:04:22 +0000892 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregord07474b2009-01-17 01:13:24 +0000893 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000894
895 // Perform lookup into our base classes.
896 BasePaths Paths;
Douglas Gregorb9ef0552009-01-16 00:38:09 +0000897 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000898
899 // Look for this member in our base classes
900 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000901 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregord07474b2009-01-17 01:13:24 +0000902 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-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 Dunbarddebeca2009-01-15 18:32:35 +0000912 int SubobjectNumber = 0;
Douglas Gregor29dfa2f2009-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 Gregord07474b2009-01-17 01:13:24 +0000928 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor29dfa2f2009-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 Gregoraf8ad2b2009-01-20 01:17:11 +0000936 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor29dfa2f2009-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 Gregord07474b2009-01-17 01:13:24 +0000966 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor29dfa2f2009-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 Gregord07474b2009-01-17 01:13:24 +0000974 return LookupResult::CreateLookupResult(Context,
Douglas Gregor29dfa2f2009-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 Gregord07474b2009-01-17 01:13:24 +0000978 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregor78d70132009-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 Gregor78d70132009-01-14 22:20:51 +0000998/// @returns The result of qualified or unqualified name lookup.
999Sema::LookupResult
Douglas Gregor52ae30c2009-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 Gregor78d70132009-01-14 22:20:51 +00001006
Douglas Gregor52ae30c2009-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 Gregor78d70132009-01-14 22:20:51 +00001013}
1014
Douglas Gregor7a7be652009-02-03 19:21:40 +00001015
Douglas Gregor29dfa2f2009-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 Gregor7a7be652009-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 Gregorb9ef0552009-01-16 00:38:09 +00001044
Douglas Gregor7a7be652009-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 Gregorb9ef0552009-01-16 00:38:09 +00001048
Douglas Gregor7a7be652009-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 Gregor09be81b2009-02-04 17:27:36 +00001074 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
1075 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor7a7be652009-02-03 19:21:40 +00001076
Chris Lattnerb02f5f22009-02-03 21:29:32 +00001077 for (; DI != DEnd; ++DI)
Douglas Gregor09be81b2009-02-04 17:27:36 +00001078 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor7a7be652009-02-03 19:21:40 +00001079
Douglas Gregor09be81b2009-02-04 17:27:36 +00001080 delete[] reinterpret_cast<NamedDecl **>(Result.First);
Douglas Gregor98b27542009-01-17 00:42:38 +00001081
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001082 return true;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001083 }
1084
Douglas Gregor7a7be652009-02-03 19:21:40 +00001085 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregord07474b2009-01-17 01:13:24 +00001086
Douglas Gregor7a7be652009-02-03 19:21:40 +00001087 // We can't reach here.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001088 return true;
1089}
Douglas Gregoraa1da4a2009-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}