blob: 69bd5602d3faee6278fb42e53376b9c9a39ea8f1 [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 {
Chris Lattner5261d0c2009-03-28 19:18:32 +000087 Scope::udir_iterator I = S->using_directives_begin(),
88 End = S->using_directives_end();
Douglas Gregor7a7be652009-02-03 19:21:40 +000089
90 for (; I != End; ++I) {
Chris Lattner5261d0c2009-03-28 19:18:32 +000091 UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>();
Douglas Gregor7a7be652009-02-03 19:21:40 +000092 UDirs.push_back(UD);
93 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
94
95 NamespaceDecl *Nominated = UD->getNominatedNamespace();
96 if (!VisitedNS.count(Nominated)) {
97 VisitedNS.insert(Nominated);
98 AddNamespaceUsingDirectives(Nominated, UDirs, /*ref*/ VisitedNS);
99 }
100 }
101 }
102}
103
Douglas Gregor78d70132009-01-14 22:20:51 +0000104/// MaybeConstructOverloadSet - Name lookup has determined that the
105/// elements in [I, IEnd) have the name that we are looking for, and
106/// *I is a match for the namespace. This routine returns an
107/// appropriate Decl for name lookup, which may either be *I or an
Douglas Gregor7a7be652009-02-03 19:21:40 +0000108/// OverloadedFunctionDecl that represents the overloaded functions in
Douglas Gregor78d70132009-01-14 22:20:51 +0000109/// [I, IEnd).
110///
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000111/// The existance of this routine is temporary; users of LookupResult
112/// should be able to handle multiple results, to deal with cases of
Douglas Gregor78d70132009-01-14 22:20:51 +0000113/// ambiguity and overloaded functions without needing to create a
114/// Decl node.
115template<typename DeclIterator>
Douglas Gregor09be81b2009-02-04 17:27:36 +0000116static NamedDecl *
Douglas Gregor78d70132009-01-14 22:20:51 +0000117MaybeConstructOverloadSet(ASTContext &Context,
118 DeclIterator I, DeclIterator IEnd) {
119 assert(I != IEnd && "Iterator range cannot be empty");
120 assert(!isa<OverloadedFunctionDecl>(*I) &&
121 "Cannot have an overloaded function");
122
123 if (isa<FunctionDecl>(*I)) {
124 // If we found a function, there might be more functions. If
125 // so, collect them into an overload set.
126 DeclIterator Last = I;
127 OverloadedFunctionDecl *Ovl = 0;
128 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
129 if (!Ovl) {
130 // FIXME: We leak this overload set. Eventually, we want to
131 // stop building the declarations for these overload sets, so
132 // there will be nothing to leak.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000133 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
Douglas Gregor78d70132009-01-14 22:20:51 +0000134 (*I)->getDeclName());
135 Ovl->addOverload(cast<FunctionDecl>(*I));
136 }
137 Ovl->addOverload(cast<FunctionDecl>(*Last));
138 }
139
140 // If we had more than one function, we built an overload
141 // set. Return it.
142 if (Ovl)
143 return Ovl;
144 }
145
146 return *I;
147}
148
Douglas Gregor7a7be652009-02-03 19:21:40 +0000149/// Merges together multiple LookupResults dealing with duplicated Decl's.
150static Sema::LookupResult
151MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
152 typedef Sema::LookupResult LResult;
Douglas Gregor09be81b2009-02-04 17:27:36 +0000153 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000154
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000155 // Remove duplicated Decl pointing at same Decl, by storing them in
156 // associative collection. This might be case for code like:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000157 //
158 // namespace A { int i; }
159 // namespace B { using namespace A; }
160 // namespace C { using namespace A; }
161 //
162 // void foo() {
163 // using namespace B;
164 // using namespace C;
165 // ++i; // finds A::i, from both namespace B and C at global scope
166 // }
167 //
168 // C++ [namespace.qual].p3:
169 // The same declaration found more than once is not an ambiguity
170 // (because it is still a unique declaration).
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000171 DeclsSetTy FoundDecls;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000172
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000173 // Counter of tag names, and functions for resolving ambiguity
174 // and name hiding.
175 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
Douglas Gregor09be81b2009-02-04 17:27:36 +0000176
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000177 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
178
179 // No name lookup results, return early.
180 if (I == End) return LResult::CreateLookupResult(Context, 0);
181
182 // Keep track of the tag declaration we found. We only use this if
183 // we find a single tag declaration.
184 TagDecl *TagFound = 0;
185
186 for (; I != End; ++I) {
187 switch (I->getKind()) {
188 case LResult::NotFound:
189 assert(false &&
190 "Should be always successful name lookup result here.");
191 break;
192
193 case LResult::AmbiguousReference:
194 case LResult::AmbiguousBaseSubobjectTypes:
195 case LResult::AmbiguousBaseSubobjects:
196 assert(false && "Shouldn't get ambiguous lookup here.");
197 break;
198
199 case LResult::Found: {
200 NamedDecl *ND = I->getAsDecl();
201 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
202 TagFound = Context.getCanonicalDecl(TD);
203 TagNames += FoundDecls.insert(TagFound)? 1 : 0;
204 } else if (isa<FunctionDecl>(ND))
205 Functions += FoundDecls.insert(ND)? 1 : 0;
206 else
207 FoundDecls.insert(ND);
208 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000209 }
210
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000211 case LResult::FoundOverloaded:
212 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
213 Functions += FoundDecls.insert(*FI)? 1 : 0;
214 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000215 }
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000216 }
217 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
218 bool Ambiguous = false, NameHidesTags = false;
219
220 if (FoundDecls.size() == 1) {
221 // 1) Exactly one result.
222 } else if (TagNames > 1) {
223 // 2) Multiple tag names (even though they may be hidden by an
224 // object name).
225 Ambiguous = true;
226 } else if (FoundDecls.size() - TagNames == 1) {
227 // 3) Ordinary name hides (optional) tag.
228 NameHidesTags = TagFound;
229 } else if (Functions) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000230 // C++ [basic.lookup].p1:
231 // ... Name lookup may associate more than one declaration with
Douglas Gregor7a7be652009-02-03 19:21:40 +0000232 // a name if it finds the name to be a function name; the declarations
233 // are said to form a set of overloaded functions (13.1).
234 // Overload resolution (13.3) takes place after name lookup has succeeded.
Douglas Gregor09be81b2009-02-04 17:27:36 +0000235 //
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000236 if (!OrdinaryNonFunc) {
237 // 4) Functions hide tag names.
238 NameHidesTags = TagFound;
239 } else {
240 // 5) Functions + ordinary names.
241 Ambiguous = true;
242 }
243 } else {
244 // 6) Multiple non-tag names
245 Ambiguous = true;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000246 }
247
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000248 if (Ambiguous)
249 return LResult::CreateLookupResult(Context,
250 FoundDecls.begin(), FoundDecls.size());
251 if (NameHidesTags) {
252 // There's only one tag, TagFound. Remove it.
253 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
254 FoundDecls.erase(TagFound);
255 }
256
257 // Return successful name lookup result.
258 return LResult::CreateLookupResult(Context,
259 MaybeConstructOverloadSet(Context,
260 FoundDecls.begin(),
261 FoundDecls.end()));
Douglas Gregor7a7be652009-02-03 19:21:40 +0000262}
263
264// Retrieve the set of identifier namespaces that correspond to a
265// specific kind of name lookup.
266inline unsigned
267getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
268 bool CPlusPlus) {
269 unsigned IDNS = 0;
270 switch (NameKind) {
271 case Sema::LookupOrdinaryName:
Douglas Gregor48a87322009-02-04 16:44:47 +0000272 case Sema::LookupOperatorName:
Douglas Gregor1c52c632009-02-24 20:03:32 +0000273 case Sema::LookupRedeclarationWithLinkage:
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.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000577 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000578 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) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000585 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor7a7be652009-02-03 19:21:40 +0000586 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.
Douglas Gregord3c78592009-03-27 04:21:56 +0000602 if (isa<RecordDecl>(Ctx)) {
603 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
604 if (R || RedeclarationOnly)
605 return std::make_pair(true, R);
606 }
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000607 if (Ctx->getParent() != Ctx->getLexicalParent()) {
608 // It is out of line defined C++ method or struct, we continue
609 // doing name lookup in parent context. Once we will find namespace
610 // or translation-unit we save it for possible checking
611 // using-directives later.
612 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
613 OutOfLineCtx = OutOfLineCtx->getParent()) {
Douglas Gregord3c78592009-03-27 04:21:56 +0000614 R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
615 if (R || RedeclarationOnly)
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000616 return std::make_pair(true, R);
617 }
618 }
619 }
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000620 }
Douglas Gregor7a7be652009-02-03 19:21:40 +0000621
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000622 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor7a7be652009-02-03 19:21:40 +0000623 // nominated namespaces by those using-directives.
624 // UsingDirectives are pushed to heap, in common ancestor pointer
625 // value order.
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000626 // FIXME: Cache this sorted list in Scope structure, and DeclContext,
627 // so we don't build it for each lookup!
Douglas Gregor7a7be652009-02-03 19:21:40 +0000628 UsingDirectivesTy UDirs;
629 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor09be81b2009-02-04 17:27:36 +0000630 if (SC->getFlags() & Scope::DeclScope)
631 AddScopeUsingDirectives(SC, UDirs);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000632
633 // Sort heapified UsingDirectiveDecls.
634 std::sort_heap(UDirs.begin(), UDirs.end());
635
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000636 // Lookup namespace scope, and global scope.
Douglas Gregor7a7be652009-02-03 19:21:40 +0000637 // Unqualified name lookup in C++ requires looking into scopes
638 // that aren't strictly lexical, and therefore we walk through the
639 // context as well as walking through the scopes.
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000640
641 LookupResultsTy LookupResults;
Sebastian Redl95216a62009-02-07 00:15:38 +0000642 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000643 "We should have been looking only at file context here already.");
644 bool LookedInCtx = false;
645 LookupResult Result;
646 while (OutOfLineCtx &&
647 OutOfLineCtx != S->getEntity() &&
648 OutOfLineCtx->isNamespace()) {
649 LookedInCtx = true;
650
651 // Look into context considering using-directives.
652 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
653 LookupResults, &UDirs);
654
655 if ((Result = MergeLookupResults(Context, LookupResults)) ||
656 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
657 return std::make_pair(true, Result);
658
659 OutOfLineCtx = OutOfLineCtx->getParent();
660 }
661
Douglas Gregor7a7be652009-02-03 19:21:40 +0000662 for (; S; S = S->getParent()) {
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000663 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
664 assert(Ctx && Ctx->isFileContext() &&
665 "We should have been looking only at file context here already.");
Douglas Gregor7a7be652009-02-03 19:21:40 +0000666
667 // Check whether the IdResolver has anything in this scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000668 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000669 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
670 // We found something. Look for anything else in our scope
671 // with this same name and in an acceptable identifier
672 // namespace, so that we can construct an overload set if we
673 // need to.
674 IdentifierResolver::iterator LastI = I;
675 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000676 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor7a7be652009-02-03 19:21:40 +0000677 break;
678 }
679
680 // We store name lookup result, and continue trying to look into
681 // associated context, and maybe namespaces nominated by
682 // using-directives.
683 LookupResults.push_back(
684 LookupResult::CreateLookupResult(Context, I, LastI));
685 break;
686 }
687 }
688
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000689 LookedInCtx = true;
690 // Look into context considering using-directives.
691 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
692 LookupResults, &UDirs);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000693
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000694 if ((Result = MergeLookupResults(Context, LookupResults)) ||
695 (RedeclarationOnly && !Ctx->isTransparentContext()))
696 return std::make_pair(true, Result);
697 }
Douglas Gregor7a7be652009-02-03 19:21:40 +0000698
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000699 if (!(LookedInCtx || LookupResults.empty())) {
700 // We didn't Performed lookup in Scope entity, so we return
701 // result form IdentifierResolver.
702 assert((LookupResults.size() == 1) && "Wrong size!");
703 return std::make_pair(true, LookupResults.front());
Douglas Gregor7a7be652009-02-03 19:21:40 +0000704 }
705 return std::make_pair(false, LookupResult());
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000706}
707
Douglas Gregor78d70132009-01-14 22:20:51 +0000708/// @brief Perform unqualified name lookup starting from a given
709/// scope.
710///
711/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
712/// used to find names within the current scope. For example, 'x' in
713/// @code
714/// int x;
715/// int f() {
716/// return x; // unqualified name look finds 'x' in the global scope
717/// }
718/// @endcode
719///
720/// Different lookup criteria can find different names. For example, a
721/// particular scope can have both a struct and a function of the same
722/// name, and each can be found by certain lookup criteria. For more
723/// information about lookup criteria, see the documentation for the
724/// class LookupCriteria.
725///
726/// @param S The scope from which unqualified name lookup will
727/// begin. If the lookup criteria permits, name lookup may also search
728/// in the parent scopes.
729///
730/// @param Name The name of the entity that we are searching for.
731///
Douglas Gregor411889e2009-02-13 23:20:09 +0000732/// @param Loc If provided, the source location where we're performing
733/// name lookup. At present, this is only used to produce diagnostics when
734/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor78d70132009-01-14 22:20:51 +0000735///
736/// @returns The result of name lookup, which includes zero or more
737/// declarations and possibly additional information used to diagnose
738/// ambiguities.
739Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000740Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor411889e2009-02-13 23:20:09 +0000741 bool RedeclarationOnly, bool AllowBuiltinCreation,
742 SourceLocation Loc) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000743 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000744
745 if (!getLangOptions().CPlusPlus) {
746 // Unqualified name lookup in C/Objective-C is purely lexical, so
747 // search in the declarations attached to the name.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000748 unsigned IDNS = 0;
749 switch (NameKind) {
750 case Sema::LookupOrdinaryName:
751 IDNS = Decl::IDNS_Ordinary;
752 break;
Douglas Gregor78d70132009-01-14 22:20:51 +0000753
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000754 case Sema::LookupTagName:
755 IDNS = Decl::IDNS_Tag;
756 break;
757
758 case Sema::LookupMemberName:
759 IDNS = Decl::IDNS_Member;
760 break;
761
Douglas Gregor48a87322009-02-04 16:44:47 +0000762 case Sema::LookupOperatorName:
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000763 case Sema::LookupNestedNameSpecifierName:
764 case Sema::LookupNamespaceName:
765 assert(false && "C does not perform these kinds of name lookup");
766 break;
Douglas Gregor1c52c632009-02-24 20:03:32 +0000767
768 case Sema::LookupRedeclarationWithLinkage:
769 // Find the nearest non-transparent declaration scope.
770 while (!(S->getFlags() & Scope::DeclScope) ||
771 (S->getEntity() &&
772 static_cast<DeclContext *>(S->getEntity())
773 ->isTransparentContext()))
774 S = S->getParent();
775 IDNS = Decl::IDNS_Ordinary;
776 break;
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000777 }
778
Douglas Gregor78d70132009-01-14 22:20:51 +0000779 // Scan up the scope chain looking for a decl that matches this
780 // identifier that is in the appropriate namespace. This search
781 // should not take long, as shadowing of names is uncommon, and
782 // deep shadowing is extremely uncommon.
Douglas Gregor1c52c632009-02-24 20:03:32 +0000783 bool LeftStartingScope = false;
784
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000785 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
786 IEnd = IdResolver.end();
787 I != IEnd; ++I)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000788 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregor1c52c632009-02-24 20:03:32 +0000789 if (NameKind == LookupRedeclarationWithLinkage) {
790 // Determine whether this (or a previous) declaration is
791 // out-of-scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000792 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor1c52c632009-02-24 20:03:32 +0000793 LeftStartingScope = true;
794
795 // If we found something outside of our starting scope that
796 // does not have linkage, skip it.
797 if (LeftStartingScope && !((*I)->hasLinkage()))
798 continue;
799 }
800
Douglas Gregorfcb19192009-02-11 23:02:49 +0000801 if ((*I)->getAttr<OverloadableAttr>()) {
802 // If this declaration has the "overloadable" attribute, we
803 // might have a set of overloaded functions.
804
805 // Figure out what scope the identifier is in.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000806 while (!(S->getFlags() & Scope::DeclScope) ||
807 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorfcb19192009-02-11 23:02:49 +0000808 S = S->getParent();
809
810 // Find the last declaration in this scope (with the same
811 // name, naturally).
812 IdentifierResolver::iterator LastI = I;
813 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000814 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorfcb19192009-02-11 23:02:49 +0000815 break;
816 }
817
818 return LookupResult::CreateLookupResult(Context, I, LastI);
819 }
820
821 // We have a single lookup result.
Douglas Gregord07474b2009-01-17 01:13:24 +0000822 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregorfcb19192009-02-11 23:02:49 +0000823 }
Douglas Gregor78d70132009-01-14 22:20:51 +0000824 } else {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000825 // Perform C++ unqualified name lookup.
826 std::pair<bool, LookupResult> MaybeResult =
827 CppLookupName(S, Name, NameKind, RedeclarationOnly);
828 if (MaybeResult.first)
829 return MaybeResult.second;
Douglas Gregor78d70132009-01-14 22:20:51 +0000830 }
831
832 // If we didn't find a use of this identifier, and if the identifier
833 // corresponds to a compiler builtin, create the decl object for the builtin
834 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1c52c632009-02-24 20:03:32 +0000835 if (NameKind == LookupOrdinaryName ||
836 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000837 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor411889e2009-02-13 23:20:09 +0000838 if (II && AllowBuiltinCreation) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000839 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor411889e2009-02-13 23:20:09 +0000840 if (unsigned BuiltinID = II->getBuiltinID()) {
841 // In C++, we don't have any predefined library functions like
842 // 'malloc'. Instead, we'll just error.
843 if (getLangOptions().CPlusPlus &&
844 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
845 return LookupResult::CreateLookupResult(Context, 0);
846
Douglas Gregord07474b2009-01-17 01:13:24 +0000847 return LookupResult::CreateLookupResult(Context,
Douglas Gregor78d70132009-01-14 22:20:51 +0000848 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
Douglas Gregor411889e2009-02-13 23:20:09 +0000849 S, RedeclarationOnly, Loc));
850 }
Douglas Gregor78d70132009-01-14 22:20:51 +0000851 }
852 if (getLangOptions().ObjC1 && II) {
853 // @interface and @compatibility_alias introduce typedef-like names.
854 // Unlike typedef's, they can only be introduced at file-scope (and are
855 // therefore not scoped decls). They can, however, be shadowed by
856 // other names in IDNS_Ordinary.
857 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
858 if (IDI != ObjCInterfaceDecls.end())
Douglas Gregord07474b2009-01-17 01:13:24 +0000859 return LookupResult::CreateLookupResult(Context, IDI->second);
Douglas Gregor78d70132009-01-14 22:20:51 +0000860 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
861 if (I != ObjCAliasDecls.end())
Douglas Gregord07474b2009-01-17 01:13:24 +0000862 return LookupResult::CreateLookupResult(Context,
863 I->second->getClassInterface());
Douglas Gregor78d70132009-01-14 22:20:51 +0000864 }
865 }
Douglas Gregord07474b2009-01-17 01:13:24 +0000866 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000867}
868
869/// @brief Perform qualified name lookup into a given context.
870///
871/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
872/// names when the context of those names is explicit specified, e.g.,
873/// "std::vector" or "x->member".
874///
875/// Different lookup criteria can find different names. For example, a
876/// particular scope can have both a struct and a function of the same
877/// name, and each can be found by certain lookup criteria. For more
878/// information about lookup criteria, see the documentation for the
879/// class LookupCriteria.
880///
881/// @param LookupCtx The context in which qualified name lookup will
882/// search. If the lookup criteria permits, name lookup may also search
883/// in the parent contexts or (for C++ classes) base classes.
884///
885/// @param Name The name of the entity that we are searching for.
886///
887/// @param Criteria The criteria that this routine will use to
888/// determine which names are visible and which names will be
889/// found. Note that name lookup will find a name that is visible by
890/// the given criteria, but the entity itself may not be semantically
891/// correct or even the kind of entity expected based on the
892/// lookup. For example, searching for a nested-name-specifier name
893/// might result in an EnumDecl, which is visible but is not permitted
894/// as a nested-name-specifier in C++03.
895///
896/// @returns The result of name lookup, which includes zero or more
897/// declarations and possibly additional information used to diagnose
898/// ambiguities.
899Sema::LookupResult
900Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000901 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000902 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
903
Douglas Gregord07474b2009-01-17 01:13:24 +0000904 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000905
906 // If we're performing qualified name lookup (e.g., lookup into a
907 // struct), find fields as part of ordinary name lookup.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000908 unsigned IDNS
909 = getIdentifierNamespacesFromLookupNameKind(NameKind,
910 getLangOptions().CPlusPlus);
911 if (NameKind == LookupOrdinaryName)
912 IDNS |= Decl::IDNS_Member;
Douglas Gregor78d70132009-01-14 22:20:51 +0000913
914 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor78d70132009-01-14 22:20:51 +0000915 DeclContext::lookup_iterator I, E;
916 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000917 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregord07474b2009-01-17 01:13:24 +0000918 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregor78d70132009-01-14 22:20:51 +0000919
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000920 // If this isn't a C++ class or we aren't allowed to look into base
921 // classes, we're done.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000922 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregord07474b2009-01-17 01:13:24 +0000923 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000924
925 // Perform lookup into our base classes.
926 BasePaths Paths;
Douglas Gregorb9ef0552009-01-16 00:38:09 +0000927 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000928
929 // Look for this member in our base classes
930 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000931 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregord07474b2009-01-17 01:13:24 +0000932 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000933
934 // C++ [class.member.lookup]p2:
935 // [...] If the resulting set of declarations are not all from
936 // sub-objects of the same type, or the set has a nonstatic member
937 // and includes members from distinct sub-objects, there is an
938 // ambiguity and the program is ill-formed. Otherwise that set is
939 // the result of the lookup.
940 // FIXME: support using declarations!
941 QualType SubobjectType;
Daniel Dunbarddebeca2009-01-15 18:32:35 +0000942 int SubobjectNumber = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000943 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
944 Path != PathEnd; ++Path) {
945 const BasePathElement &PathElement = Path->back();
946
947 // Determine whether we're looking at a distinct sub-object or not.
948 if (SubobjectType.isNull()) {
949 // This is the first subobject we've looked at. Record it's type.
950 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
951 SubobjectNumber = PathElement.SubobjectNumber;
952 } else if (SubobjectType
953 != Context.getCanonicalType(PathElement.Base->getType())) {
954 // We found members of the given name in two subobjects of
955 // different types. This lookup is ambiguous.
956 BasePaths *PathsOnHeap = new BasePaths;
957 PathsOnHeap->swap(Paths);
Douglas Gregord07474b2009-01-17 01:13:24 +0000958 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000959 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
960 // We have a different subobject of the same type.
961
962 // C++ [class.member.lookup]p5:
963 // A static member, a nested type or an enumerator defined in
964 // a base class T can unambiguously be found even if an object
965 // has more than one base class subobject of type T.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000966 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000967 if (isa<VarDecl>(FirstDecl) ||
968 isa<TypeDecl>(FirstDecl) ||
969 isa<EnumConstantDecl>(FirstDecl))
970 continue;
971
972 if (isa<CXXMethodDecl>(FirstDecl)) {
973 // Determine whether all of the methods are static.
974 bool AllMethodsAreStatic = true;
975 for (DeclContext::lookup_iterator Func = Path->Decls.first;
976 Func != Path->Decls.second; ++Func) {
977 if (!isa<CXXMethodDecl>(*Func)) {
978 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
979 break;
980 }
981
982 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
983 AllMethodsAreStatic = false;
984 break;
985 }
986 }
987
988 if (AllMethodsAreStatic)
989 continue;
990 }
991
992 // We have found a nonstatic member name in multiple, distinct
993 // subobjects. Name lookup is ambiguous.
994 BasePaths *PathsOnHeap = new BasePaths;
995 PathsOnHeap->swap(Paths);
Douglas Gregord07474b2009-01-17 01:13:24 +0000996 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000997 }
998 }
999
1000 // Lookup in a base class succeeded; return these results.
1001
1002 // If we found a function declaration, return an overload set.
1003 if (isa<FunctionDecl>(*Paths.front().Decls.first))
Douglas Gregord07474b2009-01-17 01:13:24 +00001004 return LookupResult::CreateLookupResult(Context,
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001005 Paths.front().Decls.first, Paths.front().Decls.second);
1006
1007 // We found a non-function declaration; return a single declaration.
Douglas Gregord07474b2009-01-17 01:13:24 +00001008 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregor78d70132009-01-14 22:20:51 +00001009}
1010
1011/// @brief Performs name lookup for a name that was parsed in the
1012/// source code, and may contain a C++ scope specifier.
1013///
1014/// This routine is a convenience routine meant to be called from
1015/// contexts that receive a name and an optional C++ scope specifier
1016/// (e.g., "N::M::x"). It will then perform either qualified or
1017/// unqualified name lookup (with LookupQualifiedName or LookupName,
1018/// respectively) on the given name and return those results.
1019///
1020/// @param S The scope from which unqualified name lookup will
1021/// begin.
1022///
1023/// @param SS An optional C++ scope-specified, e.g., "::N::M".
1024///
1025/// @param Name The name of the entity that name lookup will
1026/// search for.
1027///
Douglas Gregor411889e2009-02-13 23:20:09 +00001028/// @param Loc If provided, the source location where we're performing
1029/// name lookup. At present, this is only used to produce diagnostics when
1030/// C library functions (like "malloc") are implicitly declared.
1031///
Douglas Gregor78d70132009-01-14 22:20:51 +00001032/// @returns The result of qualified or unqualified name lookup.
1033Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001034Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1035 DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor411889e2009-02-13 23:20:09 +00001036 bool RedeclarationOnly, bool AllowBuiltinCreation,
1037 SourceLocation Loc) {
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001038 if (SS) {
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00001039 if (SS->isInvalid() || RequireCompleteDeclContext(*SS))
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001040 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +00001041
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001042 if (SS->isSet()) {
1043 return LookupQualifiedName(computeDeclContext(*SS),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001044 Name, NameKind, RedeclarationOnly);
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001045 }
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001046 }
1047
Douglas Gregor411889e2009-02-13 23:20:09 +00001048 return LookupName(S, Name, NameKind, RedeclarationOnly,
1049 AllowBuiltinCreation, Loc);
Douglas Gregor78d70132009-01-14 22:20:51 +00001050}
1051
Douglas Gregor7a7be652009-02-03 19:21:40 +00001052
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001053/// @brief Produce a diagnostic describing the ambiguity that resulted
1054/// from name lookup.
1055///
1056/// @param Result The ambiguous name lookup result.
1057///
1058/// @param Name The name of the entity that name lookup was
1059/// searching for.
1060///
1061/// @param NameLoc The location of the name within the source code.
1062///
1063/// @param LookupRange A source range that provides more
1064/// source-location information concerning the lookup itself. For
1065/// example, this range might highlight a nested-name-specifier that
1066/// precedes the name.
1067///
1068/// @returns true
1069bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1070 SourceLocation NameLoc,
1071 SourceRange LookupRange) {
1072 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1073
Douglas Gregor7a7be652009-02-03 19:21:40 +00001074 if (BasePaths *Paths = Result.getBasePaths())
1075 {
1076 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1077 QualType SubobjectType = Paths->front().back().Base->getType();
1078 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1079 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1080 << LookupRange;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001081
Douglas Gregor7a7be652009-02-03 19:21:40 +00001082 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1083 while (isa<CXXMethodDecl>(*Found) && cast<CXXMethodDecl>(*Found)->isStatic())
1084 ++Found;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001085
Douglas Gregor7a7be652009-02-03 19:21:40 +00001086 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1087
1088 return true;
1089 }
1090
1091 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1092 "Unhandled form of name lookup ambiguity");
1093
1094 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1095 << Name << LookupRange;
1096
1097 std::set<Decl *> DeclsPrinted;
1098 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1099 Path != PathEnd; ++Path) {
1100 Decl *D = *Path->Decls.first;
1101 if (DeclsPrinted.insert(D).second)
1102 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1103 }
1104
1105 delete Paths;
1106 return true;
1107 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
1108
1109 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1110
Douglas Gregor09be81b2009-02-04 17:27:36 +00001111 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
1112 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor7a7be652009-02-03 19:21:40 +00001113
Chris Lattnerb02f5f22009-02-03 21:29:32 +00001114 for (; DI != DEnd; ++DI)
Douglas Gregor09be81b2009-02-04 17:27:36 +00001115 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor7a7be652009-02-03 19:21:40 +00001116
Douglas Gregor09be81b2009-02-04 17:27:36 +00001117 delete[] reinterpret_cast<NamedDecl **>(Result.First);
Douglas Gregor98b27542009-01-17 00:42:38 +00001118
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001119 return true;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001120 }
1121
Douglas Gregor7a7be652009-02-03 19:21:40 +00001122 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregord07474b2009-01-17 01:13:24 +00001123
Douglas Gregor7a7be652009-02-03 19:21:40 +00001124 // We can't reach here.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001125 return true;
1126}
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001127
1128// \brief Add the associated classes and namespaces for
1129// argument-dependent lookup with an argument of class type
1130// (C++ [basic.lookup.koenig]p2).
1131static void
1132addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1133 ASTContext &Context,
1134 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1135 Sema::AssociatedClassSet &AssociatedClasses) {
1136 // C++ [basic.lookup.koenig]p2:
1137 // [...]
1138 // -- If T is a class type (including unions), its associated
1139 // classes are: the class itself; the class of which it is a
1140 // member, if any; and its direct and indirect base
1141 // classes. Its associated namespaces are the namespaces in
1142 // which its associated classes are defined.
1143
1144 // Add the class of which it is a member, if any.
1145 DeclContext *Ctx = Class->getDeclContext();
1146 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1147 AssociatedClasses.insert(EnclosingClass);
1148
1149 // Add the associated namespace for this class.
1150 while (Ctx->isRecord())
1151 Ctx = Ctx->getParent();
1152 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1153 AssociatedNamespaces.insert(EnclosingNamespace);
1154
1155 // Add the class itself. If we've already seen this class, we don't
1156 // need to visit base classes.
1157 if (!AssociatedClasses.insert(Class))
1158 return;
1159
1160 // FIXME: Handle class template specializations
1161
1162 // Add direct and indirect base classes along with their associated
1163 // namespaces.
1164 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1165 Bases.push_back(Class);
1166 while (!Bases.empty()) {
1167 // Pop this class off the stack.
1168 Class = Bases.back();
1169 Bases.pop_back();
1170
1171 // Visit the base classes.
1172 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1173 BaseEnd = Class->bases_end();
1174 Base != BaseEnd; ++Base) {
1175 const RecordType *BaseType = Base->getType()->getAsRecordType();
1176 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1177 if (AssociatedClasses.insert(BaseDecl)) {
1178 // Find the associated namespace for this base class.
1179 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1180 while (BaseCtx->isRecord())
1181 BaseCtx = BaseCtx->getParent();
1182 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1183 AssociatedNamespaces.insert(EnclosingNamespace);
1184
1185 // Make sure we visit the bases of this base class.
1186 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1187 Bases.push_back(BaseDecl);
1188 }
1189 }
1190 }
1191}
1192
1193// \brief Add the associated classes and namespaces for
1194// argument-dependent lookup with an argument of type T
1195// (C++ [basic.lookup.koenig]p2).
1196static void
1197addAssociatedClassesAndNamespaces(QualType T,
1198 ASTContext &Context,
1199 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1200 Sema::AssociatedClassSet &AssociatedClasses) {
1201 // C++ [basic.lookup.koenig]p2:
1202 //
1203 // For each argument type T in the function call, there is a set
1204 // of zero or more associated namespaces and a set of zero or more
1205 // associated classes to be considered. The sets of namespaces and
1206 // classes is determined entirely by the types of the function
1207 // arguments (and the namespace of any template template
1208 // argument). Typedef names and using-declarations used to specify
1209 // the types do not contribute to this set. The sets of namespaces
1210 // and classes are determined in the following way:
1211 T = Context.getCanonicalType(T).getUnqualifiedType();
1212
1213 // -- If T is a pointer to U or an array of U, its associated
1214 // namespaces and classes are those associated with U.
1215 //
1216 // We handle this by unwrapping pointer and array types immediately,
1217 // to avoid unnecessary recursion.
1218 while (true) {
1219 if (const PointerType *Ptr = T->getAsPointerType())
1220 T = Ptr->getPointeeType();
1221 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1222 T = Ptr->getElementType();
1223 else
1224 break;
1225 }
1226
1227 // -- If T is a fundamental type, its associated sets of
1228 // namespaces and classes are both empty.
1229 if (T->getAsBuiltinType())
1230 return;
1231
1232 // -- If T is a class type (including unions), its associated
1233 // classes are: the class itself; the class of which it is a
1234 // member, if any; and its direct and indirect base
1235 // classes. Its associated namespaces are the namespaces in
1236 // which its associated classes are defined.
Douglas Gregor2e047592009-02-28 01:32:25 +00001237 if (const RecordType *ClassType = T->getAsRecordType())
1238 if (CXXRecordDecl *ClassDecl
1239 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1240 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1241 AssociatedNamespaces,
1242 AssociatedClasses);
1243 return;
1244 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001245
1246 // -- If T is an enumeration type, its associated namespace is
1247 // the namespace in which it is defined. If it is class
1248 // member, its associated class is the member’s class; else
1249 // it has no associated class.
1250 if (const EnumType *EnumT = T->getAsEnumType()) {
1251 EnumDecl *Enum = EnumT->getDecl();
1252
1253 DeclContext *Ctx = Enum->getDeclContext();
1254 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1255 AssociatedClasses.insert(EnclosingClass);
1256
1257 // Add the associated namespace for this class.
1258 while (Ctx->isRecord())
1259 Ctx = Ctx->getParent();
1260 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1261 AssociatedNamespaces.insert(EnclosingNamespace);
1262
1263 return;
1264 }
1265
1266 // -- If T is a function type, its associated namespaces and
1267 // classes are those associated with the function parameter
1268 // types and those associated with the return type.
1269 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1270 // Return type
1271 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1272 Context,
1273 AssociatedNamespaces, AssociatedClasses);
1274
Douglas Gregor4fa58902009-02-26 23:50:07 +00001275 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001276 if (!Proto)
1277 return;
1278
1279 // Argument types
Douglas Gregor4fa58902009-02-26 23:50:07 +00001280 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001281 ArgEnd = Proto->arg_type_end();
1282 Arg != ArgEnd; ++Arg)
1283 addAssociatedClassesAndNamespaces(*Arg, Context,
1284 AssociatedNamespaces, AssociatedClasses);
1285
1286 return;
1287 }
1288
1289 // -- If T is a pointer to a member function of a class X, its
1290 // associated namespaces and classes are those associated
1291 // with the function parameter types and return type,
1292 // together with those associated with X.
1293 //
1294 // -- If T is a pointer to a data member of class X, its
1295 // associated namespaces and classes are those associated
1296 // with the member type together with those associated with
1297 // X.
1298 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1299 // Handle the type that the pointer to member points to.
1300 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1301 Context,
1302 AssociatedNamespaces, AssociatedClasses);
1303
1304 // Handle the class type into which this points.
1305 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1306 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1307 Context,
1308 AssociatedNamespaces, AssociatedClasses);
1309
1310 return;
1311 }
1312
1313 // FIXME: What about block pointers?
1314 // FIXME: What about Objective-C message sends?
1315}
1316
1317/// \brief Find the associated classes and namespaces for
1318/// argument-dependent lookup for a call with the given set of
1319/// arguments.
1320///
1321/// This routine computes the sets of associated classes and associated
1322/// namespaces searched by argument-dependent lookup
1323/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1324void
1325Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1326 AssociatedNamespaceSet &AssociatedNamespaces,
1327 AssociatedClassSet &AssociatedClasses) {
1328 AssociatedNamespaces.clear();
1329 AssociatedClasses.clear();
1330
1331 // C++ [basic.lookup.koenig]p2:
1332 // For each argument type T in the function call, there is a set
1333 // of zero or more associated namespaces and a set of zero or more
1334 // associated classes to be considered. The sets of namespaces and
1335 // classes is determined entirely by the types of the function
1336 // arguments (and the namespace of any template template
1337 // argument).
1338 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1339 Expr *Arg = Args[ArgIdx];
1340
1341 if (Arg->getType() != Context.OverloadTy) {
1342 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
1343 AssociatedNamespaces, AssociatedClasses);
1344 continue;
1345 }
1346
1347 // [...] In addition, if the argument is the name or address of a
1348 // set of overloaded functions and/or function templates, its
1349 // associated classes and namespaces are the union of those
1350 // associated with each of the members of the set: the namespace
1351 // in which the function or function template is defined and the
1352 // classes and namespaces associated with its (non-dependent)
1353 // parameter types and return type.
1354 DeclRefExpr *DRE = 0;
1355 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1356 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1357 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1358 } else
1359 DRE = dyn_cast<DeclRefExpr>(Arg);
1360 if (!DRE)
1361 continue;
1362
1363 OverloadedFunctionDecl *Ovl
1364 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1365 if (!Ovl)
1366 continue;
1367
1368 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1369 FuncEnd = Ovl->function_end();
1370 Func != FuncEnd; ++Func) {
1371 FunctionDecl *FDecl = cast<FunctionDecl>(*Func);
1372
1373 // Add the namespace in which this function was defined. Note
1374 // that, if this is a member function, we do *not* consider the
1375 // enclosing namespace of its class.
1376 DeclContext *Ctx = FDecl->getDeclContext();
1377 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1378 AssociatedNamespaces.insert(EnclosingNamespace);
1379
1380 // Add the classes and namespaces associated with the parameter
1381 // types and return type of this function.
1382 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
1383 AssociatedNamespaces, AssociatedClasses);
1384 }
1385 }
1386}
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001387
1388/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1389/// an acceptable non-member overloaded operator for a call whose
1390/// arguments have types T1 (and, if non-empty, T2). This routine
1391/// implements the check in C++ [over.match.oper]p3b2 concerning
1392/// enumeration types.
1393static bool
1394IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1395 QualType T1, QualType T2,
1396 ASTContext &Context) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001397 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1398 return true;
1399
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001400 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1401 return true;
1402
1403 const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1404 if (Proto->getNumArgs() < 1)
1405 return false;
1406
1407 if (T1->isEnumeralType()) {
1408 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1409 if (Context.getCanonicalType(T1).getUnqualifiedType()
1410 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1411 return true;
1412 }
1413
1414 if (Proto->getNumArgs() < 2)
1415 return false;
1416
1417 if (!T2.isNull() && T2->isEnumeralType()) {
1418 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1419 if (Context.getCanonicalType(T2).getUnqualifiedType()
1420 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1421 return true;
1422 }
1423
1424 return false;
1425}
1426
1427void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1428 QualType T1, QualType T2,
1429 FunctionSet &Functions) {
1430 // C++ [over.match.oper]p3:
1431 // -- The set of non-member candidates is the result of the
1432 // unqualified lookup of operator@ in the context of the
1433 // expression according to the usual rules for name lookup in
1434 // unqualified function calls (3.4.2) except that all member
1435 // functions are ignored. However, if no operand has a class
1436 // type, only those non-member functions in the lookup set
1437 // that have a first parameter of type T1 or “reference to
1438 // (possibly cv-qualified) T1”, when T1 is an enumeration
1439 // type, or (if there is a right operand) a second parameter
1440 // of type T2 or “reference to (possibly cv-qualified) T2”,
1441 // when T2 is an enumeration type, are candidate functions.
1442 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1443 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1444
1445 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1446
1447 if (!Operators)
1448 return;
1449
1450 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1451 Op != OpEnd; ++Op) {
1452 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
1453 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1454 Functions.insert(FD); // FIXME: canonical FD
1455 }
1456}
1457
1458void Sema::ArgumentDependentLookup(DeclarationName Name,
1459 Expr **Args, unsigned NumArgs,
1460 FunctionSet &Functions) {
1461 // Find all of the associated namespaces and classes based on the
1462 // arguments we have.
1463 AssociatedNamespaceSet AssociatedNamespaces;
1464 AssociatedClassSet AssociatedClasses;
1465 FindAssociatedClassesAndNamespaces(Args, NumArgs,
1466 AssociatedNamespaces, AssociatedClasses);
1467
1468 // C++ [basic.lookup.argdep]p3:
1469 //
1470 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1471 // and let Y be the lookup set produced by argument dependent
1472 // lookup (defined as follows). If X contains [...] then Y is
1473 // empty. Otherwise Y is the set of declarations found in the
1474 // namespaces associated with the argument types as described
1475 // below. The set of declarations found by the lookup of the name
1476 // is the union of X and Y.
1477 //
1478 // Here, we compute Y and add its members to the overloaded
1479 // candidate set.
1480 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1481 NSEnd = AssociatedNamespaces.end();
1482 NS != NSEnd; ++NS) {
1483 // When considering an associated namespace, the lookup is the
1484 // same as the lookup performed when the associated namespace is
1485 // used as a qualifier (3.4.3.2) except that:
1486 //
1487 // -- Any using-directives in the associated namespace are
1488 // ignored.
1489 //
1490 // -- FIXME: Any namespace-scope friend functions declared in
1491 // associated classes are visible within their respective
1492 // namespaces even if they are not visible during an ordinary
1493 // lookup (11.4).
1494 DeclContext::lookup_iterator I, E;
1495 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
1496 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1497 if (!Func)
1498 break;
1499
1500 Functions.insert(Func);
1501 }
1502 }
1503}
1504