blob: 770f9301e616ea92cd8d8c262bbe48adc3fb6e84 [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 Gregord6f7e9d2009-02-24 20:03:32 +0000274 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000275 IDNS = Decl::IDNS_Ordinary;
276 if (CPlusPlus)
277 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
278 break;
279
280 case Sema::LookupTagName:
281 IDNS = Decl::IDNS_Tag;
282 break;
283
284 case Sema::LookupMemberName:
285 IDNS = Decl::IDNS_Member;
286 if (CPlusPlus)
287 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
288 break;
289
290 case Sema::LookupNestedNameSpecifierName:
291 case Sema::LookupNamespaceName:
292 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
293 break;
294 }
295 return IDNS;
296}
297
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000298Sema::LookupResult
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000299Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000300 LookupResult Result;
301 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
302 OverloadedDeclSingleDecl : SingleDecl;
303 Result.First = reinterpret_cast<uintptr_t>(D);
304 Result.Last = 0;
305 Result.Context = &Context;
306 return Result;
307}
308
Douglas Gregor4bb64e72009-01-15 02:19:31 +0000309/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000310Sema::LookupResult
311Sema::LookupResult::CreateLookupResult(ASTContext &Context,
312 IdentifierResolver::iterator F,
313 IdentifierResolver::iterator L) {
314 LookupResult Result;
315 Result.Context = &Context;
316
Douglas Gregor7176fff2009-01-15 00:26:24 +0000317 if (F != L && isa<FunctionDecl>(*F)) {
318 IdentifierResolver::iterator Next = F;
319 ++Next;
320 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000321 Result.StoredKind = OverloadedDeclFromIdResolver;
322 Result.First = F.getAsOpaqueValue();
323 Result.Last = L.getAsOpaqueValue();
324 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000325 }
326 }
327
Douglas Gregor69d993a2009-01-17 01:13:24 +0000328 Result.StoredKind = SingleDecl;
329 Result.First = reinterpret_cast<uintptr_t>(*F);
330 Result.Last = 0;
331 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000332}
333
Douglas Gregor69d993a2009-01-17 01:13:24 +0000334Sema::LookupResult
335Sema::LookupResult::CreateLookupResult(ASTContext &Context,
336 DeclContext::lookup_iterator F,
337 DeclContext::lookup_iterator L) {
338 LookupResult Result;
339 Result.Context = &Context;
340
Douglas Gregor7176fff2009-01-15 00:26:24 +0000341 if (F != L && isa<FunctionDecl>(*F)) {
342 DeclContext::lookup_iterator Next = F;
343 ++Next;
344 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000345 Result.StoredKind = OverloadedDeclFromDeclContext;
346 Result.First = reinterpret_cast<uintptr_t>(F);
347 Result.Last = reinterpret_cast<uintptr_t>(L);
348 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000349 }
350 }
351
Douglas Gregor69d993a2009-01-17 01:13:24 +0000352 Result.StoredKind = SingleDecl;
353 Result.First = reinterpret_cast<uintptr_t>(*F);
354 Result.Last = 0;
355 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000356}
357
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000358/// @brief Determine the result of name lookup.
359Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
360 switch (StoredKind) {
361 case SingleDecl:
362 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
363
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000364 case OverloadedDeclSingleDecl:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000365 case OverloadedDeclFromIdResolver:
366 case OverloadedDeclFromDeclContext:
367 return FoundOverloaded;
368
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000369 case AmbiguousLookupStoresBasePaths:
Douglas Gregor7176fff2009-01-15 00:26:24 +0000370 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000371
372 case AmbiguousLookupStoresDecls:
373 return AmbiguousReference;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000374 }
375
Douglas Gregor7176fff2009-01-15 00:26:24 +0000376 // We can't ever get here.
377 return NotFound;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000378}
379
380/// @brief Converts the result of name lookup into a single (possible
381/// NULL) pointer to a declaration.
382///
383/// The resulting declaration will either be the declaration we found
384/// (if only a single declaration was found), an
385/// OverloadedFunctionDecl (if an overloaded function was found), or
386/// NULL (if no declaration was found). This conversion must not be
387/// used anywhere where name lookup could result in an ambiguity.
388///
389/// The OverloadedFunctionDecl conversion is meant as a stop-gap
390/// solution, since it causes the OverloadedFunctionDecl to be
391/// leaked. FIXME: Eventually, there will be a better way to iterate
392/// over the set of overloaded functions returned by name lookup.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000393NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000394 switch (StoredKind) {
395 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000396 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000397
398 case OverloadedDeclFromIdResolver:
399 return MaybeConstructOverloadSet(*Context,
400 IdentifierResolver::iterator::getFromOpaqueValue(First),
401 IdentifierResolver::iterator::getFromOpaqueValue(Last));
402
403 case OverloadedDeclFromDeclContext:
404 return MaybeConstructOverloadSet(*Context,
405 reinterpret_cast<DeclContext::lookup_iterator>(First),
406 reinterpret_cast<DeclContext::lookup_iterator>(Last));
407
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000408 case OverloadedDeclSingleDecl:
409 return reinterpret_cast<OverloadedFunctionDecl*>(First);
410
411 case AmbiguousLookupStoresDecls:
412 case AmbiguousLookupStoresBasePaths:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000413 assert(false &&
414 "Name lookup returned an ambiguity that could not be handled");
415 break;
416 }
417
418 return 0;
419}
420
Douglas Gregor7176fff2009-01-15 00:26:24 +0000421/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000422/// name lookup, or null.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000423BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000424 if (StoredKind == AmbiguousLookupStoresBasePaths)
425 return reinterpret_cast<BasePaths *>(First);
426 return 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000427}
428
Douglas Gregord8635172009-02-02 21:35:47 +0000429Sema::LookupResult::iterator::reference
430Sema::LookupResult::iterator::operator*() const {
431 switch (Result->StoredKind) {
432 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000433 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000434
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000435 case OverloadedDeclSingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000436 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000437
Douglas Gregord8635172009-02-02 21:35:47 +0000438 case OverloadedDeclFromIdResolver:
439 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
440
441 case OverloadedDeclFromDeclContext:
442 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000443
444 case AmbiguousLookupStoresDecls:
445 case AmbiguousLookupStoresBasePaths:
Douglas Gregord8635172009-02-02 21:35:47 +0000446 assert(false && "Cannot look into ambiguous lookup results");
447 break;
448 }
449
450 return 0;
451}
452
453Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
454 switch (Result->StoredKind) {
455 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000456 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregord8635172009-02-02 21:35:47 +0000457 break;
458
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000459 case OverloadedDeclSingleDecl: {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000460 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000461 ++I;
462 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000463 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000464 }
465
Douglas Gregord8635172009-02-02 21:35:47 +0000466 case OverloadedDeclFromIdResolver: {
467 IdentifierResolver::iterator I
468 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
469 ++I;
470 Current = I.getAsOpaqueValue();
471 break;
472 }
473
474 case OverloadedDeclFromDeclContext: {
475 DeclContext::lookup_iterator I
476 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
477 ++I;
478 Current = reinterpret_cast<uintptr_t>(I);
479 break;
480 }
481
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000482 case AmbiguousLookupStoresDecls:
483 case AmbiguousLookupStoresBasePaths:
Douglas Gregord8635172009-02-02 21:35:47 +0000484 assert(false && "Cannot look into ambiguous lookup results");
485 break;
486 }
487
488 return *this;
489}
490
491Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000492 assert(!isAmbiguous() && "Lookup into an ambiguous result");
493 if (StoredKind != OverloadedDeclSingleDecl)
494 return iterator(this, First);
495 OverloadedFunctionDecl * Ovl =
496 reinterpret_cast<OverloadedFunctionDecl*>(First);
497 return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
Douglas Gregord8635172009-02-02 21:35:47 +0000498}
499
500Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000501 assert(!isAmbiguous() && "Lookup into an ambiguous result");
502 if (StoredKind != OverloadedDeclSingleDecl)
503 return iterator(this, Last);
504 OverloadedFunctionDecl * Ovl =
505 reinterpret_cast<OverloadedFunctionDecl*>(First);
506 return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
Douglas Gregord8635172009-02-02 21:35:47 +0000507}
508
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000509static void
510CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
511 DeclarationName Name, Sema::LookupNameKind NameKind,
512 unsigned IDNS, LookupResultsTy &Results,
513 UsingDirectivesTy *UDirs = 0) {
514
515 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
516
517 // Perform qualified name lookup into the LookupCtx.
518 DeclContext::lookup_iterator I, E;
519 for (llvm::tie(I, E) = NS->lookup(Name); I != E; ++I)
520 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
521 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
522 break;
523 }
524
525 if (UDirs) {
526 // For each UsingDirectiveDecl, which common ancestor is equal
527 // to NS, we preform qualified name lookup into namespace nominated by it.
528 UsingDirectivesTy::const_iterator UI, UEnd;
529 llvm::tie(UI, UEnd) =
530 std::equal_range(UDirs->begin(), UDirs->end(), NS,
531 UsingDirAncestorCompare());
532
533 for (; UI != UEnd; ++UI)
534 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
535 Name, NameKind, IDNS, Results);
536 }
537}
538
539static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000540 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000541 return Ctx->isFileContext();
542 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000543}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000544
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000545std::pair<bool, Sema::LookupResult>
546Sema::CppLookupName(Scope *S, DeclarationName Name,
547 LookupNameKind NameKind, bool RedeclarationOnly) {
548 assert(getLangOptions().CPlusPlus &&
549 "Can perform only C++ lookup");
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000550 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000551 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000552 Scope *Initial = S;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000553 DeclContext *OutOfLineCtx = 0;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000554 IdentifierResolver::iterator
555 I = IdResolver.begin(Name),
556 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000557
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000558 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000559 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000560 // ...During unqualified name lookup (3.4.1), the names appear as if
561 // they were declared in the nearest enclosing namespace which contains
562 // both the using-directive and the nominated namespace.
563 // [Note: in this context, “contains” means “contains directly or
564 // indirectly”.
565 //
566 // For example:
567 // namespace A { int i; }
568 // void foo() {
569 // int i;
570 // {
571 // using namespace A;
572 // ++i; // finds local 'i', A::i appears at global scope
573 // }
574 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000575 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000576 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000577 // Check whether the IdResolver has anything in this scope.
578 for (; I != IEnd && S->isDeclScope(*I); ++I) {
579 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
580 // We found something. Look for anything else in our scope
581 // with this same name and in an acceptable identifier
582 // namespace, so that we can construct an overload set if we
583 // need to.
584 IdentifierResolver::iterator LastI = I;
585 for (++LastI; LastI != IEnd; ++LastI) {
586 if (!S->isDeclScope(*LastI))
587 break;
588 }
589 LookupResult Result =
590 LookupResult::CreateLookupResult(Context, I, LastI);
591 return std::make_pair(true, Result);
592 }
593 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000594 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
595 LookupResult R;
596 // Perform member lookup into struct.
597 // FIXME: In some cases, we know that every name that could be
598 // found by this qualified name lookup will also be on the
599 // identifier chain. For example, inside a class without any
600 // base classes, we never need to perform qualified lookup
601 // because all of the members are on top of the identifier
602 // chain.
Douglas Gregor551f48c2009-03-27 04:21:56 +0000603 if (isa<RecordDecl>(Ctx)) {
604 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
605 if (R || RedeclarationOnly)
606 return std::make_pair(true, R);
607 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000608 if (Ctx->getParent() != Ctx->getLexicalParent()) {
609 // It is out of line defined C++ method or struct, we continue
610 // doing name lookup in parent context. Once we will find namespace
611 // or translation-unit we save it for possible checking
612 // using-directives later.
613 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
614 OutOfLineCtx = OutOfLineCtx->getParent()) {
Douglas Gregor551f48c2009-03-27 04:21:56 +0000615 R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
616 if (R || RedeclarationOnly)
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000617 return std::make_pair(true, R);
618 }
619 }
620 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000621 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000622
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000623 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000624 // nominated namespaces by those using-directives.
625 // UsingDirectives are pushed to heap, in common ancestor pointer
626 // value order.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000627 // FIXME: Cache this sorted list in Scope structure, and DeclContext,
628 // so we don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000629 UsingDirectivesTy UDirs;
630 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000631 if (SC->getFlags() & Scope::DeclScope)
632 AddScopeUsingDirectives(SC, UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000633
634 // Sort heapified UsingDirectiveDecls.
635 std::sort_heap(UDirs.begin(), UDirs.end());
636
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000637 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000638 // Unqualified name lookup in C++ requires looking into scopes
639 // that aren't strictly lexical, and therefore we walk through the
640 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000641
642 LookupResultsTy LookupResults;
Sebastian Redl22460502009-02-07 00:15:38 +0000643 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000644 "We should have been looking only at file context here already.");
645 bool LookedInCtx = false;
646 LookupResult Result;
647 while (OutOfLineCtx &&
648 OutOfLineCtx != S->getEntity() &&
649 OutOfLineCtx->isNamespace()) {
650 LookedInCtx = true;
651
652 // Look into context considering using-directives.
653 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
654 LookupResults, &UDirs);
655
656 if ((Result = MergeLookupResults(Context, LookupResults)) ||
657 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
658 return std::make_pair(true, Result);
659
660 OutOfLineCtx = OutOfLineCtx->getParent();
661 }
662
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000663 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000664 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
665 assert(Ctx && Ctx->isFileContext() &&
666 "We should have been looking only at file context here already.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000667
668 // Check whether the IdResolver has anything in this scope.
669 for (; I != IEnd && S->isDeclScope(*I); ++I) {
670 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
671 // We found something. Look for anything else in our scope
672 // with this same name and in an acceptable identifier
673 // namespace, so that we can construct an overload set if we
674 // need to.
675 IdentifierResolver::iterator LastI = I;
676 for (++LastI; LastI != IEnd; ++LastI) {
677 if (!S->isDeclScope(*LastI))
678 break;
679 }
680
681 // We store name lookup result, and continue trying to look into
682 // associated context, and maybe namespaces nominated by
683 // using-directives.
684 LookupResults.push_back(
685 LookupResult::CreateLookupResult(Context, I, LastI));
686 break;
687 }
688 }
689
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000690 LookedInCtx = true;
691 // Look into context considering using-directives.
692 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
693 LookupResults, &UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000694
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000695 if ((Result = MergeLookupResults(Context, LookupResults)) ||
696 (RedeclarationOnly && !Ctx->isTransparentContext()))
697 return std::make_pair(true, Result);
698 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000699
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000700 if (!(LookedInCtx || LookupResults.empty())) {
701 // We didn't Performed lookup in Scope entity, so we return
702 // result form IdentifierResolver.
703 assert((LookupResults.size() == 1) && "Wrong size!");
704 return std::make_pair(true, LookupResults.front());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000705 }
706 return std::make_pair(false, LookupResult());
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000707}
708
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000709/// @brief Perform unqualified name lookup starting from a given
710/// scope.
711///
712/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
713/// used to find names within the current scope. For example, 'x' in
714/// @code
715/// int x;
716/// int f() {
717/// return x; // unqualified name look finds 'x' in the global scope
718/// }
719/// @endcode
720///
721/// Different lookup criteria can find different names. For example, a
722/// particular scope can have both a struct and a function of the same
723/// name, and each can be found by certain lookup criteria. For more
724/// information about lookup criteria, see the documentation for the
725/// class LookupCriteria.
726///
727/// @param S The scope from which unqualified name lookup will
728/// begin. If the lookup criteria permits, name lookup may also search
729/// in the parent scopes.
730///
731/// @param Name The name of the entity that we are searching for.
732///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000733/// @param Loc If provided, the source location where we're performing
734/// name lookup. At present, this is only used to produce diagnostics when
735/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000736///
737/// @returns The result of name lookup, which includes zero or more
738/// declarations and possibly additional information used to diagnose
739/// ambiguities.
740Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000741Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000742 bool RedeclarationOnly, bool AllowBuiltinCreation,
743 SourceLocation Loc) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000744 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000745
746 if (!getLangOptions().CPlusPlus) {
747 // Unqualified name lookup in C/Objective-C is purely lexical, so
748 // search in the declarations attached to the name.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000749 unsigned IDNS = 0;
750 switch (NameKind) {
751 case Sema::LookupOrdinaryName:
752 IDNS = Decl::IDNS_Ordinary;
753 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000754
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000755 case Sema::LookupTagName:
756 IDNS = Decl::IDNS_Tag;
757 break;
758
759 case Sema::LookupMemberName:
760 IDNS = Decl::IDNS_Member;
761 break;
762
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000763 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000764 case Sema::LookupNestedNameSpecifierName:
765 case Sema::LookupNamespaceName:
766 assert(false && "C does not perform these kinds of name lookup");
767 break;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000768
769 case Sema::LookupRedeclarationWithLinkage:
770 // Find the nearest non-transparent declaration scope.
771 while (!(S->getFlags() & Scope::DeclScope) ||
772 (S->getEntity() &&
773 static_cast<DeclContext *>(S->getEntity())
774 ->isTransparentContext()))
775 S = S->getParent();
776 IDNS = Decl::IDNS_Ordinary;
777 break;
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000778 }
779
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000780 // Scan up the scope chain looking for a decl that matches this
781 // identifier that is in the appropriate namespace. This search
782 // should not take long, as shadowing of names is uncommon, and
783 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000784 bool LeftStartingScope = false;
785
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000786 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
787 IEnd = IdResolver.end();
788 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000789 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000790 if (NameKind == LookupRedeclarationWithLinkage) {
791 // Determine whether this (or a previous) declaration is
792 // out-of-scope.
793 if (!LeftStartingScope && !S->isDeclScope(*I))
794 LeftStartingScope = true;
795
796 // If we found something outside of our starting scope that
797 // does not have linkage, skip it.
798 if (LeftStartingScope && !((*I)->hasLinkage()))
799 continue;
800 }
801
Douglas Gregorf9201e02009-02-11 23:02:49 +0000802 if ((*I)->getAttr<OverloadableAttr>()) {
803 // If this declaration has the "overloadable" attribute, we
804 // might have a set of overloaded functions.
805
806 // Figure out what scope the identifier is in.
807 while (!(S->getFlags() & Scope::DeclScope) || !S->isDeclScope(*I))
808 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) {
814 if (!S->isDeclScope(*LastI))
815 break;
816 }
817
818 return LookupResult::CreateLookupResult(Context, I, LastI);
819 }
820
821 // We have a single lookup result.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000822 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000823 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000824 } else {
Douglas Gregor2a3009a2009-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 Gregoreb11cd02009-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 Gregord6f7e9d2009-02-24 20:03:32 +0000835 if (NameKind == LookupOrdinaryName ||
836 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000837 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000838 if (II && AllowBuiltinCreation) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000839 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor3e41d602009-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 Gregor69d993a2009-01-17 01:13:24 +0000847 return LookupResult::CreateLookupResult(Context,
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000848 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000849 S, RedeclarationOnly, Loc));
850 }
Douglas Gregoreb11cd02009-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 Gregor69d993a2009-01-17 01:13:24 +0000859 return LookupResult::CreateLookupResult(Context, IDI->second);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000860 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
861 if (I != ObjCAliasDecls.end())
Douglas Gregor69d993a2009-01-17 01:13:24 +0000862 return LookupResult::CreateLookupResult(Context,
863 I->second->getClassInterface());
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000864 }
865 }
Douglas Gregor69d993a2009-01-17 01:13:24 +0000866 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-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 Gregor4c921ae2009-01-30 01:04:22 +0000901 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000902 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
903
Douglas Gregor69d993a2009-01-17 01:13:24 +0000904 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-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 Gregor4c921ae2009-01-30 01:04:22 +0000908 unsigned IDNS
909 = getIdentifierNamespacesFromLookupNameKind(NameKind,
910 getLangOptions().CPlusPlus);
911 if (NameKind == LookupOrdinaryName)
912 IDNS |= Decl::IDNS_Member;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000913
914 // Perform qualified name lookup into the LookupCtx.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000915 DeclContext::lookup_iterator I, E;
916 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000917 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000918 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000919
Douglas Gregor7176fff2009-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 Gregor4c921ae2009-01-30 01:04:22 +0000922 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000923 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000924
925 // Perform lookup into our base classes.
926 BasePaths Paths;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +0000927 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor7176fff2009-01-15 00:26:24 +0000928
929 // Look for this member in our base classes
930 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000931 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000932 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-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 Dunbarf1853192009-01-15 18:32:35 +0000942 int SubobjectNumber = 0;
Douglas Gregor7176fff2009-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 Gregor69d993a2009-01-17 01:13:24 +0000958 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor7176fff2009-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 Gregor4afa39d2009-01-20 01:17:11 +0000966 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-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 Gregor69d993a2009-01-17 01:13:24 +0000996 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor7176fff2009-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 Gregor69d993a2009-01-17 01:13:24 +00001004 return LookupResult::CreateLookupResult(Context,
Douglas Gregor7176fff2009-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 Gregor69d993a2009-01-17 01:13:24 +00001008 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregoreb11cd02009-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 Gregor3e41d602009-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 Gregoreb11cd02009-01-14 22:20:51 +00001032/// @returns The result of qualified or unqualified name lookup.
1033Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001034Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1035 DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001036 bool RedeclarationOnly, bool AllowBuiltinCreation,
1037 SourceLocation Loc) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001038 if (SS) {
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00001039 if (SS->isInvalid() || RequireCompleteDeclContext(*SS))
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001040 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001041
Douglas Gregore4e5b052009-03-19 00:18:19 +00001042 if (SS->isSet()) {
1043 return LookupQualifiedName(computeDeclContext(*SS),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001044 Name, NameKind, RedeclarationOnly);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001045 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001046 }
1047
Douglas Gregor3e41d602009-02-13 23:20:09 +00001048 return LookupName(S, Name, NameKind, RedeclarationOnly,
1049 AllowBuiltinCreation, Loc);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001050}
1051
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001052
Douglas Gregor7176fff2009-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 Gregor2a3009a2009-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 Gregor4dc6b1c2009-01-16 00:38:09 +00001081
Douglas Gregor2a3009a2009-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 Gregor4dc6b1c2009-01-16 00:38:09 +00001085
Douglas Gregor2a3009a2009-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 Gregor47b9a1c2009-02-04 17:27:36 +00001111 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
1112 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001113
Chris Lattner48458d22009-02-03 21:29:32 +00001114 for (; DI != DEnd; ++DI)
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001115 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001116
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001117 delete[] reinterpret_cast<NamedDecl **>(Result.First);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00001118
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001119 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001120 }
1121
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001122 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregor69d993a2009-01-17 01:13:24 +00001123
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001124 // We can't reach here.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001125 return true;
1126}
Douglas Gregorfa047642009-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 Gregorc1efaec2009-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 Gregorfa047642009-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 Gregor72564e72009-02-26 23:50:07 +00001275 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001276 if (!Proto)
1277 return;
1278
1279 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001280 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Douglas Gregorfa047642009-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 Gregor3fd95ce2009-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 Gregorba498172009-03-13 21:01:28 +00001397 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1398 return true;
1399
Douglas Gregor3fd95ce2009-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