blob: ee4c14d0ca49d509e96fb7b8c73499024ea96111 [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 Gregor7dda67d2009-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 Gregor2a3009a2009-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 Gregor7dda67d2009-02-05 19:25:20 +0000172 DeclsSetTy FoundDecls;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000173
Douglas Gregor7dda67d2009-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 Gregor47b9a1c2009-02-04 17:27:36 +0000177
Douglas Gregor7dda67d2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000210 }
211
Douglas Gregor7dda67d2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000216 }
Douglas Gregor7dda67d2009-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 Gregor47b9a1c2009-02-04 17:27:36 +0000231 // C++ [basic.lookup].p1:
232 // ... Name lookup may associate more than one declaration with
Douglas Gregor2a3009a2009-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 Gregor47b9a1c2009-02-04 17:27:36 +0000236 //
Douglas Gregor7dda67d2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000247 }
248
Douglas Gregor7dda67d2009-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 Gregor2a3009a2009-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 Gregorf680a0f2009-02-04 16:44:47 +0000273 case Sema::LookupOperatorName:
Douglas Gregor2a3009a2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000297Sema::LookupResult
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000298Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Douglas Gregor2a3009a2009-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 Gregor4bb64e72009-01-15 02:19:31 +0000308/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregor69d993a2009-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 Gregor7176fff2009-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 Gregor69d993a2009-01-17 01:13:24 +0000320 Result.StoredKind = OverloadedDeclFromIdResolver;
321 Result.First = F.getAsOpaqueValue();
322 Result.Last = L.getAsOpaqueValue();
323 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000324 }
325 }
326
Douglas Gregor69d993a2009-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 Gregor7176fff2009-01-15 00:26:24 +0000331}
332
Douglas Gregor69d993a2009-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 Gregor7176fff2009-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 Gregor69d993a2009-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 Gregor7176fff2009-01-15 00:26:24 +0000348 }
349 }
350
Douglas Gregor69d993a2009-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 Gregor7176fff2009-01-15 00:26:24 +0000355}
356
Douglas Gregoreb11cd02009-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 Gregor2a3009a2009-02-03 19:21:40 +0000363 case OverloadedDeclSingleDecl:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000364 case OverloadedDeclFromIdResolver:
365 case OverloadedDeclFromDeclContext:
366 return FoundOverloaded;
367
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000368 case AmbiguousLookupStoresBasePaths:
Douglas Gregor7176fff2009-01-15 00:26:24 +0000369 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000370
371 case AmbiguousLookupStoresDecls:
372 return AmbiguousReference;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000373 }
374
Douglas Gregor7176fff2009-01-15 00:26:24 +0000375 // We can't ever get here.
376 return NotFound;
Douglas Gregoreb11cd02009-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 Gregor47b9a1c2009-02-04 17:27:36 +0000392NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000393 switch (StoredKind) {
394 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000395 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregoreb11cd02009-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 Gregor2a3009a2009-02-03 19:21:40 +0000407 case OverloadedDeclSingleDecl:
408 return reinterpret_cast<OverloadedFunctionDecl*>(First);
409
410 case AmbiguousLookupStoresDecls:
411 case AmbiguousLookupStoresBasePaths:
Douglas Gregoreb11cd02009-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 Gregor7176fff2009-01-15 00:26:24 +0000420/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000421/// name lookup, or null.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000422BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000423 if (StoredKind == AmbiguousLookupStoresBasePaths)
424 return reinterpret_cast<BasePaths *>(First);
425 return 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000426}
427
Douglas Gregord8635172009-02-02 21:35:47 +0000428Sema::LookupResult::iterator::reference
429Sema::LookupResult::iterator::operator*() const {
430 switch (Result->StoredKind) {
431 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000432 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000433
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000434 case OverloadedDeclSingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000435 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000436
Douglas Gregord8635172009-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 Gregor2a3009a2009-02-03 19:21:40 +0000442
443 case AmbiguousLookupStoresDecls:
444 case AmbiguousLookupStoresBasePaths:
Douglas Gregord8635172009-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 Gregor47b9a1c2009-02-04 17:27:36 +0000455 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregord8635172009-02-02 21:35:47 +0000456 break;
457
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000458 case OverloadedDeclSingleDecl: {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000459 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000460 ++I;
461 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000462 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000463 }
464
Douglas Gregord8635172009-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 Gregor2a3009a2009-02-03 19:21:40 +0000481 case AmbiguousLookupStoresDecls:
482 case AmbiguousLookupStoresBasePaths:
Douglas Gregord8635172009-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 Gregor2a3009a2009-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 Gregord8635172009-02-02 21:35:47 +0000497}
498
499Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregor2a3009a2009-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 Gregord8635172009-02-02 21:35:47 +0000506}
507
Douglas Gregor7dda67d2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000539 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000540 return Ctx->isFileContext();
541 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000542}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000543
Douglas Gregor2a3009a2009-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 Gregorf680a0f2009-02-04 16:44:47 +0000549 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000550 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000551 Scope *Initial = S;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000552 DeclContext *OutOfLineCtx = 0;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000553 IdentifierResolver::iterator
554 I = IdResolver.begin(Name),
555 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000556
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000557 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000558 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-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 Gregor47b9a1c2009-02-04 17:27:36 +0000574 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000575 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-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 Gregor7dda67d2009-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 Redl22460502009-02-07 00:15:38 +0000613 if ((R = LookupQualifiedName(OutOfLineCtx, Name, NameKind,
614 RedeclarationOnly)))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000615 return std::make_pair(true, R);
616 }
617 }
618 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000619 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000620
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000621 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-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 Gregor7dda67d2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000627 UsingDirectivesTy UDirs;
628 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000629 if (SC->getFlags() & Scope::DeclScope)
630 AddScopeUsingDirectives(SC, UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000631
632 // Sort heapified UsingDirectiveDecls.
633 std::sort_heap(UDirs.begin(), UDirs.end());
634
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000635 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-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 Gregor7dda67d2009-02-05 19:25:20 +0000639
640 LookupResultsTy LookupResults;
Sebastian Redl22460502009-02-07 00:15:38 +0000641 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregor7dda67d2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000661 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-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 Gregor2a3009a2009-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 Gregor7dda67d2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000692
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000693 if ((Result = MergeLookupResults(Context, LookupResults)) ||
694 (RedeclarationOnly && !Ctx->isTransparentContext()))
695 return std::make_pair(true, Result);
696 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000697
Douglas Gregor7dda67d2009-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 Gregor2a3009a2009-02-03 19:21:40 +0000703 }
704 return std::make_pair(false, LookupResult());
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000705}
706
Douglas Gregoreb11cd02009-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 Gregor4c921ae2009-01-30 01:04:22 +0000744Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
745 bool RedeclarationOnly) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000746 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-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 Gregor4c921ae2009-01-30 01:04:22 +0000751 unsigned IDNS = 0;
752 switch (NameKind) {
753 case Sema::LookupOrdinaryName:
754 IDNS = Decl::IDNS_Ordinary;
755 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000756
Douglas Gregor4c921ae2009-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 Gregorf680a0f2009-02-04 16:44:47 +0000765 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-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 Gregoreb11cd02009-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 Gregor4c921ae2009-01-30 01:04:22 +0000776 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
777 IEnd = IdResolver.end();
778 I != IEnd; ++I)
779 if ((*I)->isInIdentifierNamespace(IDNS))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000780 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000781 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000782 // Perform C++ unqualified name lookup.
783 std::pair<bool, LookupResult> MaybeResult =
784 CppLookupName(S, Name, NameKind, RedeclarationOnly);
785 if (MaybeResult.first)
786 return MaybeResult.second;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000787 }
788
789 // If we didn't find a use of this identifier, and if the identifier
790 // corresponds to a compiler builtin, create the decl object for the builtin
791 // now, injecting it into translation unit scope, and return it.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000792 if (NameKind == LookupOrdinaryName) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000793 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000794 if (II) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000795 // If this is a builtin on this (or all) targets, create the decl.
796 if (unsigned BuiltinID = II->getBuiltinID())
Douglas Gregor69d993a2009-01-17 01:13:24 +0000797 return LookupResult::CreateLookupResult(Context,
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000798 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
799 S));
800 }
801 if (getLangOptions().ObjC1 && II) {
802 // @interface and @compatibility_alias introduce typedef-like names.
803 // Unlike typedef's, they can only be introduced at file-scope (and are
804 // therefore not scoped decls). They can, however, be shadowed by
805 // other names in IDNS_Ordinary.
806 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
807 if (IDI != ObjCInterfaceDecls.end())
Douglas Gregor69d993a2009-01-17 01:13:24 +0000808 return LookupResult::CreateLookupResult(Context, IDI->second);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000809 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
810 if (I != ObjCAliasDecls.end())
Douglas Gregor69d993a2009-01-17 01:13:24 +0000811 return LookupResult::CreateLookupResult(Context,
812 I->second->getClassInterface());
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000813 }
814 }
Douglas Gregor69d993a2009-01-17 01:13:24 +0000815 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000816}
817
818/// @brief Perform qualified name lookup into a given context.
819///
820/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
821/// names when the context of those names is explicit specified, e.g.,
822/// "std::vector" or "x->member".
823///
824/// Different lookup criteria can find different names. For example, a
825/// particular scope can have both a struct and a function of the same
826/// name, and each can be found by certain lookup criteria. For more
827/// information about lookup criteria, see the documentation for the
828/// class LookupCriteria.
829///
830/// @param LookupCtx The context in which qualified name lookup will
831/// search. If the lookup criteria permits, name lookup may also search
832/// in the parent contexts or (for C++ classes) base classes.
833///
834/// @param Name The name of the entity that we are searching for.
835///
836/// @param Criteria The criteria that this routine will use to
837/// determine which names are visible and which names will be
838/// found. Note that name lookup will find a name that is visible by
839/// the given criteria, but the entity itself may not be semantically
840/// correct or even the kind of entity expected based on the
841/// lookup. For example, searching for a nested-name-specifier name
842/// might result in an EnumDecl, which is visible but is not permitted
843/// as a nested-name-specifier in C++03.
844///
845/// @returns The result of name lookup, which includes zero or more
846/// declarations and possibly additional information used to diagnose
847/// ambiguities.
848Sema::LookupResult
849Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000850 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000851 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
852
Douglas Gregor69d993a2009-01-17 01:13:24 +0000853 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000854
855 // If we're performing qualified name lookup (e.g., lookup into a
856 // struct), find fields as part of ordinary name lookup.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000857 unsigned IDNS
858 = getIdentifierNamespacesFromLookupNameKind(NameKind,
859 getLangOptions().CPlusPlus);
860 if (NameKind == LookupOrdinaryName)
861 IDNS |= Decl::IDNS_Member;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000862
863 // Perform qualified name lookup into the LookupCtx.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000864 DeclContext::lookup_iterator I, E;
865 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000866 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000867 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000868
Douglas Gregor7176fff2009-01-15 00:26:24 +0000869 // If this isn't a C++ class or we aren't allowed to look into base
870 // classes, we're done.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000871 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000872 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000873
874 // Perform lookup into our base classes.
875 BasePaths Paths;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +0000876 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor7176fff2009-01-15 00:26:24 +0000877
878 // Look for this member in our base classes
879 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000880 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000881 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000882
883 // C++ [class.member.lookup]p2:
884 // [...] If the resulting set of declarations are not all from
885 // sub-objects of the same type, or the set has a nonstatic member
886 // and includes members from distinct sub-objects, there is an
887 // ambiguity and the program is ill-formed. Otherwise that set is
888 // the result of the lookup.
889 // FIXME: support using declarations!
890 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +0000891 int SubobjectNumber = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000892 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
893 Path != PathEnd; ++Path) {
894 const BasePathElement &PathElement = Path->back();
895
896 // Determine whether we're looking at a distinct sub-object or not.
897 if (SubobjectType.isNull()) {
898 // This is the first subobject we've looked at. Record it's type.
899 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
900 SubobjectNumber = PathElement.SubobjectNumber;
901 } else if (SubobjectType
902 != Context.getCanonicalType(PathElement.Base->getType())) {
903 // We found members of the given name in two subobjects of
904 // different types. This lookup is ambiguous.
905 BasePaths *PathsOnHeap = new BasePaths;
906 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000907 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000908 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
909 // We have a different subobject of the same type.
910
911 // C++ [class.member.lookup]p5:
912 // A static member, a nested type or an enumerator defined in
913 // a base class T can unambiguously be found even if an object
914 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000915 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000916 if (isa<VarDecl>(FirstDecl) ||
917 isa<TypeDecl>(FirstDecl) ||
918 isa<EnumConstantDecl>(FirstDecl))
919 continue;
920
921 if (isa<CXXMethodDecl>(FirstDecl)) {
922 // Determine whether all of the methods are static.
923 bool AllMethodsAreStatic = true;
924 for (DeclContext::lookup_iterator Func = Path->Decls.first;
925 Func != Path->Decls.second; ++Func) {
926 if (!isa<CXXMethodDecl>(*Func)) {
927 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
928 break;
929 }
930
931 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
932 AllMethodsAreStatic = false;
933 break;
934 }
935 }
936
937 if (AllMethodsAreStatic)
938 continue;
939 }
940
941 // We have found a nonstatic member name in multiple, distinct
942 // subobjects. Name lookup is ambiguous.
943 BasePaths *PathsOnHeap = new BasePaths;
944 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000945 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000946 }
947 }
948
949 // Lookup in a base class succeeded; return these results.
950
951 // If we found a function declaration, return an overload set.
952 if (isa<FunctionDecl>(*Paths.front().Decls.first))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000953 return LookupResult::CreateLookupResult(Context,
Douglas Gregor7176fff2009-01-15 00:26:24 +0000954 Paths.front().Decls.first, Paths.front().Decls.second);
955
956 // We found a non-function declaration; return a single declaration.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000957 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000958}
959
960/// @brief Performs name lookup for a name that was parsed in the
961/// source code, and may contain a C++ scope specifier.
962///
963/// This routine is a convenience routine meant to be called from
964/// contexts that receive a name and an optional C++ scope specifier
965/// (e.g., "N::M::x"). It will then perform either qualified or
966/// unqualified name lookup (with LookupQualifiedName or LookupName,
967/// respectively) on the given name and return those results.
968///
969/// @param S The scope from which unqualified name lookup will
970/// begin.
971///
972/// @param SS An optional C++ scope-specified, e.g., "::N::M".
973///
974/// @param Name The name of the entity that name lookup will
975/// search for.
976///
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000977/// @returns The result of qualified or unqualified name lookup.
978Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000979Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
980 DeclarationName Name, LookupNameKind NameKind,
981 bool RedeclarationOnly) {
982 if (SS) {
983 if (SS->isInvalid())
984 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000985
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000986 if (SS->isSet())
987 return LookupQualifiedName(static_cast<DeclContext *>(SS->getScopeRep()),
988 Name, NameKind, RedeclarationOnly);
989 }
990
991 return LookupName(S, Name, NameKind, RedeclarationOnly);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000992}
993
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000994
Douglas Gregor7176fff2009-01-15 00:26:24 +0000995/// @brief Produce a diagnostic describing the ambiguity that resulted
996/// from name lookup.
997///
998/// @param Result The ambiguous name lookup result.
999///
1000/// @param Name The name of the entity that name lookup was
1001/// searching for.
1002///
1003/// @param NameLoc The location of the name within the source code.
1004///
1005/// @param LookupRange A source range that provides more
1006/// source-location information concerning the lookup itself. For
1007/// example, this range might highlight a nested-name-specifier that
1008/// precedes the name.
1009///
1010/// @returns true
1011bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1012 SourceLocation NameLoc,
1013 SourceRange LookupRange) {
1014 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1015
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001016 if (BasePaths *Paths = Result.getBasePaths())
1017 {
1018 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1019 QualType SubobjectType = Paths->front().back().Base->getType();
1020 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1021 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1022 << LookupRange;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001023
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001024 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1025 while (isa<CXXMethodDecl>(*Found) && cast<CXXMethodDecl>(*Found)->isStatic())
1026 ++Found;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001027
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001028 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1029
1030 return true;
1031 }
1032
1033 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1034 "Unhandled form of name lookup ambiguity");
1035
1036 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1037 << Name << LookupRange;
1038
1039 std::set<Decl *> DeclsPrinted;
1040 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1041 Path != PathEnd; ++Path) {
1042 Decl *D = *Path->Decls.first;
1043 if (DeclsPrinted.insert(D).second)
1044 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1045 }
1046
1047 delete Paths;
1048 return true;
1049 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
1050
1051 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1052
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001053 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
1054 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001055
Chris Lattner48458d22009-02-03 21:29:32 +00001056 for (; DI != DEnd; ++DI)
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001057 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001058
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001059 delete[] reinterpret_cast<NamedDecl **>(Result.First);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00001060
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001061 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001062 }
1063
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001064 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregor69d993a2009-01-17 01:13:24 +00001065
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001066 // We can't reach here.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001067 return true;
1068}
Douglas Gregorfa047642009-02-04 00:32:51 +00001069
1070// \brief Add the associated classes and namespaces for
1071// argument-dependent lookup with an argument of class type
1072// (C++ [basic.lookup.koenig]p2).
1073static void
1074addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1075 ASTContext &Context,
1076 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1077 Sema::AssociatedClassSet &AssociatedClasses) {
1078 // C++ [basic.lookup.koenig]p2:
1079 // [...]
1080 // -- If T is a class type (including unions), its associated
1081 // classes are: the class itself; the class of which it is a
1082 // member, if any; and its direct and indirect base
1083 // classes. Its associated namespaces are the namespaces in
1084 // which its associated classes are defined.
1085
1086 // Add the class of which it is a member, if any.
1087 DeclContext *Ctx = Class->getDeclContext();
1088 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1089 AssociatedClasses.insert(EnclosingClass);
1090
1091 // Add the associated namespace for this class.
1092 while (Ctx->isRecord())
1093 Ctx = Ctx->getParent();
1094 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1095 AssociatedNamespaces.insert(EnclosingNamespace);
1096
1097 // Add the class itself. If we've already seen this class, we don't
1098 // need to visit base classes.
1099 if (!AssociatedClasses.insert(Class))
1100 return;
1101
1102 // FIXME: Handle class template specializations
1103
1104 // Add direct and indirect base classes along with their associated
1105 // namespaces.
1106 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1107 Bases.push_back(Class);
1108 while (!Bases.empty()) {
1109 // Pop this class off the stack.
1110 Class = Bases.back();
1111 Bases.pop_back();
1112
1113 // Visit the base classes.
1114 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1115 BaseEnd = Class->bases_end();
1116 Base != BaseEnd; ++Base) {
1117 const RecordType *BaseType = Base->getType()->getAsRecordType();
1118 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1119 if (AssociatedClasses.insert(BaseDecl)) {
1120 // Find the associated namespace for this base class.
1121 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1122 while (BaseCtx->isRecord())
1123 BaseCtx = BaseCtx->getParent();
1124 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1125 AssociatedNamespaces.insert(EnclosingNamespace);
1126
1127 // Make sure we visit the bases of this base class.
1128 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1129 Bases.push_back(BaseDecl);
1130 }
1131 }
1132 }
1133}
1134
1135// \brief Add the associated classes and namespaces for
1136// argument-dependent lookup with an argument of type T
1137// (C++ [basic.lookup.koenig]p2).
1138static void
1139addAssociatedClassesAndNamespaces(QualType T,
1140 ASTContext &Context,
1141 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1142 Sema::AssociatedClassSet &AssociatedClasses) {
1143 // C++ [basic.lookup.koenig]p2:
1144 //
1145 // For each argument type T in the function call, there is a set
1146 // of zero or more associated namespaces and a set of zero or more
1147 // associated classes to be considered. The sets of namespaces and
1148 // classes is determined entirely by the types of the function
1149 // arguments (and the namespace of any template template
1150 // argument). Typedef names and using-declarations used to specify
1151 // the types do not contribute to this set. The sets of namespaces
1152 // and classes are determined in the following way:
1153 T = Context.getCanonicalType(T).getUnqualifiedType();
1154
1155 // -- If T is a pointer to U or an array of U, its associated
1156 // namespaces and classes are those associated with U.
1157 //
1158 // We handle this by unwrapping pointer and array types immediately,
1159 // to avoid unnecessary recursion.
1160 while (true) {
1161 if (const PointerType *Ptr = T->getAsPointerType())
1162 T = Ptr->getPointeeType();
1163 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1164 T = Ptr->getElementType();
1165 else
1166 break;
1167 }
1168
1169 // -- If T is a fundamental type, its associated sets of
1170 // namespaces and classes are both empty.
1171 if (T->getAsBuiltinType())
1172 return;
1173
1174 // -- If T is a class type (including unions), its associated
1175 // classes are: the class itself; the class of which it is a
1176 // member, if any; and its direct and indirect base
1177 // classes. Its associated namespaces are the namespaces in
1178 // which its associated classes are defined.
1179 if (const CXXRecordType *ClassType
1180 = dyn_cast_or_null<CXXRecordType>(T->getAsRecordType())) {
1181 addAssociatedClassesAndNamespaces(ClassType->getDecl(),
1182 Context, AssociatedNamespaces,
1183 AssociatedClasses);
1184 return;
1185 }
1186
1187 // -- If T is an enumeration type, its associated namespace is
1188 // the namespace in which it is defined. If it is class
1189 // member, its associated class is the member’s class; else
1190 // it has no associated class.
1191 if (const EnumType *EnumT = T->getAsEnumType()) {
1192 EnumDecl *Enum = EnumT->getDecl();
1193
1194 DeclContext *Ctx = Enum->getDeclContext();
1195 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1196 AssociatedClasses.insert(EnclosingClass);
1197
1198 // Add the associated namespace for this class.
1199 while (Ctx->isRecord())
1200 Ctx = Ctx->getParent();
1201 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1202 AssociatedNamespaces.insert(EnclosingNamespace);
1203
1204 return;
1205 }
1206
1207 // -- If T is a function type, its associated namespaces and
1208 // classes are those associated with the function parameter
1209 // types and those associated with the return type.
1210 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1211 // Return type
1212 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1213 Context,
1214 AssociatedNamespaces, AssociatedClasses);
1215
1216 const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FunctionType);
1217 if (!Proto)
1218 return;
1219
1220 // Argument types
1221 for (FunctionTypeProto::arg_type_iterator Arg = Proto->arg_type_begin(),
1222 ArgEnd = Proto->arg_type_end();
1223 Arg != ArgEnd; ++Arg)
1224 addAssociatedClassesAndNamespaces(*Arg, Context,
1225 AssociatedNamespaces, AssociatedClasses);
1226
1227 return;
1228 }
1229
1230 // -- If T is a pointer to a member function of a class X, its
1231 // associated namespaces and classes are those associated
1232 // with the function parameter types and return type,
1233 // together with those associated with X.
1234 //
1235 // -- If T is a pointer to a data member of class X, its
1236 // associated namespaces and classes are those associated
1237 // with the member type together with those associated with
1238 // X.
1239 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1240 // Handle the type that the pointer to member points to.
1241 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1242 Context,
1243 AssociatedNamespaces, AssociatedClasses);
1244
1245 // Handle the class type into which this points.
1246 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1247 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1248 Context,
1249 AssociatedNamespaces, AssociatedClasses);
1250
1251 return;
1252 }
1253
1254 // FIXME: What about block pointers?
1255 // FIXME: What about Objective-C message sends?
1256}
1257
1258/// \brief Find the associated classes and namespaces for
1259/// argument-dependent lookup for a call with the given set of
1260/// arguments.
1261///
1262/// This routine computes the sets of associated classes and associated
1263/// namespaces searched by argument-dependent lookup
1264/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1265void
1266Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1267 AssociatedNamespaceSet &AssociatedNamespaces,
1268 AssociatedClassSet &AssociatedClasses) {
1269 AssociatedNamespaces.clear();
1270 AssociatedClasses.clear();
1271
1272 // C++ [basic.lookup.koenig]p2:
1273 // For each argument type T in the function call, there is a set
1274 // of zero or more associated namespaces and a set of zero or more
1275 // associated classes to be considered. The sets of namespaces and
1276 // classes is determined entirely by the types of the function
1277 // arguments (and the namespace of any template template
1278 // argument).
1279 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1280 Expr *Arg = Args[ArgIdx];
1281
1282 if (Arg->getType() != Context.OverloadTy) {
1283 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
1284 AssociatedNamespaces, AssociatedClasses);
1285 continue;
1286 }
1287
1288 // [...] In addition, if the argument is the name or address of a
1289 // set of overloaded functions and/or function templates, its
1290 // associated classes and namespaces are the union of those
1291 // associated with each of the members of the set: the namespace
1292 // in which the function or function template is defined and the
1293 // classes and namespaces associated with its (non-dependent)
1294 // parameter types and return type.
1295 DeclRefExpr *DRE = 0;
1296 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1297 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1298 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1299 } else
1300 DRE = dyn_cast<DeclRefExpr>(Arg);
1301 if (!DRE)
1302 continue;
1303
1304 OverloadedFunctionDecl *Ovl
1305 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1306 if (!Ovl)
1307 continue;
1308
1309 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1310 FuncEnd = Ovl->function_end();
1311 Func != FuncEnd; ++Func) {
1312 FunctionDecl *FDecl = cast<FunctionDecl>(*Func);
1313
1314 // Add the namespace in which this function was defined. Note
1315 // that, if this is a member function, we do *not* consider the
1316 // enclosing namespace of its class.
1317 DeclContext *Ctx = FDecl->getDeclContext();
1318 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1319 AssociatedNamespaces.insert(EnclosingNamespace);
1320
1321 // Add the classes and namespaces associated with the parameter
1322 // types and return type of this function.
1323 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
1324 AssociatedNamespaces, AssociatedClasses);
1325 }
1326 }
1327}