blob: 4b5a04b450fdf02c5fbdda9549a6379c44088476 [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.
Douglas Gregorc55b0b02009-04-09 21:40:53 +000060void AddNamespaceUsingDirectives(ASTContext &Context,
61 DeclContext *NS,
Douglas Gregor7a7be652009-02-03 19:21:40 +000062 UsingDirectivesTy &UDirs,
63 NamespaceSet &Visited) {
64 DeclContext::udir_iterator I, End;
65
Douglas Gregorc55b0b02009-04-09 21:40:53 +000066 for (llvm::tie(I, End) = NS->getUsingDirectives(Context); I !=End; ++I) {
Douglas Gregor7a7be652009-02-03 19:21:40 +000067 UDirs.push_back(*I);
68 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
69 NamespaceDecl *Nominated = (*I)->getNominatedNamespace();
70 if (Visited.insert(Nominated).second)
Douglas Gregorc55b0b02009-04-09 21:40:53 +000071 AddNamespaceUsingDirectives(Context, Nominated, UDirs, /*ref*/ Visited);
Douglas Gregor7a7be652009-02-03 19:21:40 +000072 }
73}
74
75/// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S,
76/// including all found in the namespaces they nominate.
Douglas Gregorc55b0b02009-04-09 21:40:53 +000077static void AddScopeUsingDirectives(ASTContext &Context, Scope *S,
78 UsingDirectivesTy &UDirs) {
Douglas Gregor7a7be652009-02-03 19:21:40 +000079 NamespaceSet VisitedNS;
80
81 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
82
83 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx))
84 VisitedNS.insert(NS);
85
Douglas Gregorc55b0b02009-04-09 21:40:53 +000086 AddNamespaceUsingDirectives(Context, Ctx, UDirs, /*ref*/ VisitedNS);
Douglas Gregor7a7be652009-02-03 19:21:40 +000087
88 } else {
Chris Lattner5261d0c2009-03-28 19:18:32 +000089 Scope::udir_iterator I = S->using_directives_begin(),
90 End = S->using_directives_end();
Douglas Gregor7a7be652009-02-03 19:21:40 +000091
92 for (; I != End; ++I) {
Chris Lattner5261d0c2009-03-28 19:18:32 +000093 UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>();
Douglas Gregor7a7be652009-02-03 19:21:40 +000094 UDirs.push_back(UD);
95 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
96
97 NamespaceDecl *Nominated = UD->getNominatedNamespace();
98 if (!VisitedNS.count(Nominated)) {
99 VisitedNS.insert(Nominated);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000100 AddNamespaceUsingDirectives(Context, Nominated, UDirs,
101 /*ref*/ VisitedNS);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000102 }
103 }
104 }
105}
106
Douglas Gregor78d70132009-01-14 22:20:51 +0000107/// MaybeConstructOverloadSet - Name lookup has determined that the
108/// elements in [I, IEnd) have the name that we are looking for, and
109/// *I is a match for the namespace. This routine returns an
110/// appropriate Decl for name lookup, which may either be *I or an
Douglas Gregor7a7be652009-02-03 19:21:40 +0000111/// OverloadedFunctionDecl that represents the overloaded functions in
Douglas Gregor78d70132009-01-14 22:20:51 +0000112/// [I, IEnd).
113///
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000114/// The existance of this routine is temporary; users of LookupResult
115/// should be able to handle multiple results, to deal with cases of
Douglas Gregor78d70132009-01-14 22:20:51 +0000116/// ambiguity and overloaded functions without needing to create a
117/// Decl node.
118template<typename DeclIterator>
Douglas Gregor09be81b2009-02-04 17:27:36 +0000119static NamedDecl *
Douglas Gregor78d70132009-01-14 22:20:51 +0000120MaybeConstructOverloadSet(ASTContext &Context,
121 DeclIterator I, DeclIterator IEnd) {
122 assert(I != IEnd && "Iterator range cannot be empty");
123 assert(!isa<OverloadedFunctionDecl>(*I) &&
124 "Cannot have an overloaded function");
125
126 if (isa<FunctionDecl>(*I)) {
127 // If we found a function, there might be more functions. If
128 // so, collect them into an overload set.
129 DeclIterator Last = I;
130 OverloadedFunctionDecl *Ovl = 0;
131 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
132 if (!Ovl) {
133 // FIXME: We leak this overload set. Eventually, we want to
134 // stop building the declarations for these overload sets, so
135 // there will be nothing to leak.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000136 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
Douglas Gregor78d70132009-01-14 22:20:51 +0000137 (*I)->getDeclName());
138 Ovl->addOverload(cast<FunctionDecl>(*I));
139 }
140 Ovl->addOverload(cast<FunctionDecl>(*Last));
141 }
142
143 // If we had more than one function, we built an overload
144 // set. Return it.
145 if (Ovl)
146 return Ovl;
147 }
148
149 return *I;
150}
151
Douglas Gregor7a7be652009-02-03 19:21:40 +0000152/// Merges together multiple LookupResults dealing with duplicated Decl's.
153static Sema::LookupResult
154MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
155 typedef Sema::LookupResult LResult;
Douglas Gregor09be81b2009-02-04 17:27:36 +0000156 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000157
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000158 // Remove duplicated Decl pointing at same Decl, by storing them in
159 // associative collection. This might be case for code like:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000160 //
161 // namespace A { int i; }
162 // namespace B { using namespace A; }
163 // namespace C { using namespace A; }
164 //
165 // void foo() {
166 // using namespace B;
167 // using namespace C;
168 // ++i; // finds A::i, from both namespace B and C at global scope
169 // }
170 //
171 // C++ [namespace.qual].p3:
172 // The same declaration found more than once is not an ambiguity
173 // (because it is still a unique declaration).
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000174 DeclsSetTy FoundDecls;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000175
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000176 // Counter of tag names, and functions for resolving ambiguity
177 // and name hiding.
178 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
Douglas Gregor09be81b2009-02-04 17:27:36 +0000179
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000180 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
181
182 // No name lookup results, return early.
183 if (I == End) return LResult::CreateLookupResult(Context, 0);
184
185 // Keep track of the tag declaration we found. We only use this if
186 // we find a single tag declaration.
187 TagDecl *TagFound = 0;
188
189 for (; I != End; ++I) {
190 switch (I->getKind()) {
191 case LResult::NotFound:
192 assert(false &&
193 "Should be always successful name lookup result here.");
194 break;
195
196 case LResult::AmbiguousReference:
197 case LResult::AmbiguousBaseSubobjectTypes:
198 case LResult::AmbiguousBaseSubobjects:
199 assert(false && "Shouldn't get ambiguous lookup here.");
200 break;
201
202 case LResult::Found: {
203 NamedDecl *ND = I->getAsDecl();
204 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
205 TagFound = Context.getCanonicalDecl(TD);
206 TagNames += FoundDecls.insert(TagFound)? 1 : 0;
207 } else if (isa<FunctionDecl>(ND))
208 Functions += FoundDecls.insert(ND)? 1 : 0;
209 else
210 FoundDecls.insert(ND);
211 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000212 }
213
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000214 case LResult::FoundOverloaded:
215 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
216 Functions += FoundDecls.insert(*FI)? 1 : 0;
217 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000218 }
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000219 }
220 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
221 bool Ambiguous = false, NameHidesTags = false;
222
223 if (FoundDecls.size() == 1) {
224 // 1) Exactly one result.
225 } else if (TagNames > 1) {
226 // 2) Multiple tag names (even though they may be hidden by an
227 // object name).
228 Ambiguous = true;
229 } else if (FoundDecls.size() - TagNames == 1) {
230 // 3) Ordinary name hides (optional) tag.
231 NameHidesTags = TagFound;
232 } else if (Functions) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000233 // C++ [basic.lookup].p1:
234 // ... Name lookup may associate more than one declaration with
Douglas Gregor7a7be652009-02-03 19:21:40 +0000235 // a name if it finds the name to be a function name; the declarations
236 // are said to form a set of overloaded functions (13.1).
237 // Overload resolution (13.3) takes place after name lookup has succeeded.
Douglas Gregor09be81b2009-02-04 17:27:36 +0000238 //
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000239 if (!OrdinaryNonFunc) {
240 // 4) Functions hide tag names.
241 NameHidesTags = TagFound;
242 } else {
243 // 5) Functions + ordinary names.
244 Ambiguous = true;
245 }
246 } else {
247 // 6) Multiple non-tag names
248 Ambiguous = true;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000249 }
250
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000251 if (Ambiguous)
252 return LResult::CreateLookupResult(Context,
253 FoundDecls.begin(), FoundDecls.size());
254 if (NameHidesTags) {
255 // There's only one tag, TagFound. Remove it.
256 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
257 FoundDecls.erase(TagFound);
258 }
259
260 // Return successful name lookup result.
261 return LResult::CreateLookupResult(Context,
262 MaybeConstructOverloadSet(Context,
263 FoundDecls.begin(),
264 FoundDecls.end()));
Douglas Gregor7a7be652009-02-03 19:21:40 +0000265}
266
267// Retrieve the set of identifier namespaces that correspond to a
268// specific kind of name lookup.
269inline unsigned
270getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
271 bool CPlusPlus) {
272 unsigned IDNS = 0;
273 switch (NameKind) {
274 case Sema::LookupOrdinaryName:
Douglas Gregor48a87322009-02-04 16:44:47 +0000275 case Sema::LookupOperatorName:
Douglas Gregor1c52c632009-02-24 20:03:32 +0000276 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000277 IDNS = Decl::IDNS_Ordinary;
278 if (CPlusPlus)
279 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
280 break;
281
282 case Sema::LookupTagName:
283 IDNS = Decl::IDNS_Tag;
284 break;
285
286 case Sema::LookupMemberName:
287 IDNS = Decl::IDNS_Member;
288 if (CPlusPlus)
289 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
290 break;
291
292 case Sema::LookupNestedNameSpecifierName:
293 case Sema::LookupNamespaceName:
294 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
295 break;
Douglas Gregore57c8cc2009-04-23 23:18:26 +0000296
Douglas Gregorafd5eb32009-04-24 00:11:27 +0000297 case Sema::LookupObjCProtocolName:
298 IDNS = Decl::IDNS_ObjCProtocol;
299 break;
300
301 case Sema::LookupObjCImplementationName:
302 IDNS = Decl::IDNS_ObjCImplementation;
303 break;
304
305 case Sema::LookupObjCCategoryImplName:
306 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregore57c8cc2009-04-23 23:18:26 +0000307 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000308 }
309 return IDNS;
310}
311
Douglas Gregor7a7be652009-02-03 19:21:40 +0000312Sema::LookupResult
Douglas Gregor09be81b2009-02-04 17:27:36 +0000313Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000314 LookupResult Result;
315 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
316 OverloadedDeclSingleDecl : SingleDecl;
317 Result.First = reinterpret_cast<uintptr_t>(D);
318 Result.Last = 0;
319 Result.Context = &Context;
320 return Result;
321}
322
Douglas Gregor6beddfe2009-01-15 02:19:31 +0000323/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregord07474b2009-01-17 01:13:24 +0000324Sema::LookupResult
325Sema::LookupResult::CreateLookupResult(ASTContext &Context,
326 IdentifierResolver::iterator F,
327 IdentifierResolver::iterator L) {
328 LookupResult Result;
329 Result.Context = &Context;
330
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000331 if (F != L && isa<FunctionDecl>(*F)) {
332 IdentifierResolver::iterator Next = F;
333 ++Next;
334 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000335 Result.StoredKind = OverloadedDeclFromIdResolver;
336 Result.First = F.getAsOpaqueValue();
337 Result.Last = L.getAsOpaqueValue();
338 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000339 }
340 }
341
Douglas Gregord07474b2009-01-17 01:13:24 +0000342 Result.StoredKind = SingleDecl;
343 Result.First = reinterpret_cast<uintptr_t>(*F);
344 Result.Last = 0;
345 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000346}
347
Douglas Gregord07474b2009-01-17 01:13:24 +0000348Sema::LookupResult
349Sema::LookupResult::CreateLookupResult(ASTContext &Context,
350 DeclContext::lookup_iterator F,
351 DeclContext::lookup_iterator L) {
352 LookupResult Result;
353 Result.Context = &Context;
354
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000355 if (F != L && isa<FunctionDecl>(*F)) {
356 DeclContext::lookup_iterator Next = F;
357 ++Next;
358 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000359 Result.StoredKind = OverloadedDeclFromDeclContext;
360 Result.First = reinterpret_cast<uintptr_t>(F);
361 Result.Last = reinterpret_cast<uintptr_t>(L);
362 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000363 }
364 }
365
Douglas Gregord07474b2009-01-17 01:13:24 +0000366 Result.StoredKind = SingleDecl;
367 Result.First = reinterpret_cast<uintptr_t>(*F);
368 Result.Last = 0;
369 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000370}
371
Douglas Gregor78d70132009-01-14 22:20:51 +0000372/// @brief Determine the result of name lookup.
373Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
374 switch (StoredKind) {
375 case SingleDecl:
376 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
377
Douglas Gregor7a7be652009-02-03 19:21:40 +0000378 case OverloadedDeclSingleDecl:
Douglas Gregor78d70132009-01-14 22:20:51 +0000379 case OverloadedDeclFromIdResolver:
380 case OverloadedDeclFromDeclContext:
381 return FoundOverloaded;
382
Douglas Gregor7a7be652009-02-03 19:21:40 +0000383 case AmbiguousLookupStoresBasePaths:
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000384 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000385
386 case AmbiguousLookupStoresDecls:
387 return AmbiguousReference;
Douglas Gregor78d70132009-01-14 22:20:51 +0000388 }
389
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000390 // We can't ever get here.
391 return NotFound;
Douglas Gregor78d70132009-01-14 22:20:51 +0000392}
393
394/// @brief Converts the result of name lookup into a single (possible
395/// NULL) pointer to a declaration.
396///
397/// The resulting declaration will either be the declaration we found
398/// (if only a single declaration was found), an
399/// OverloadedFunctionDecl (if an overloaded function was found), or
400/// NULL (if no declaration was found). This conversion must not be
401/// used anywhere where name lookup could result in an ambiguity.
402///
403/// The OverloadedFunctionDecl conversion is meant as a stop-gap
404/// solution, since it causes the OverloadedFunctionDecl to be
405/// leaked. FIXME: Eventually, there will be a better way to iterate
406/// over the set of overloaded functions returned by name lookup.
Douglas Gregor09be81b2009-02-04 17:27:36 +0000407NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregor78d70132009-01-14 22:20:51 +0000408 switch (StoredKind) {
409 case SingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000410 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregor78d70132009-01-14 22:20:51 +0000411
412 case OverloadedDeclFromIdResolver:
413 return MaybeConstructOverloadSet(*Context,
414 IdentifierResolver::iterator::getFromOpaqueValue(First),
415 IdentifierResolver::iterator::getFromOpaqueValue(Last));
416
417 case OverloadedDeclFromDeclContext:
418 return MaybeConstructOverloadSet(*Context,
419 reinterpret_cast<DeclContext::lookup_iterator>(First),
420 reinterpret_cast<DeclContext::lookup_iterator>(Last));
421
Douglas Gregor7a7be652009-02-03 19:21:40 +0000422 case OverloadedDeclSingleDecl:
423 return reinterpret_cast<OverloadedFunctionDecl*>(First);
424
425 case AmbiguousLookupStoresDecls:
426 case AmbiguousLookupStoresBasePaths:
Douglas Gregor78d70132009-01-14 22:20:51 +0000427 assert(false &&
428 "Name lookup returned an ambiguity that could not be handled");
429 break;
430 }
431
432 return 0;
433}
434
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000435/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor7a7be652009-02-03 19:21:40 +0000436/// name lookup, or null.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000437BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000438 if (StoredKind == AmbiguousLookupStoresBasePaths)
439 return reinterpret_cast<BasePaths *>(First);
440 return 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000441}
442
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000443Sema::LookupResult::iterator::reference
444Sema::LookupResult::iterator::operator*() const {
445 switch (Result->StoredKind) {
446 case SingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000447 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000448
Douglas Gregor7a7be652009-02-03 19:21:40 +0000449 case OverloadedDeclSingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000450 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000451
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000452 case OverloadedDeclFromIdResolver:
453 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
454
Douglas Gregor7a7be652009-02-03 19:21:40 +0000455 case AmbiguousLookupStoresBasePaths:
Douglas Gregord7cb0372009-04-01 21:51:26 +0000456 if (Result->Last)
457 return *reinterpret_cast<NamedDecl**>(Current);
458
459 // Fall through to handle the DeclContext::lookup_iterator we're
460 // storing.
461
462 case OverloadedDeclFromDeclContext:
463 case AmbiguousLookupStoresDecls:
464 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000465 }
466
467 return 0;
468}
469
470Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
471 switch (Result->StoredKind) {
472 case SingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000473 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000474 break;
475
Douglas Gregor7a7be652009-02-03 19:21:40 +0000476 case OverloadedDeclSingleDecl: {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000477 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000478 ++I;
479 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregor48a87322009-02-04 16:44:47 +0000480 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000481 }
482
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000483 case OverloadedDeclFromIdResolver: {
484 IdentifierResolver::iterator I
485 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
486 ++I;
487 Current = I.getAsOpaqueValue();
488 break;
489 }
490
Douglas Gregord7cb0372009-04-01 21:51:26 +0000491 case AmbiguousLookupStoresBasePaths:
492 if (Result->Last) {
493 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
494 ++I;
495 Current = reinterpret_cast<uintptr_t>(I);
496 break;
497 }
498 // Fall through to handle the DeclContext::lookup_iterator we're
499 // storing.
500
501 case OverloadedDeclFromDeclContext:
502 case AmbiguousLookupStoresDecls: {
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000503 DeclContext::lookup_iterator I
504 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
505 ++I;
506 Current = reinterpret_cast<uintptr_t>(I);
507 break;
508 }
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000509 }
510
511 return *this;
512}
513
514Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregord7cb0372009-04-01 21:51:26 +0000515 switch (StoredKind) {
516 case SingleDecl:
517 case OverloadedDeclFromIdResolver:
518 case OverloadedDeclFromDeclContext:
519 case AmbiguousLookupStoresDecls:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000520 return iterator(this, First);
Douglas Gregord7cb0372009-04-01 21:51:26 +0000521
522 case OverloadedDeclSingleDecl: {
523 OverloadedFunctionDecl * Ovl =
524 reinterpret_cast<OverloadedFunctionDecl*>(First);
525 return iterator(this,
526 reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
527 }
528
529 case AmbiguousLookupStoresBasePaths:
530 if (Last)
531 return iterator(this,
532 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin()));
533 else
534 return iterator(this,
535 reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first));
536 }
537
538 // Required to suppress GCC warning.
539 return iterator();
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000540}
541
542Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregord7cb0372009-04-01 21:51:26 +0000543 switch (StoredKind) {
544 case SingleDecl:
545 case OverloadedDeclFromIdResolver:
546 case OverloadedDeclFromDeclContext:
547 case AmbiguousLookupStoresDecls:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000548 return iterator(this, Last);
Douglas Gregord7cb0372009-04-01 21:51:26 +0000549
550 case OverloadedDeclSingleDecl: {
551 OverloadedFunctionDecl * Ovl =
552 reinterpret_cast<OverloadedFunctionDecl*>(First);
553 return iterator(this,
554 reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
555 }
556
557 case AmbiguousLookupStoresBasePaths:
558 if (Last)
559 return iterator(this,
560 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end()));
561 else
562 return iterator(this, reinterpret_cast<uintptr_t>(
563 getBasePaths()->front().Decls.second));
564 }
565
566 // Required to suppress GCC warning.
567 return iterator();
568}
569
570void Sema::LookupResult::Destroy() {
571 if (BasePaths *Paths = getBasePaths())
572 delete Paths;
573 else if (getKind() == AmbiguousReference)
574 delete[] reinterpret_cast<NamedDecl **>(First);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000575}
576
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000577static void
578CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
579 DeclarationName Name, Sema::LookupNameKind NameKind,
580 unsigned IDNS, LookupResultsTy &Results,
581 UsingDirectivesTy *UDirs = 0) {
582
583 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
584
585 // Perform qualified name lookup into the LookupCtx.
586 DeclContext::lookup_iterator I, E;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000587 for (llvm::tie(I, E) = NS->lookup(Context, Name); I != E; ++I)
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000588 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
589 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
590 break;
591 }
592
593 if (UDirs) {
594 // For each UsingDirectiveDecl, which common ancestor is equal
595 // to NS, we preform qualified name lookup into namespace nominated by it.
596 UsingDirectivesTy::const_iterator UI, UEnd;
597 llvm::tie(UI, UEnd) =
598 std::equal_range(UDirs->begin(), UDirs->end(), NS,
599 UsingDirAncestorCompare());
600
601 for (; UI != UEnd; ++UI)
602 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
603 Name, NameKind, IDNS, Results);
604 }
605}
606
607static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000608 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000609 return Ctx->isFileContext();
610 return false;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000611}
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000612
Douglas Gregor7a7be652009-02-03 19:21:40 +0000613std::pair<bool, Sema::LookupResult>
614Sema::CppLookupName(Scope *S, DeclarationName Name,
615 LookupNameKind NameKind, bool RedeclarationOnly) {
616 assert(getLangOptions().CPlusPlus &&
617 "Can perform only C++ lookup");
Douglas Gregor48a87322009-02-04 16:44:47 +0000618 unsigned IDNS
Douglas Gregor09be81b2009-02-04 17:27:36 +0000619 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000620 Scope *Initial = S;
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000621 DeclContext *OutOfLineCtx = 0;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000622 IdentifierResolver::iterator
623 I = IdResolver.begin(Name),
624 IEnd = IdResolver.end();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000625
Douglas Gregor7a7be652009-02-03 19:21:40 +0000626 // First we lookup local scope.
Douglas Gregor279272e2009-02-04 19:02:06 +0000627 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor7a7be652009-02-03 19:21:40 +0000628 // ...During unqualified name lookup (3.4.1), the names appear as if
629 // they were declared in the nearest enclosing namespace which contains
630 // both the using-directive and the nominated namespace.
631 // [Note: in this context, “contains” means “contains directly or
632 // indirectly”.
633 //
634 // For example:
635 // namespace A { int i; }
636 // void foo() {
637 // int i;
638 // {
639 // using namespace A;
640 // ++i; // finds local 'i', A::i appears at global scope
641 // }
642 // }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000643 //
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000644 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000645 // Check whether the IdResolver has anything in this scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000646 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000647 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
648 // We found something. Look for anything else in our scope
649 // with this same name and in an acceptable identifier
650 // namespace, so that we can construct an overload set if we
651 // need to.
652 IdentifierResolver::iterator LastI = I;
653 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000654 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor7a7be652009-02-03 19:21:40 +0000655 break;
656 }
657 LookupResult Result =
658 LookupResult::CreateLookupResult(Context, I, LastI);
659 return std::make_pair(true, Result);
660 }
661 }
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000662 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
663 LookupResult R;
664 // Perform member lookup into struct.
665 // FIXME: In some cases, we know that every name that could be
666 // found by this qualified name lookup will also be on the
667 // identifier chain. For example, inside a class without any
668 // base classes, we never need to perform qualified lookup
669 // because all of the members are on top of the identifier
670 // chain.
Douglas Gregord3c78592009-03-27 04:21:56 +0000671 if (isa<RecordDecl>(Ctx)) {
672 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
673 if (R || RedeclarationOnly)
674 return std::make_pair(true, R);
675 }
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000676 if (Ctx->getParent() != Ctx->getLexicalParent()) {
677 // It is out of line defined C++ method or struct, we continue
678 // doing name lookup in parent context. Once we will find namespace
679 // or translation-unit we save it for possible checking
680 // using-directives later.
681 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
682 OutOfLineCtx = OutOfLineCtx->getParent()) {
Douglas Gregord3c78592009-03-27 04:21:56 +0000683 R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
684 if (R || RedeclarationOnly)
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000685 return std::make_pair(true, R);
686 }
687 }
688 }
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000689 }
Douglas Gregor7a7be652009-02-03 19:21:40 +0000690
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000691 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor7a7be652009-02-03 19:21:40 +0000692 // nominated namespaces by those using-directives.
693 // UsingDirectives are pushed to heap, in common ancestor pointer
694 // value order.
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000695 // FIXME: Cache this sorted list in Scope structure, and DeclContext,
696 // so we don't build it for each lookup!
Douglas Gregor7a7be652009-02-03 19:21:40 +0000697 UsingDirectivesTy UDirs;
698 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor09be81b2009-02-04 17:27:36 +0000699 if (SC->getFlags() & Scope::DeclScope)
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000700 AddScopeUsingDirectives(Context, SC, UDirs);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000701
702 // Sort heapified UsingDirectiveDecls.
703 std::sort_heap(UDirs.begin(), UDirs.end());
704
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000705 // Lookup namespace scope, and global scope.
Douglas Gregor7a7be652009-02-03 19:21:40 +0000706 // Unqualified name lookup in C++ requires looking into scopes
707 // that aren't strictly lexical, and therefore we walk through the
708 // context as well as walking through the scopes.
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000709
710 LookupResultsTy LookupResults;
Sebastian Redl95216a62009-02-07 00:15:38 +0000711 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000712 "We should have been looking only at file context here already.");
713 bool LookedInCtx = false;
714 LookupResult Result;
715 while (OutOfLineCtx &&
716 OutOfLineCtx != S->getEntity() &&
717 OutOfLineCtx->isNamespace()) {
718 LookedInCtx = true;
719
720 // Look into context considering using-directives.
721 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
722 LookupResults, &UDirs);
723
724 if ((Result = MergeLookupResults(Context, LookupResults)) ||
725 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
726 return std::make_pair(true, Result);
727
728 OutOfLineCtx = OutOfLineCtx->getParent();
729 }
730
Douglas Gregor7a7be652009-02-03 19:21:40 +0000731 for (; S; S = S->getParent()) {
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000732 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
733 assert(Ctx && Ctx->isFileContext() &&
734 "We should have been looking only at file context here already.");
Douglas Gregor7a7be652009-02-03 19:21:40 +0000735
736 // Check whether the IdResolver has anything in this scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000737 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000738 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
739 // We found something. Look for anything else in our scope
740 // with this same name and in an acceptable identifier
741 // namespace, so that we can construct an overload set if we
742 // need to.
743 IdentifierResolver::iterator LastI = I;
744 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000745 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor7a7be652009-02-03 19:21:40 +0000746 break;
747 }
748
749 // We store name lookup result, and continue trying to look into
750 // associated context, and maybe namespaces nominated by
751 // using-directives.
752 LookupResults.push_back(
753 LookupResult::CreateLookupResult(Context, I, LastI));
754 break;
755 }
756 }
757
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000758 LookedInCtx = true;
759 // Look into context considering using-directives.
760 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
761 LookupResults, &UDirs);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000762
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000763 if ((Result = MergeLookupResults(Context, LookupResults)) ||
764 (RedeclarationOnly && !Ctx->isTransparentContext()))
765 return std::make_pair(true, Result);
766 }
Douglas Gregor7a7be652009-02-03 19:21:40 +0000767
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000768 if (!(LookedInCtx || LookupResults.empty())) {
769 // We didn't Performed lookup in Scope entity, so we return
770 // result form IdentifierResolver.
771 assert((LookupResults.size() == 1) && "Wrong size!");
772 return std::make_pair(true, LookupResults.front());
Douglas Gregor7a7be652009-02-03 19:21:40 +0000773 }
774 return std::make_pair(false, LookupResult());
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000775}
776
Douglas Gregor78d70132009-01-14 22:20:51 +0000777/// @brief Perform unqualified name lookup starting from a given
778/// scope.
779///
780/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
781/// used to find names within the current scope. For example, 'x' in
782/// @code
783/// int x;
784/// int f() {
785/// return x; // unqualified name look finds 'x' in the global scope
786/// }
787/// @endcode
788///
789/// Different lookup criteria can find different names. For example, a
790/// particular scope can have both a struct and a function of the same
791/// name, and each can be found by certain lookup criteria. For more
792/// information about lookup criteria, see the documentation for the
793/// class LookupCriteria.
794///
795/// @param S The scope from which unqualified name lookup will
796/// begin. If the lookup criteria permits, name lookup may also search
797/// in the parent scopes.
798///
799/// @param Name The name of the entity that we are searching for.
800///
Douglas Gregor411889e2009-02-13 23:20:09 +0000801/// @param Loc If provided, the source location where we're performing
802/// name lookup. At present, this is only used to produce diagnostics when
803/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor78d70132009-01-14 22:20:51 +0000804///
805/// @returns The result of name lookup, which includes zero or more
806/// declarations and possibly additional information used to diagnose
807/// ambiguities.
808Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000809Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor411889e2009-02-13 23:20:09 +0000810 bool RedeclarationOnly, bool AllowBuiltinCreation,
811 SourceLocation Loc) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000812 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000813
814 if (!getLangOptions().CPlusPlus) {
815 // Unqualified name lookup in C/Objective-C is purely lexical, so
816 // search in the declarations attached to the name.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000817 unsigned IDNS = 0;
818 switch (NameKind) {
819 case Sema::LookupOrdinaryName:
820 IDNS = Decl::IDNS_Ordinary;
821 break;
Douglas Gregor78d70132009-01-14 22:20:51 +0000822
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000823 case Sema::LookupTagName:
824 IDNS = Decl::IDNS_Tag;
825 break;
826
827 case Sema::LookupMemberName:
828 IDNS = Decl::IDNS_Member;
829 break;
830
Douglas Gregor48a87322009-02-04 16:44:47 +0000831 case Sema::LookupOperatorName:
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000832 case Sema::LookupNestedNameSpecifierName:
833 case Sema::LookupNamespaceName:
834 assert(false && "C does not perform these kinds of name lookup");
835 break;
Douglas Gregor1c52c632009-02-24 20:03:32 +0000836
837 case Sema::LookupRedeclarationWithLinkage:
838 // Find the nearest non-transparent declaration scope.
839 while (!(S->getFlags() & Scope::DeclScope) ||
840 (S->getEntity() &&
841 static_cast<DeclContext *>(S->getEntity())
842 ->isTransparentContext()))
843 S = S->getParent();
844 IDNS = Decl::IDNS_Ordinary;
845 break;
Douglas Gregore57c8cc2009-04-23 23:18:26 +0000846
Douglas Gregorafd5eb32009-04-24 00:11:27 +0000847 case Sema::LookupObjCProtocolName:
848 IDNS = Decl::IDNS_ObjCProtocol;
849 break;
850
851 case Sema::LookupObjCImplementationName:
852 IDNS = Decl::IDNS_ObjCImplementation;
853 break;
854
855 case Sema::LookupObjCCategoryImplName:
856 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregore57c8cc2009-04-23 23:18:26 +0000857 break;
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000858 }
859
Douglas Gregor78d70132009-01-14 22:20:51 +0000860 // Scan up the scope chain looking for a decl that matches this
861 // identifier that is in the appropriate namespace. This search
862 // should not take long, as shadowing of names is uncommon, and
863 // deep shadowing is extremely uncommon.
Douglas Gregor1c52c632009-02-24 20:03:32 +0000864 bool LeftStartingScope = false;
865
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000866 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
867 IEnd = IdResolver.end();
868 I != IEnd; ++I)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000869 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregor1c52c632009-02-24 20:03:32 +0000870 if (NameKind == LookupRedeclarationWithLinkage) {
871 // Determine whether this (or a previous) declaration is
872 // out-of-scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000873 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor1c52c632009-02-24 20:03:32 +0000874 LeftStartingScope = true;
875
876 // If we found something outside of our starting scope that
877 // does not have linkage, skip it.
878 if (LeftStartingScope && !((*I)->hasLinkage()))
879 continue;
880 }
881
Douglas Gregorfcb19192009-02-11 23:02:49 +0000882 if ((*I)->getAttr<OverloadableAttr>()) {
883 // If this declaration has the "overloadable" attribute, we
884 // might have a set of overloaded functions.
885
886 // Figure out what scope the identifier is in.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000887 while (!(S->getFlags() & Scope::DeclScope) ||
888 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorfcb19192009-02-11 23:02:49 +0000889 S = S->getParent();
890
891 // Find the last declaration in this scope (with the same
892 // name, naturally).
893 IdentifierResolver::iterator LastI = I;
894 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000895 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorfcb19192009-02-11 23:02:49 +0000896 break;
897 }
898
899 return LookupResult::CreateLookupResult(Context, I, LastI);
900 }
901
902 // We have a single lookup result.
Douglas Gregord07474b2009-01-17 01:13:24 +0000903 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregorfcb19192009-02-11 23:02:49 +0000904 }
Douglas Gregor78d70132009-01-14 22:20:51 +0000905 } else {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000906 // Perform C++ unqualified name lookup.
907 std::pair<bool, LookupResult> MaybeResult =
908 CppLookupName(S, Name, NameKind, RedeclarationOnly);
909 if (MaybeResult.first)
910 return MaybeResult.second;
Douglas Gregor78d70132009-01-14 22:20:51 +0000911 }
912
913 // If we didn't find a use of this identifier, and if the identifier
914 // corresponds to a compiler builtin, create the decl object for the builtin
915 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1c52c632009-02-24 20:03:32 +0000916 if (NameKind == LookupOrdinaryName ||
917 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000918 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor411889e2009-02-13 23:20:09 +0000919 if (II && AllowBuiltinCreation) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000920 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor411889e2009-02-13 23:20:09 +0000921 if (unsigned BuiltinID = II->getBuiltinID()) {
922 // In C++, we don't have any predefined library functions like
923 // 'malloc'. Instead, we'll just error.
924 if (getLangOptions().CPlusPlus &&
925 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
926 return LookupResult::CreateLookupResult(Context, 0);
927
Douglas Gregord07474b2009-01-17 01:13:24 +0000928 return LookupResult::CreateLookupResult(Context,
Douglas Gregor78d70132009-01-14 22:20:51 +0000929 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
Douglas Gregor411889e2009-02-13 23:20:09 +0000930 S, RedeclarationOnly, Loc));
931 }
Douglas Gregor78d70132009-01-14 22:20:51 +0000932 }
933 if (getLangOptions().ObjC1 && II) {
934 // @interface and @compatibility_alias introduce typedef-like names.
935 // Unlike typedef's, they can only be introduced at file-scope (and are
936 // therefore not scoped decls). They can, however, be shadowed by
937 // other names in IDNS_Ordinary.
938 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
939 if (IDI != ObjCInterfaceDecls.end())
Douglas Gregord07474b2009-01-17 01:13:24 +0000940 return LookupResult::CreateLookupResult(Context, IDI->second);
Douglas Gregor78d70132009-01-14 22:20:51 +0000941 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
942 if (I != ObjCAliasDecls.end())
Douglas Gregord07474b2009-01-17 01:13:24 +0000943 return LookupResult::CreateLookupResult(Context,
944 I->second->getClassInterface());
Douglas Gregor78d70132009-01-14 22:20:51 +0000945 }
946 }
Douglas Gregord07474b2009-01-17 01:13:24 +0000947 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000948}
949
950/// @brief Perform qualified name lookup into a given context.
951///
952/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
953/// names when the context of those names is explicit specified, e.g.,
954/// "std::vector" or "x->member".
955///
956/// Different lookup criteria can find different names. For example, a
957/// particular scope can have both a struct and a function of the same
958/// name, and each can be found by certain lookup criteria. For more
959/// information about lookup criteria, see the documentation for the
960/// class LookupCriteria.
961///
962/// @param LookupCtx The context in which qualified name lookup will
963/// search. If the lookup criteria permits, name lookup may also search
964/// in the parent contexts or (for C++ classes) base classes.
965///
966/// @param Name The name of the entity that we are searching for.
967///
968/// @param Criteria The criteria that this routine will use to
969/// determine which names are visible and which names will be
970/// found. Note that name lookup will find a name that is visible by
971/// the given criteria, but the entity itself may not be semantically
972/// correct or even the kind of entity expected based on the
973/// lookup. For example, searching for a nested-name-specifier name
974/// might result in an EnumDecl, which is visible but is not permitted
975/// as a nested-name-specifier in C++03.
976///
977/// @returns The result of name lookup, which includes zero or more
978/// declarations and possibly additional information used to diagnose
979/// ambiguities.
980Sema::LookupResult
981Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000982 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000983 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
984
Douglas Gregord07474b2009-01-17 01:13:24 +0000985 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000986
987 // If we're performing qualified name lookup (e.g., lookup into a
988 // struct), find fields as part of ordinary name lookup.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000989 unsigned IDNS
990 = getIdentifierNamespacesFromLookupNameKind(NameKind,
991 getLangOptions().CPlusPlus);
992 if (NameKind == LookupOrdinaryName)
993 IDNS |= Decl::IDNS_Member;
Douglas Gregor78d70132009-01-14 22:20:51 +0000994
995 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor78d70132009-01-14 22:20:51 +0000996 DeclContext::lookup_iterator I, E;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000997 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000998 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregord07474b2009-01-17 01:13:24 +0000999 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregor78d70132009-01-14 22:20:51 +00001000
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001001 // If this isn't a C++ class or we aren't allowed to look into base
1002 // classes, we're done.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001003 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregord07474b2009-01-17 01:13:24 +00001004 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001005
1006 // Perform lookup into our base classes.
1007 BasePaths Paths;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001008 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001009
1010 // Look for this member in our base classes
1011 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001012 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregord07474b2009-01-17 01:13:24 +00001013 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001014
1015 // C++ [class.member.lookup]p2:
1016 // [...] If the resulting set of declarations are not all from
1017 // sub-objects of the same type, or the set has a nonstatic member
1018 // and includes members from distinct sub-objects, there is an
1019 // ambiguity and the program is ill-formed. Otherwise that set is
1020 // the result of the lookup.
1021 // FIXME: support using declarations!
1022 QualType SubobjectType;
Daniel Dunbarddebeca2009-01-15 18:32:35 +00001023 int SubobjectNumber = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001024 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1025 Path != PathEnd; ++Path) {
1026 const BasePathElement &PathElement = Path->back();
1027
1028 // Determine whether we're looking at a distinct sub-object or not.
1029 if (SubobjectType.isNull()) {
1030 // This is the first subobject we've looked at. Record it's type.
1031 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1032 SubobjectNumber = PathElement.SubobjectNumber;
1033 } else if (SubobjectType
1034 != Context.getCanonicalType(PathElement.Base->getType())) {
1035 // We found members of the given name in two subobjects of
1036 // different types. This lookup is ambiguous.
1037 BasePaths *PathsOnHeap = new BasePaths;
1038 PathsOnHeap->swap(Paths);
Douglas Gregord07474b2009-01-17 01:13:24 +00001039 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001040 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1041 // We have a different subobject of the same type.
1042
1043 // C++ [class.member.lookup]p5:
1044 // A static member, a nested type or an enumerator defined in
1045 // a base class T can unambiguously be found even if an object
1046 // has more than one base class subobject of type T.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001047 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001048 if (isa<VarDecl>(FirstDecl) ||
1049 isa<TypeDecl>(FirstDecl) ||
1050 isa<EnumConstantDecl>(FirstDecl))
1051 continue;
1052
1053 if (isa<CXXMethodDecl>(FirstDecl)) {
1054 // Determine whether all of the methods are static.
1055 bool AllMethodsAreStatic = true;
1056 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1057 Func != Path->Decls.second; ++Func) {
1058 if (!isa<CXXMethodDecl>(*Func)) {
1059 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1060 break;
1061 }
1062
1063 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1064 AllMethodsAreStatic = false;
1065 break;
1066 }
1067 }
1068
1069 if (AllMethodsAreStatic)
1070 continue;
1071 }
1072
1073 // We have found a nonstatic member name in multiple, distinct
1074 // subobjects. Name lookup is ambiguous.
1075 BasePaths *PathsOnHeap = new BasePaths;
1076 PathsOnHeap->swap(Paths);
Douglas Gregord07474b2009-01-17 01:13:24 +00001077 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001078 }
1079 }
1080
1081 // Lookup in a base class succeeded; return these results.
1082
1083 // If we found a function declaration, return an overload set.
1084 if (isa<FunctionDecl>(*Paths.front().Decls.first))
Douglas Gregord07474b2009-01-17 01:13:24 +00001085 return LookupResult::CreateLookupResult(Context,
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001086 Paths.front().Decls.first, Paths.front().Decls.second);
1087
1088 // We found a non-function declaration; return a single declaration.
Douglas Gregord07474b2009-01-17 01:13:24 +00001089 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregor78d70132009-01-14 22:20:51 +00001090}
1091
1092/// @brief Performs name lookup for a name that was parsed in the
1093/// source code, and may contain a C++ scope specifier.
1094///
1095/// This routine is a convenience routine meant to be called from
1096/// contexts that receive a name and an optional C++ scope specifier
1097/// (e.g., "N::M::x"). It will then perform either qualified or
1098/// unqualified name lookup (with LookupQualifiedName or LookupName,
1099/// respectively) on the given name and return those results.
1100///
1101/// @param S The scope from which unqualified name lookup will
1102/// begin.
1103///
1104/// @param SS An optional C++ scope-specified, e.g., "::N::M".
1105///
1106/// @param Name The name of the entity that name lookup will
1107/// search for.
1108///
Douglas Gregor411889e2009-02-13 23:20:09 +00001109/// @param Loc If provided, the source location where we're performing
1110/// name lookup. At present, this is only used to produce diagnostics when
1111/// C library functions (like "malloc") are implicitly declared.
1112///
Douglas Gregor78d70132009-01-14 22:20:51 +00001113/// @returns The result of qualified or unqualified name lookup.
1114Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001115Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1116 DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor411889e2009-02-13 23:20:09 +00001117 bool RedeclarationOnly, bool AllowBuiltinCreation,
1118 SourceLocation Loc) {
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001119 if (SS) {
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00001120 if (SS->isInvalid() || RequireCompleteDeclContext(*SS))
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001121 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +00001122
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001123 if (SS->isSet()) {
1124 return LookupQualifiedName(computeDeclContext(*SS),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001125 Name, NameKind, RedeclarationOnly);
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001126 }
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001127 }
1128
Douglas Gregor411889e2009-02-13 23:20:09 +00001129 return LookupName(S, Name, NameKind, RedeclarationOnly,
1130 AllowBuiltinCreation, Loc);
Douglas Gregor78d70132009-01-14 22:20:51 +00001131}
1132
Douglas Gregor7a7be652009-02-03 19:21:40 +00001133
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001134/// @brief Produce a diagnostic describing the ambiguity that resulted
1135/// from name lookup.
1136///
1137/// @param Result The ambiguous name lookup result.
1138///
1139/// @param Name The name of the entity that name lookup was
1140/// searching for.
1141///
1142/// @param NameLoc The location of the name within the source code.
1143///
1144/// @param LookupRange A source range that provides more
1145/// source-location information concerning the lookup itself. For
1146/// example, this range might highlight a nested-name-specifier that
1147/// precedes the name.
1148///
1149/// @returns true
1150bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1151 SourceLocation NameLoc,
1152 SourceRange LookupRange) {
1153 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1154
Douglas Gregord7cb0372009-04-01 21:51:26 +00001155 if (BasePaths *Paths = Result.getBasePaths()) {
Douglas Gregor7a7be652009-02-03 19:21:40 +00001156 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1157 QualType SubobjectType = Paths->front().back().Base->getType();
1158 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1159 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1160 << LookupRange;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001161
Douglas Gregor7a7be652009-02-03 19:21:40 +00001162 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
Douglas Gregord7cb0372009-04-01 21:51:26 +00001163 while (isa<CXXMethodDecl>(*Found) &&
1164 cast<CXXMethodDecl>(*Found)->isStatic())
Douglas Gregor7a7be652009-02-03 19:21:40 +00001165 ++Found;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001166
Douglas Gregor7a7be652009-02-03 19:21:40 +00001167 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1168
Douglas Gregord7cb0372009-04-01 21:51:26 +00001169 Result.Destroy();
Douglas Gregor7a7be652009-02-03 19:21:40 +00001170 return true;
1171 }
1172
1173 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1174 "Unhandled form of name lookup ambiguity");
1175
1176 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1177 << Name << LookupRange;
1178
1179 std::set<Decl *> DeclsPrinted;
1180 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1181 Path != PathEnd; ++Path) {
1182 Decl *D = *Path->Decls.first;
1183 if (DeclsPrinted.insert(D).second)
1184 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1185 }
1186
Douglas Gregord7cb0372009-04-01 21:51:26 +00001187 Result.Destroy();
Douglas Gregor7a7be652009-02-03 19:21:40 +00001188 return true;
1189 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
Douglas Gregor7a7be652009-02-03 19:21:40 +00001190 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1191
Douglas Gregor09be81b2009-02-04 17:27:36 +00001192 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
Douglas Gregord7cb0372009-04-01 21:51:26 +00001193 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor7a7be652009-02-03 19:21:40 +00001194
Chris Lattnerb02f5f22009-02-03 21:29:32 +00001195 for (; DI != DEnd; ++DI)
Douglas Gregor09be81b2009-02-04 17:27:36 +00001196 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor7a7be652009-02-03 19:21:40 +00001197
Douglas Gregord7cb0372009-04-01 21:51:26 +00001198 Result.Destroy();
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001199 return true;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001200 }
1201
Douglas Gregor7a7be652009-02-03 19:21:40 +00001202 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregord07474b2009-01-17 01:13:24 +00001203
Douglas Gregor7a7be652009-02-03 19:21:40 +00001204 // We can't reach here.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001205 return true;
1206}
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001207
1208// \brief Add the associated classes and namespaces for
1209// argument-dependent lookup with an argument of class type
1210// (C++ [basic.lookup.koenig]p2).
1211static void
1212addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1213 ASTContext &Context,
1214 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1215 Sema::AssociatedClassSet &AssociatedClasses) {
1216 // C++ [basic.lookup.koenig]p2:
1217 // [...]
1218 // -- If T is a class type (including unions), its associated
1219 // classes are: the class itself; the class of which it is a
1220 // member, if any; and its direct and indirect base
1221 // classes. Its associated namespaces are the namespaces in
1222 // which its associated classes are defined.
1223
1224 // Add the class of which it is a member, if any.
1225 DeclContext *Ctx = Class->getDeclContext();
1226 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1227 AssociatedClasses.insert(EnclosingClass);
1228
1229 // Add the associated namespace for this class.
1230 while (Ctx->isRecord())
1231 Ctx = Ctx->getParent();
1232 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1233 AssociatedNamespaces.insert(EnclosingNamespace);
1234
1235 // Add the class itself. If we've already seen this class, we don't
1236 // need to visit base classes.
1237 if (!AssociatedClasses.insert(Class))
1238 return;
1239
1240 // FIXME: Handle class template specializations
1241
1242 // Add direct and indirect base classes along with their associated
1243 // namespaces.
1244 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1245 Bases.push_back(Class);
1246 while (!Bases.empty()) {
1247 // Pop this class off the stack.
1248 Class = Bases.back();
1249 Bases.pop_back();
1250
1251 // Visit the base classes.
1252 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1253 BaseEnd = Class->bases_end();
1254 Base != BaseEnd; ++Base) {
1255 const RecordType *BaseType = Base->getType()->getAsRecordType();
1256 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1257 if (AssociatedClasses.insert(BaseDecl)) {
1258 // Find the associated namespace for this base class.
1259 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1260 while (BaseCtx->isRecord())
1261 BaseCtx = BaseCtx->getParent();
1262 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1263 AssociatedNamespaces.insert(EnclosingNamespace);
1264
1265 // Make sure we visit the bases of this base class.
1266 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1267 Bases.push_back(BaseDecl);
1268 }
1269 }
1270 }
1271}
1272
1273// \brief Add the associated classes and namespaces for
1274// argument-dependent lookup with an argument of type T
1275// (C++ [basic.lookup.koenig]p2).
1276static void
1277addAssociatedClassesAndNamespaces(QualType T,
1278 ASTContext &Context,
1279 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1280 Sema::AssociatedClassSet &AssociatedClasses) {
1281 // C++ [basic.lookup.koenig]p2:
1282 //
1283 // For each argument type T in the function call, there is a set
1284 // of zero or more associated namespaces and a set of zero or more
1285 // associated classes to be considered. The sets of namespaces and
1286 // classes is determined entirely by the types of the function
1287 // arguments (and the namespace of any template template
1288 // argument). Typedef names and using-declarations used to specify
1289 // the types do not contribute to this set. The sets of namespaces
1290 // and classes are determined in the following way:
1291 T = Context.getCanonicalType(T).getUnqualifiedType();
1292
1293 // -- If T is a pointer to U or an array of U, its associated
1294 // namespaces and classes are those associated with U.
1295 //
1296 // We handle this by unwrapping pointer and array types immediately,
1297 // to avoid unnecessary recursion.
1298 while (true) {
1299 if (const PointerType *Ptr = T->getAsPointerType())
1300 T = Ptr->getPointeeType();
1301 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1302 T = Ptr->getElementType();
1303 else
1304 break;
1305 }
1306
1307 // -- If T is a fundamental type, its associated sets of
1308 // namespaces and classes are both empty.
1309 if (T->getAsBuiltinType())
1310 return;
1311
1312 // -- If T is a class type (including unions), its associated
1313 // classes are: the class itself; the class of which it is a
1314 // member, if any; and its direct and indirect base
1315 // classes. Its associated namespaces are the namespaces in
1316 // which its associated classes are defined.
Douglas Gregor2e047592009-02-28 01:32:25 +00001317 if (const RecordType *ClassType = T->getAsRecordType())
1318 if (CXXRecordDecl *ClassDecl
1319 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1320 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1321 AssociatedNamespaces,
1322 AssociatedClasses);
1323 return;
1324 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001325
1326 // -- If T is an enumeration type, its associated namespace is
1327 // the namespace in which it is defined. If it is class
1328 // member, its associated class is the member’s class; else
1329 // it has no associated class.
1330 if (const EnumType *EnumT = T->getAsEnumType()) {
1331 EnumDecl *Enum = EnumT->getDecl();
1332
1333 DeclContext *Ctx = Enum->getDeclContext();
1334 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1335 AssociatedClasses.insert(EnclosingClass);
1336
1337 // Add the associated namespace for this class.
1338 while (Ctx->isRecord())
1339 Ctx = Ctx->getParent();
1340 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1341 AssociatedNamespaces.insert(EnclosingNamespace);
1342
1343 return;
1344 }
1345
1346 // -- If T is a function type, its associated namespaces and
1347 // classes are those associated with the function parameter
1348 // types and those associated with the return type.
1349 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1350 // Return type
1351 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1352 Context,
1353 AssociatedNamespaces, AssociatedClasses);
1354
Douglas Gregor4fa58902009-02-26 23:50:07 +00001355 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001356 if (!Proto)
1357 return;
1358
1359 // Argument types
Douglas Gregor4fa58902009-02-26 23:50:07 +00001360 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001361 ArgEnd = Proto->arg_type_end();
1362 Arg != ArgEnd; ++Arg)
1363 addAssociatedClassesAndNamespaces(*Arg, Context,
1364 AssociatedNamespaces, AssociatedClasses);
1365
1366 return;
1367 }
1368
1369 // -- If T is a pointer to a member function of a class X, its
1370 // associated namespaces and classes are those associated
1371 // with the function parameter types and return type,
1372 // together with those associated with X.
1373 //
1374 // -- If T is a pointer to a data member of class X, its
1375 // associated namespaces and classes are those associated
1376 // with the member type together with those associated with
1377 // X.
1378 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1379 // Handle the type that the pointer to member points to.
1380 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1381 Context,
1382 AssociatedNamespaces, AssociatedClasses);
1383
1384 // Handle the class type into which this points.
1385 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1386 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1387 Context,
1388 AssociatedNamespaces, AssociatedClasses);
1389
1390 return;
1391 }
1392
1393 // FIXME: What about block pointers?
1394 // FIXME: What about Objective-C message sends?
1395}
1396
1397/// \brief Find the associated classes and namespaces for
1398/// argument-dependent lookup for a call with the given set of
1399/// arguments.
1400///
1401/// This routine computes the sets of associated classes and associated
1402/// namespaces searched by argument-dependent lookup
1403/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1404void
1405Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1406 AssociatedNamespaceSet &AssociatedNamespaces,
1407 AssociatedClassSet &AssociatedClasses) {
1408 AssociatedNamespaces.clear();
1409 AssociatedClasses.clear();
1410
1411 // C++ [basic.lookup.koenig]p2:
1412 // For each argument type T in the function call, there is a set
1413 // of zero or more associated namespaces and a set of zero or more
1414 // associated classes to be considered. The sets of namespaces and
1415 // classes is determined entirely by the types of the function
1416 // arguments (and the namespace of any template template
1417 // argument).
1418 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1419 Expr *Arg = Args[ArgIdx];
1420
1421 if (Arg->getType() != Context.OverloadTy) {
1422 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
1423 AssociatedNamespaces, AssociatedClasses);
1424 continue;
1425 }
1426
1427 // [...] In addition, if the argument is the name or address of a
1428 // set of overloaded functions and/or function templates, its
1429 // associated classes and namespaces are the union of those
1430 // associated with each of the members of the set: the namespace
1431 // in which the function or function template is defined and the
1432 // classes and namespaces associated with its (non-dependent)
1433 // parameter types and return type.
1434 DeclRefExpr *DRE = 0;
1435 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1436 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1437 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1438 } else
1439 DRE = dyn_cast<DeclRefExpr>(Arg);
1440 if (!DRE)
1441 continue;
1442
1443 OverloadedFunctionDecl *Ovl
1444 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1445 if (!Ovl)
1446 continue;
1447
1448 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1449 FuncEnd = Ovl->function_end();
1450 Func != FuncEnd; ++Func) {
1451 FunctionDecl *FDecl = cast<FunctionDecl>(*Func);
1452
1453 // Add the namespace in which this function was defined. Note
1454 // that, if this is a member function, we do *not* consider the
1455 // enclosing namespace of its class.
1456 DeclContext *Ctx = FDecl->getDeclContext();
1457 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1458 AssociatedNamespaces.insert(EnclosingNamespace);
1459
1460 // Add the classes and namespaces associated with the parameter
1461 // types and return type of this function.
1462 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
1463 AssociatedNamespaces, AssociatedClasses);
1464 }
1465 }
1466}
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001467
1468/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1469/// an acceptable non-member overloaded operator for a call whose
1470/// arguments have types T1 (and, if non-empty, T2). This routine
1471/// implements the check in C++ [over.match.oper]p3b2 concerning
1472/// enumeration types.
1473static bool
1474IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1475 QualType T1, QualType T2,
1476 ASTContext &Context) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001477 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1478 return true;
1479
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001480 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1481 return true;
1482
1483 const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1484 if (Proto->getNumArgs() < 1)
1485 return false;
1486
1487 if (T1->isEnumeralType()) {
1488 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1489 if (Context.getCanonicalType(T1).getUnqualifiedType()
1490 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1491 return true;
1492 }
1493
1494 if (Proto->getNumArgs() < 2)
1495 return false;
1496
1497 if (!T2.isNull() && T2->isEnumeralType()) {
1498 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1499 if (Context.getCanonicalType(T2).getUnqualifiedType()
1500 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1501 return true;
1502 }
1503
1504 return false;
1505}
1506
Douglas Gregore57c8cc2009-04-23 23:18:26 +00001507/// \brief Find the protocol with the given name, if any.
1508ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
Douglas Gregorafd5eb32009-04-24 00:11:27 +00001509 Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl();
Douglas Gregore57c8cc2009-04-23 23:18:26 +00001510 return cast_or_null<ObjCProtocolDecl>(D);
1511}
1512
Douglas Gregorafd5eb32009-04-24 00:11:27 +00001513/// \brief Find the Objective-C implementation with the given name, if
1514/// any.
1515ObjCImplementationDecl *Sema::LookupObjCImplementation(IdentifierInfo *II) {
1516 Decl *D = LookupName(TUScope, II, LookupObjCImplementationName).getAsDecl();
1517 return cast_or_null<ObjCImplementationDecl>(D);
1518}
1519
1520/// \brief Find the Objective-C category implementation with the given
1521/// name, if any.
1522ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
1523 Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl();
1524 return cast_or_null<ObjCCategoryImplDecl>(D);
1525}
1526
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001527void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1528 QualType T1, QualType T2,
1529 FunctionSet &Functions) {
1530 // C++ [over.match.oper]p3:
1531 // -- The set of non-member candidates is the result of the
1532 // unqualified lookup of operator@ in the context of the
1533 // expression according to the usual rules for name lookup in
1534 // unqualified function calls (3.4.2) except that all member
1535 // functions are ignored. However, if no operand has a class
1536 // type, only those non-member functions in the lookup set
1537 // that have a first parameter of type T1 or “reference to
1538 // (possibly cv-qualified) T1”, when T1 is an enumeration
1539 // type, or (if there is a right operand) a second parameter
1540 // of type T2 or “reference to (possibly cv-qualified) T2”,
1541 // when T2 is an enumeration type, are candidate functions.
1542 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1543 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1544
1545 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1546
1547 if (!Operators)
1548 return;
1549
1550 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1551 Op != OpEnd; ++Op) {
1552 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
1553 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1554 Functions.insert(FD); // FIXME: canonical FD
1555 }
1556}
1557
1558void Sema::ArgumentDependentLookup(DeclarationName Name,
1559 Expr **Args, unsigned NumArgs,
1560 FunctionSet &Functions) {
1561 // Find all of the associated namespaces and classes based on the
1562 // arguments we have.
1563 AssociatedNamespaceSet AssociatedNamespaces;
1564 AssociatedClassSet AssociatedClasses;
1565 FindAssociatedClassesAndNamespaces(Args, NumArgs,
1566 AssociatedNamespaces, AssociatedClasses);
1567
1568 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001569 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1570 // and let Y be the lookup set produced by argument dependent
1571 // lookup (defined as follows). If X contains [...] then Y is
1572 // empty. Otherwise Y is the set of declarations found in the
1573 // namespaces associated with the argument types as described
1574 // below. The set of declarations found by the lookup of the name
1575 // is the union of X and Y.
1576 //
1577 // Here, we compute Y and add its members to the overloaded
1578 // candidate set.
1579 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1580 NSEnd = AssociatedNamespaces.end();
1581 NS != NSEnd; ++NS) {
1582 // When considering an associated namespace, the lookup is the
1583 // same as the lookup performed when the associated namespace is
1584 // used as a qualifier (3.4.3.2) except that:
1585 //
1586 // -- Any using-directives in the associated namespace are
1587 // ignored.
1588 //
1589 // -- FIXME: Any namespace-scope friend functions declared in
1590 // associated classes are visible within their respective
1591 // namespaces even if they are not visible during an ordinary
1592 // lookup (11.4).
1593 DeclContext::lookup_iterator I, E;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001594 for (llvm::tie(I, E) = (*NS)->lookup(Context, Name); I != E; ++I) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001595 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1596 if (!Func)
1597 break;
1598
1599 Functions.insert(Func);
1600 }
1601 }
1602}
1603