blob: 9bcf320771ef83a1b494eb1faae5233ea6d1b080 [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 Gregor3eb20702009-05-11 19:58:34 +000020#include "clang/AST/DeclTemplate.h"
Douglas Gregoraa1da4a2009-02-04 00:32:51 +000021#include "clang/AST/Expr.h"
Douglas Gregor78d70132009-01-14 22:20:51 +000022#include "clang/Parse/DeclSpec.h"
Chris Lattnerc46fcdd2009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Douglas Gregor78d70132009-01-14 22:20:51 +000024#include "clang/Basic/LangOptions.h"
25#include "llvm/ADT/STLExtras.h"
Douglas Gregoraa1da4a2009-02-04 00:32:51 +000026#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorb9ef0552009-01-16 00:38:09 +000027#include <set>
Douglas Gregor7a7be652009-02-03 19:21:40 +000028#include <vector>
29#include <iterator>
30#include <utility>
31#include <algorithm>
Douglas Gregor78d70132009-01-14 22:20:51 +000032
33using namespace clang;
34
Douglas Gregor7a7be652009-02-03 19:21:40 +000035typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy;
36typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet;
37typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy;
38
39/// UsingDirAncestorCompare - Implements strict weak ordering of
40/// UsingDirectives. It orders them by address of its common ancestor.
41struct UsingDirAncestorCompare {
42
43 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
44 bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const {
45 return U->getCommonAncestor() < Ctx;
46 }
47
48 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
49 bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const {
50 return Ctx < U->getCommonAncestor();
51 }
52
53 /// @brief Compares UsingDirectiveDecl common ancestors.
54 bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const {
55 return U1->getCommonAncestor() < U2->getCommonAncestor();
56 }
57};
58
59/// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs
60/// (ordered by common ancestors), found in namespace NS,
61/// including all found (recursively) in their nominated namespaces.
Douglas Gregorc55b0b02009-04-09 21:40:53 +000062void AddNamespaceUsingDirectives(ASTContext &Context,
63 DeclContext *NS,
Douglas Gregor7a7be652009-02-03 19:21:40 +000064 UsingDirectivesTy &UDirs,
65 NamespaceSet &Visited) {
66 DeclContext::udir_iterator I, End;
67
Douglas Gregorc55b0b02009-04-09 21:40:53 +000068 for (llvm::tie(I, End) = NS->getUsingDirectives(Context); I !=End; ++I) {
Douglas Gregor7a7be652009-02-03 19:21:40 +000069 UDirs.push_back(*I);
70 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
71 NamespaceDecl *Nominated = (*I)->getNominatedNamespace();
72 if (Visited.insert(Nominated).second)
Douglas Gregorc55b0b02009-04-09 21:40:53 +000073 AddNamespaceUsingDirectives(Context, Nominated, UDirs, /*ref*/ Visited);
Douglas Gregor7a7be652009-02-03 19:21:40 +000074 }
75}
76
77/// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S,
78/// including all found in the namespaces they nominate.
Douglas Gregorc55b0b02009-04-09 21:40:53 +000079static void AddScopeUsingDirectives(ASTContext &Context, Scope *S,
80 UsingDirectivesTy &UDirs) {
Douglas Gregor7a7be652009-02-03 19:21:40 +000081 NamespaceSet VisitedNS;
82
83 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
84
85 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx))
86 VisitedNS.insert(NS);
87
Douglas Gregorc55b0b02009-04-09 21:40:53 +000088 AddNamespaceUsingDirectives(Context, Ctx, UDirs, /*ref*/ VisitedNS);
Douglas Gregor7a7be652009-02-03 19:21:40 +000089
90 } else {
Chris Lattner5261d0c2009-03-28 19:18:32 +000091 Scope::udir_iterator I = S->using_directives_begin(),
92 End = S->using_directives_end();
Douglas Gregor7a7be652009-02-03 19:21:40 +000093
94 for (; I != End; ++I) {
Chris Lattner5261d0c2009-03-28 19:18:32 +000095 UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>();
Douglas Gregor7a7be652009-02-03 19:21:40 +000096 UDirs.push_back(UD);
97 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
98
99 NamespaceDecl *Nominated = UD->getNominatedNamespace();
100 if (!VisitedNS.count(Nominated)) {
101 VisitedNS.insert(Nominated);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000102 AddNamespaceUsingDirectives(Context, Nominated, UDirs,
103 /*ref*/ VisitedNS);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000104 }
105 }
106 }
107}
108
Douglas Gregor78d70132009-01-14 22:20:51 +0000109/// MaybeConstructOverloadSet - Name lookup has determined that the
110/// elements in [I, IEnd) have the name that we are looking for, and
111/// *I is a match for the namespace. This routine returns an
112/// appropriate Decl for name lookup, which may either be *I or an
Douglas Gregor7a7be652009-02-03 19:21:40 +0000113/// OverloadedFunctionDecl that represents the overloaded functions in
Douglas Gregor78d70132009-01-14 22:20:51 +0000114/// [I, IEnd).
115///
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000116/// The existance of this routine is temporary; users of LookupResult
117/// should be able to handle multiple results, to deal with cases of
Douglas Gregor78d70132009-01-14 22:20:51 +0000118/// ambiguity and overloaded functions without needing to create a
119/// Decl node.
120template<typename DeclIterator>
Douglas Gregor09be81b2009-02-04 17:27:36 +0000121static NamedDecl *
Douglas Gregor78d70132009-01-14 22:20:51 +0000122MaybeConstructOverloadSet(ASTContext &Context,
123 DeclIterator I, DeclIterator IEnd) {
124 assert(I != IEnd && "Iterator range cannot be empty");
125 assert(!isa<OverloadedFunctionDecl>(*I) &&
126 "Cannot have an overloaded function");
127
128 if (isa<FunctionDecl>(*I)) {
129 // If we found a function, there might be more functions. If
130 // so, collect them into an overload set.
131 DeclIterator Last = I;
132 OverloadedFunctionDecl *Ovl = 0;
133 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
134 if (!Ovl) {
Mike Stumpe127ae32009-05-16 07:39:55 +0000135 // FIXME: We leak this overload set. Eventually, we want to stop
136 // building the declarations for these overload sets, so there will be
137 // nothing to leak.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000138 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
Douglas Gregor78d70132009-01-14 22:20:51 +0000139 (*I)->getDeclName());
140 Ovl->addOverload(cast<FunctionDecl>(*I));
141 }
142 Ovl->addOverload(cast<FunctionDecl>(*Last));
143 }
144
145 // If we had more than one function, we built an overload
146 // set. Return it.
147 if (Ovl)
148 return Ovl;
149 }
150
151 return *I;
152}
153
Douglas Gregor7a7be652009-02-03 19:21:40 +0000154/// Merges together multiple LookupResults dealing with duplicated Decl's.
155static Sema::LookupResult
156MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
157 typedef Sema::LookupResult LResult;
Douglas Gregor09be81b2009-02-04 17:27:36 +0000158 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000159
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000160 // Remove duplicated Decl pointing at same Decl, by storing them in
161 // associative collection. This might be case for code like:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000162 //
163 // namespace A { int i; }
164 // namespace B { using namespace A; }
165 // namespace C { using namespace A; }
166 //
167 // void foo() {
168 // using namespace B;
169 // using namespace C;
170 // ++i; // finds A::i, from both namespace B and C at global scope
171 // }
172 //
173 // C++ [namespace.qual].p3:
174 // The same declaration found more than once is not an ambiguity
175 // (because it is still a unique declaration).
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000176 DeclsSetTy FoundDecls;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000177
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000178 // Counter of tag names, and functions for resolving ambiguity
179 // and name hiding.
180 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
Douglas Gregor09be81b2009-02-04 17:27:36 +0000181
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000182 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
183
184 // No name lookup results, return early.
185 if (I == End) return LResult::CreateLookupResult(Context, 0);
186
187 // Keep track of the tag declaration we found. We only use this if
188 // we find a single tag declaration.
189 TagDecl *TagFound = 0;
190
191 for (; I != End; ++I) {
192 switch (I->getKind()) {
193 case LResult::NotFound:
194 assert(false &&
195 "Should be always successful name lookup result here.");
196 break;
197
198 case LResult::AmbiguousReference:
199 case LResult::AmbiguousBaseSubobjectTypes:
200 case LResult::AmbiguousBaseSubobjects:
201 assert(false && "Shouldn't get ambiguous lookup here.");
202 break;
203
204 case LResult::Found: {
205 NamedDecl *ND = I->getAsDecl();
206 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
207 TagFound = Context.getCanonicalDecl(TD);
208 TagNames += FoundDecls.insert(TagFound)? 1 : 0;
209 } else if (isa<FunctionDecl>(ND))
210 Functions += FoundDecls.insert(ND)? 1 : 0;
211 else
212 FoundDecls.insert(ND);
213 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000214 }
215
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000216 case LResult::FoundOverloaded:
217 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
218 Functions += FoundDecls.insert(*FI)? 1 : 0;
219 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000220 }
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000221 }
222 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
223 bool Ambiguous = false, NameHidesTags = false;
224
225 if (FoundDecls.size() == 1) {
226 // 1) Exactly one result.
227 } else if (TagNames > 1) {
228 // 2) Multiple tag names (even though they may be hidden by an
229 // object name).
230 Ambiguous = true;
231 } else if (FoundDecls.size() - TagNames == 1) {
232 // 3) Ordinary name hides (optional) tag.
233 NameHidesTags = TagFound;
234 } else if (Functions) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000235 // C++ [basic.lookup].p1:
236 // ... Name lookup may associate more than one declaration with
Douglas Gregor7a7be652009-02-03 19:21:40 +0000237 // a name if it finds the name to be a function name; the declarations
238 // are said to form a set of overloaded functions (13.1).
239 // Overload resolution (13.3) takes place after name lookup has succeeded.
Douglas Gregor09be81b2009-02-04 17:27:36 +0000240 //
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000241 if (!OrdinaryNonFunc) {
242 // 4) Functions hide tag names.
243 NameHidesTags = TagFound;
244 } else {
245 // 5) Functions + ordinary names.
246 Ambiguous = true;
247 }
248 } else {
249 // 6) Multiple non-tag names
250 Ambiguous = true;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000251 }
252
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000253 if (Ambiguous)
254 return LResult::CreateLookupResult(Context,
255 FoundDecls.begin(), FoundDecls.size());
256 if (NameHidesTags) {
257 // There's only one tag, TagFound. Remove it.
258 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
259 FoundDecls.erase(TagFound);
260 }
261
262 // Return successful name lookup result.
263 return LResult::CreateLookupResult(Context,
264 MaybeConstructOverloadSet(Context,
265 FoundDecls.begin(),
266 FoundDecls.end()));
Douglas Gregor7a7be652009-02-03 19:21:40 +0000267}
268
269// Retrieve the set of identifier namespaces that correspond to a
270// specific kind of name lookup.
271inline unsigned
272getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
273 bool CPlusPlus) {
274 unsigned IDNS = 0;
275 switch (NameKind) {
276 case Sema::LookupOrdinaryName:
Douglas Gregor48a87322009-02-04 16:44:47 +0000277 case Sema::LookupOperatorName:
Douglas Gregor1c52c632009-02-24 20:03:32 +0000278 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000279 IDNS = Decl::IDNS_Ordinary;
280 if (CPlusPlus)
281 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
282 break;
283
284 case Sema::LookupTagName:
285 IDNS = Decl::IDNS_Tag;
286 break;
287
288 case Sema::LookupMemberName:
289 IDNS = Decl::IDNS_Member;
290 if (CPlusPlus)
291 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
292 break;
293
294 case Sema::LookupNestedNameSpecifierName:
295 case Sema::LookupNamespaceName:
296 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
297 break;
Douglas Gregore57c8cc2009-04-23 23:18:26 +0000298
Douglas Gregorafd5eb32009-04-24 00:11:27 +0000299 case Sema::LookupObjCProtocolName:
300 IDNS = Decl::IDNS_ObjCProtocol;
301 break;
302
303 case Sema::LookupObjCImplementationName:
304 IDNS = Decl::IDNS_ObjCImplementation;
305 break;
306
307 case Sema::LookupObjCCategoryImplName:
308 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregore57c8cc2009-04-23 23:18:26 +0000309 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000310 }
311 return IDNS;
312}
313
Douglas Gregor7a7be652009-02-03 19:21:40 +0000314Sema::LookupResult
Douglas Gregor09be81b2009-02-04 17:27:36 +0000315Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Douglas Gregor54713b62009-04-24 02:57:34 +0000316 if (ObjCCompatibleAliasDecl *Alias
317 = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
318 D = Alias->getClassInterface();
319
Douglas Gregor7a7be652009-02-03 19:21:40 +0000320 LookupResult Result;
321 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
322 OverloadedDeclSingleDecl : SingleDecl;
323 Result.First = reinterpret_cast<uintptr_t>(D);
324 Result.Last = 0;
325 Result.Context = &Context;
326 return Result;
327}
328
Douglas Gregor6beddfe2009-01-15 02:19:31 +0000329/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregord07474b2009-01-17 01:13:24 +0000330Sema::LookupResult
331Sema::LookupResult::CreateLookupResult(ASTContext &Context,
332 IdentifierResolver::iterator F,
333 IdentifierResolver::iterator L) {
334 LookupResult Result;
335 Result.Context = &Context;
336
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000337 if (F != L && isa<FunctionDecl>(*F)) {
338 IdentifierResolver::iterator Next = F;
339 ++Next;
340 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000341 Result.StoredKind = OverloadedDeclFromIdResolver;
342 Result.First = F.getAsOpaqueValue();
343 Result.Last = L.getAsOpaqueValue();
344 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000345 }
346 }
Douglas Gregor54713b62009-04-24 02:57:34 +0000347
348 Decl *D = *F;
349 if (ObjCCompatibleAliasDecl *Alias
350 = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
351 D = Alias->getClassInterface();
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000352
Douglas Gregord07474b2009-01-17 01:13:24 +0000353 Result.StoredKind = SingleDecl;
Douglas Gregor54713b62009-04-24 02:57:34 +0000354 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregord07474b2009-01-17 01:13:24 +0000355 Result.Last = 0;
356 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000357}
358
Douglas Gregord07474b2009-01-17 01:13:24 +0000359Sema::LookupResult
360Sema::LookupResult::CreateLookupResult(ASTContext &Context,
361 DeclContext::lookup_iterator F,
362 DeclContext::lookup_iterator L) {
363 LookupResult Result;
364 Result.Context = &Context;
365
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000366 if (F != L && isa<FunctionDecl>(*F)) {
367 DeclContext::lookup_iterator Next = F;
368 ++Next;
369 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000370 Result.StoredKind = OverloadedDeclFromDeclContext;
371 Result.First = reinterpret_cast<uintptr_t>(F);
372 Result.Last = reinterpret_cast<uintptr_t>(L);
373 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000374 }
375 }
Douglas Gregor54713b62009-04-24 02:57:34 +0000376
377 Decl *D = *F;
378 if (ObjCCompatibleAliasDecl *Alias
379 = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
380 D = Alias->getClassInterface();
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000381
Douglas Gregord07474b2009-01-17 01:13:24 +0000382 Result.StoredKind = SingleDecl;
Douglas Gregor54713b62009-04-24 02:57:34 +0000383 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregord07474b2009-01-17 01:13:24 +0000384 Result.Last = 0;
385 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000386}
387
Douglas Gregor78d70132009-01-14 22:20:51 +0000388/// @brief Determine the result of name lookup.
389Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
390 switch (StoredKind) {
391 case SingleDecl:
392 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
393
Douglas Gregor7a7be652009-02-03 19:21:40 +0000394 case OverloadedDeclSingleDecl:
Douglas Gregor78d70132009-01-14 22:20:51 +0000395 case OverloadedDeclFromIdResolver:
396 case OverloadedDeclFromDeclContext:
397 return FoundOverloaded;
398
Douglas Gregor7a7be652009-02-03 19:21:40 +0000399 case AmbiguousLookupStoresBasePaths:
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000400 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000401
402 case AmbiguousLookupStoresDecls:
403 return AmbiguousReference;
Douglas Gregor78d70132009-01-14 22:20:51 +0000404 }
405
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000406 // We can't ever get here.
407 return NotFound;
Douglas Gregor78d70132009-01-14 22:20:51 +0000408}
409
410/// @brief Converts the result of name lookup into a single (possible
411/// NULL) pointer to a declaration.
412///
413/// The resulting declaration will either be the declaration we found
414/// (if only a single declaration was found), an
415/// OverloadedFunctionDecl (if an overloaded function was found), or
416/// NULL (if no declaration was found). This conversion must not be
417/// used anywhere where name lookup could result in an ambiguity.
418///
419/// The OverloadedFunctionDecl conversion is meant as a stop-gap
420/// solution, since it causes the OverloadedFunctionDecl to be
421/// leaked. FIXME: Eventually, there will be a better way to iterate
422/// over the set of overloaded functions returned by name lookup.
Douglas Gregor09be81b2009-02-04 17:27:36 +0000423NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregor78d70132009-01-14 22:20:51 +0000424 switch (StoredKind) {
425 case SingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000426 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregor78d70132009-01-14 22:20:51 +0000427
428 case OverloadedDeclFromIdResolver:
429 return MaybeConstructOverloadSet(*Context,
430 IdentifierResolver::iterator::getFromOpaqueValue(First),
431 IdentifierResolver::iterator::getFromOpaqueValue(Last));
432
433 case OverloadedDeclFromDeclContext:
434 return MaybeConstructOverloadSet(*Context,
435 reinterpret_cast<DeclContext::lookup_iterator>(First),
436 reinterpret_cast<DeclContext::lookup_iterator>(Last));
437
Douglas Gregor7a7be652009-02-03 19:21:40 +0000438 case OverloadedDeclSingleDecl:
439 return reinterpret_cast<OverloadedFunctionDecl*>(First);
440
441 case AmbiguousLookupStoresDecls:
442 case AmbiguousLookupStoresBasePaths:
Douglas Gregor78d70132009-01-14 22:20:51 +0000443 assert(false &&
444 "Name lookup returned an ambiguity that could not be handled");
445 break;
446 }
447
448 return 0;
449}
450
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000451/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor7a7be652009-02-03 19:21:40 +0000452/// name lookup, or null.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000453BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000454 if (StoredKind == AmbiguousLookupStoresBasePaths)
455 return reinterpret_cast<BasePaths *>(First);
456 return 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000457}
458
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000459Sema::LookupResult::iterator::reference
460Sema::LookupResult::iterator::operator*() const {
461 switch (Result->StoredKind) {
462 case SingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000463 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000464
Douglas Gregor7a7be652009-02-03 19:21:40 +0000465 case OverloadedDeclSingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000466 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000467
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000468 case OverloadedDeclFromIdResolver:
469 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
470
Douglas Gregor7a7be652009-02-03 19:21:40 +0000471 case AmbiguousLookupStoresBasePaths:
Douglas Gregord7cb0372009-04-01 21:51:26 +0000472 if (Result->Last)
473 return *reinterpret_cast<NamedDecl**>(Current);
474
475 // Fall through to handle the DeclContext::lookup_iterator we're
476 // storing.
477
478 case OverloadedDeclFromDeclContext:
479 case AmbiguousLookupStoresDecls:
480 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000481 }
482
483 return 0;
484}
485
486Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
487 switch (Result->StoredKind) {
488 case SingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000489 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000490 break;
491
Douglas Gregor7a7be652009-02-03 19:21:40 +0000492 case OverloadedDeclSingleDecl: {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000493 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000494 ++I;
495 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregor48a87322009-02-04 16:44:47 +0000496 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000497 }
498
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000499 case OverloadedDeclFromIdResolver: {
500 IdentifierResolver::iterator I
501 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
502 ++I;
503 Current = I.getAsOpaqueValue();
504 break;
505 }
506
Douglas Gregord7cb0372009-04-01 21:51:26 +0000507 case AmbiguousLookupStoresBasePaths:
508 if (Result->Last) {
509 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
510 ++I;
511 Current = reinterpret_cast<uintptr_t>(I);
512 break;
513 }
514 // Fall through to handle the DeclContext::lookup_iterator we're
515 // storing.
516
517 case OverloadedDeclFromDeclContext:
518 case AmbiguousLookupStoresDecls: {
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000519 DeclContext::lookup_iterator I
520 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
521 ++I;
522 Current = reinterpret_cast<uintptr_t>(I);
523 break;
524 }
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000525 }
526
527 return *this;
528}
529
530Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregord7cb0372009-04-01 21:51:26 +0000531 switch (StoredKind) {
532 case SingleDecl:
533 case OverloadedDeclFromIdResolver:
534 case OverloadedDeclFromDeclContext:
535 case AmbiguousLookupStoresDecls:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000536 return iterator(this, First);
Douglas Gregord7cb0372009-04-01 21:51:26 +0000537
538 case OverloadedDeclSingleDecl: {
539 OverloadedFunctionDecl * Ovl =
540 reinterpret_cast<OverloadedFunctionDecl*>(First);
541 return iterator(this,
542 reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
543 }
544
545 case AmbiguousLookupStoresBasePaths:
546 if (Last)
547 return iterator(this,
548 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin()));
549 else
550 return iterator(this,
551 reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first));
552 }
553
554 // Required to suppress GCC warning.
555 return iterator();
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000556}
557
558Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregord7cb0372009-04-01 21:51:26 +0000559 switch (StoredKind) {
560 case SingleDecl:
561 case OverloadedDeclFromIdResolver:
562 case OverloadedDeclFromDeclContext:
563 case AmbiguousLookupStoresDecls:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000564 return iterator(this, Last);
Douglas Gregord7cb0372009-04-01 21:51:26 +0000565
566 case OverloadedDeclSingleDecl: {
567 OverloadedFunctionDecl * Ovl =
568 reinterpret_cast<OverloadedFunctionDecl*>(First);
569 return iterator(this,
570 reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
571 }
572
573 case AmbiguousLookupStoresBasePaths:
574 if (Last)
575 return iterator(this,
576 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end()));
577 else
578 return iterator(this, reinterpret_cast<uintptr_t>(
579 getBasePaths()->front().Decls.second));
580 }
581
582 // Required to suppress GCC warning.
583 return iterator();
584}
585
586void Sema::LookupResult::Destroy() {
587 if (BasePaths *Paths = getBasePaths())
588 delete Paths;
589 else if (getKind() == AmbiguousReference)
590 delete[] reinterpret_cast<NamedDecl **>(First);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000591}
592
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000593static void
594CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
595 DeclarationName Name, Sema::LookupNameKind NameKind,
596 unsigned IDNS, LookupResultsTy &Results,
597 UsingDirectivesTy *UDirs = 0) {
598
599 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
600
601 // Perform qualified name lookup into the LookupCtx.
602 DeclContext::lookup_iterator I, E;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000603 for (llvm::tie(I, E) = NS->lookup(Context, Name); I != E; ++I)
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000604 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
605 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
606 break;
607 }
608
609 if (UDirs) {
610 // For each UsingDirectiveDecl, which common ancestor is equal
611 // to NS, we preform qualified name lookup into namespace nominated by it.
612 UsingDirectivesTy::const_iterator UI, UEnd;
613 llvm::tie(UI, UEnd) =
614 std::equal_range(UDirs->begin(), UDirs->end(), NS,
615 UsingDirAncestorCompare());
616
617 for (; UI != UEnd; ++UI)
618 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
619 Name, NameKind, IDNS, Results);
620 }
621}
622
623static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000624 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000625 return Ctx->isFileContext();
626 return false;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000627}
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000628
Douglas Gregor7a7be652009-02-03 19:21:40 +0000629std::pair<bool, Sema::LookupResult>
630Sema::CppLookupName(Scope *S, DeclarationName Name,
631 LookupNameKind NameKind, bool RedeclarationOnly) {
632 assert(getLangOptions().CPlusPlus &&
633 "Can perform only C++ lookup");
Douglas Gregor48a87322009-02-04 16:44:47 +0000634 unsigned IDNS
Douglas Gregor09be81b2009-02-04 17:27:36 +0000635 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000636 Scope *Initial = S;
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000637 DeclContext *OutOfLineCtx = 0;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000638 IdentifierResolver::iterator
639 I = IdResolver.begin(Name),
640 IEnd = IdResolver.end();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000641
Douglas Gregor7a7be652009-02-03 19:21:40 +0000642 // First we lookup local scope.
Douglas Gregor279272e2009-02-04 19:02:06 +0000643 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor7a7be652009-02-03 19:21:40 +0000644 // ...During unqualified name lookup (3.4.1), the names appear as if
645 // they were declared in the nearest enclosing namespace which contains
646 // both the using-directive and the nominated namespace.
647 // [Note: in this context, “contains” means “contains directly or
648 // indirectly”.
649 //
650 // For example:
651 // namespace A { int i; }
652 // void foo() {
653 // int i;
654 // {
655 // using namespace A;
656 // ++i; // finds local 'i', A::i appears at global scope
657 // }
658 // }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000659 //
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000660 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000661 // Check whether the IdResolver has anything in this scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000662 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000663 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
664 // We found something. Look for anything else in our scope
665 // with this same name and in an acceptable identifier
666 // namespace, so that we can construct an overload set if we
667 // need to.
668 IdentifierResolver::iterator LastI = I;
669 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000670 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor7a7be652009-02-03 19:21:40 +0000671 break;
672 }
673 LookupResult Result =
674 LookupResult::CreateLookupResult(Context, I, LastI);
675 return std::make_pair(true, Result);
676 }
677 }
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000678 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
679 LookupResult R;
680 // Perform member lookup into struct.
Mike Stumpe127ae32009-05-16 07:39:55 +0000681 // FIXME: In some cases, we know that every name that could be found by
682 // this qualified name lookup will also be on the identifier chain. For
683 // example, inside a class without any base classes, we never need to
684 // perform qualified lookup because all of the members are on top of the
685 // identifier chain.
Douglas Gregord3c78592009-03-27 04:21:56 +0000686 if (isa<RecordDecl>(Ctx)) {
687 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
Douglas Gregor23521802009-06-17 23:37:01 +0000688 if (R)
Douglas Gregord3c78592009-03-27 04:21:56 +0000689 return std::make_pair(true, R);
690 }
Douglas Gregore919fb02009-05-27 17:07:49 +0000691 if (Ctx->getParent() != Ctx->getLexicalParent()
692 || isa<CXXMethodDecl>(Ctx)) {
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000693 // It is out of line defined C++ method or struct, we continue
694 // doing name lookup in parent context. Once we will find namespace
695 // or translation-unit we save it for possible checking
696 // using-directives later.
697 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
698 OutOfLineCtx = OutOfLineCtx->getParent()) {
Douglas Gregord3c78592009-03-27 04:21:56 +0000699 R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
Douglas Gregor23521802009-06-17 23:37:01 +0000700 if (R)
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000701 return std::make_pair(true, R);
702 }
703 }
704 }
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000705 }
Douglas Gregor7a7be652009-02-03 19:21:40 +0000706
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000707 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor7a7be652009-02-03 19:21:40 +0000708 // nominated namespaces by those using-directives.
Mike Stumpe127ae32009-05-16 07:39:55 +0000709 // UsingDirectives are pushed to heap, in common ancestor pointer value order.
710 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
711 // don't build it for each lookup!
Douglas Gregor7a7be652009-02-03 19:21:40 +0000712 UsingDirectivesTy UDirs;
713 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor09be81b2009-02-04 17:27:36 +0000714 if (SC->getFlags() & Scope::DeclScope)
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000715 AddScopeUsingDirectives(Context, SC, UDirs);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000716
717 // Sort heapified UsingDirectiveDecls.
Douglas Gregor69319772009-05-18 22:06:54 +0000718 std::sort_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
Douglas Gregor7a7be652009-02-03 19:21:40 +0000719
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000720 // Lookup namespace scope, and global scope.
Douglas Gregor7a7be652009-02-03 19:21:40 +0000721 // Unqualified name lookup in C++ requires looking into scopes
722 // that aren't strictly lexical, and therefore we walk through the
723 // context as well as walking through the scopes.
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000724
725 LookupResultsTy LookupResults;
Sebastian Redl95216a62009-02-07 00:15:38 +0000726 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000727 "We should have been looking only at file context here already.");
728 bool LookedInCtx = false;
729 LookupResult Result;
730 while (OutOfLineCtx &&
731 OutOfLineCtx != S->getEntity() &&
732 OutOfLineCtx->isNamespace()) {
733 LookedInCtx = true;
734
735 // Look into context considering using-directives.
736 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
737 LookupResults, &UDirs);
738
739 if ((Result = MergeLookupResults(Context, LookupResults)) ||
740 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
741 return std::make_pair(true, Result);
742
743 OutOfLineCtx = OutOfLineCtx->getParent();
744 }
745
Douglas Gregor7a7be652009-02-03 19:21:40 +0000746 for (; S; S = S->getParent()) {
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000747 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
748 assert(Ctx && Ctx->isFileContext() &&
749 "We should have been looking only at file context here already.");
Douglas Gregor7a7be652009-02-03 19:21:40 +0000750
751 // Check whether the IdResolver has anything in this scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000752 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000753 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
754 // We found something. Look for anything else in our scope
755 // with this same name and in an acceptable identifier
756 // namespace, so that we can construct an overload set if we
757 // need to.
758 IdentifierResolver::iterator LastI = I;
759 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000760 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor7a7be652009-02-03 19:21:40 +0000761 break;
762 }
763
764 // We store name lookup result, and continue trying to look into
765 // associated context, and maybe namespaces nominated by
766 // using-directives.
767 LookupResults.push_back(
768 LookupResult::CreateLookupResult(Context, I, LastI));
769 break;
770 }
771 }
772
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000773 LookedInCtx = true;
774 // Look into context considering using-directives.
775 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
776 LookupResults, &UDirs);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000777
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000778 if ((Result = MergeLookupResults(Context, LookupResults)) ||
779 (RedeclarationOnly && !Ctx->isTransparentContext()))
780 return std::make_pair(true, Result);
781 }
Douglas Gregor7a7be652009-02-03 19:21:40 +0000782
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000783 if (!(LookedInCtx || LookupResults.empty())) {
784 // We didn't Performed lookup in Scope entity, so we return
785 // result form IdentifierResolver.
786 assert((LookupResults.size() == 1) && "Wrong size!");
787 return std::make_pair(true, LookupResults.front());
Douglas Gregor7a7be652009-02-03 19:21:40 +0000788 }
789 return std::make_pair(false, LookupResult());
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000790}
791
Douglas Gregor78d70132009-01-14 22:20:51 +0000792/// @brief Perform unqualified name lookup starting from a given
793/// scope.
794///
795/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
796/// used to find names within the current scope. For example, 'x' in
797/// @code
798/// int x;
799/// int f() {
800/// return x; // unqualified name look finds 'x' in the global scope
801/// }
802/// @endcode
803///
804/// Different lookup criteria can find different names. For example, a
805/// particular scope can have both a struct and a function of the same
806/// name, and each can be found by certain lookup criteria. For more
807/// information about lookup criteria, see the documentation for the
808/// class LookupCriteria.
809///
810/// @param S The scope from which unqualified name lookup will
811/// begin. If the lookup criteria permits, name lookup may also search
812/// in the parent scopes.
813///
814/// @param Name The name of the entity that we are searching for.
815///
Douglas Gregor411889e2009-02-13 23:20:09 +0000816/// @param Loc If provided, the source location where we're performing
817/// name lookup. At present, this is only used to produce diagnostics when
818/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor78d70132009-01-14 22:20:51 +0000819///
820/// @returns The result of name lookup, which includes zero or more
821/// declarations and possibly additional information used to diagnose
822/// ambiguities.
823Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000824Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor411889e2009-02-13 23:20:09 +0000825 bool RedeclarationOnly, bool AllowBuiltinCreation,
826 SourceLocation Loc) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000827 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000828
829 if (!getLangOptions().CPlusPlus) {
830 // Unqualified name lookup in C/Objective-C is purely lexical, so
831 // search in the declarations attached to the name.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000832 unsigned IDNS = 0;
833 switch (NameKind) {
834 case Sema::LookupOrdinaryName:
835 IDNS = Decl::IDNS_Ordinary;
836 break;
Douglas Gregor78d70132009-01-14 22:20:51 +0000837
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000838 case Sema::LookupTagName:
839 IDNS = Decl::IDNS_Tag;
840 break;
841
842 case Sema::LookupMemberName:
843 IDNS = Decl::IDNS_Member;
844 break;
845
Douglas Gregor48a87322009-02-04 16:44:47 +0000846 case Sema::LookupOperatorName:
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000847 case Sema::LookupNestedNameSpecifierName:
848 case Sema::LookupNamespaceName:
849 assert(false && "C does not perform these kinds of name lookup");
850 break;
Douglas Gregor1c52c632009-02-24 20:03:32 +0000851
852 case Sema::LookupRedeclarationWithLinkage:
853 // Find the nearest non-transparent declaration scope.
854 while (!(S->getFlags() & Scope::DeclScope) ||
855 (S->getEntity() &&
856 static_cast<DeclContext *>(S->getEntity())
857 ->isTransparentContext()))
858 S = S->getParent();
859 IDNS = Decl::IDNS_Ordinary;
860 break;
Douglas Gregore57c8cc2009-04-23 23:18:26 +0000861
Douglas Gregorafd5eb32009-04-24 00:11:27 +0000862 case Sema::LookupObjCProtocolName:
863 IDNS = Decl::IDNS_ObjCProtocol;
864 break;
865
866 case Sema::LookupObjCImplementationName:
867 IDNS = Decl::IDNS_ObjCImplementation;
868 break;
869
870 case Sema::LookupObjCCategoryImplName:
871 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregore57c8cc2009-04-23 23:18:26 +0000872 break;
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000873 }
874
Douglas Gregor78d70132009-01-14 22:20:51 +0000875 // Scan up the scope chain looking for a decl that matches this
876 // identifier that is in the appropriate namespace. This search
877 // should not take long, as shadowing of names is uncommon, and
878 // deep shadowing is extremely uncommon.
Douglas Gregor1c52c632009-02-24 20:03:32 +0000879 bool LeftStartingScope = false;
880
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000881 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
882 IEnd = IdResolver.end();
883 I != IEnd; ++I)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000884 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregor1c52c632009-02-24 20:03:32 +0000885 if (NameKind == LookupRedeclarationWithLinkage) {
886 // Determine whether this (or a previous) declaration is
887 // out-of-scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000888 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor1c52c632009-02-24 20:03:32 +0000889 LeftStartingScope = true;
890
891 // If we found something outside of our starting scope that
892 // does not have linkage, skip it.
893 if (LeftStartingScope && !((*I)->hasLinkage()))
894 continue;
895 }
896
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000897 if ((*I)->getAttr<OverloadableAttr>(Context)) {
Douglas Gregorfcb19192009-02-11 23:02:49 +0000898 // If this declaration has the "overloadable" attribute, we
899 // might have a set of overloaded functions.
900
901 // Figure out what scope the identifier is in.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000902 while (!(S->getFlags() & Scope::DeclScope) ||
903 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorfcb19192009-02-11 23:02:49 +0000904 S = S->getParent();
905
906 // Find the last declaration in this scope (with the same
907 // name, naturally).
908 IdentifierResolver::iterator LastI = I;
909 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000910 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorfcb19192009-02-11 23:02:49 +0000911 break;
912 }
913
914 return LookupResult::CreateLookupResult(Context, I, LastI);
915 }
916
917 // We have a single lookup result.
Douglas Gregord07474b2009-01-17 01:13:24 +0000918 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregorfcb19192009-02-11 23:02:49 +0000919 }
Douglas Gregor78d70132009-01-14 22:20:51 +0000920 } else {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000921 // Perform C++ unqualified name lookup.
922 std::pair<bool, LookupResult> MaybeResult =
923 CppLookupName(S, Name, NameKind, RedeclarationOnly);
924 if (MaybeResult.first)
925 return MaybeResult.second;
Douglas Gregor78d70132009-01-14 22:20:51 +0000926 }
927
928 // If we didn't find a use of this identifier, and if the identifier
929 // corresponds to a compiler builtin, create the decl object for the builtin
930 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1c52c632009-02-24 20:03:32 +0000931 if (NameKind == LookupOrdinaryName ||
932 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000933 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor411889e2009-02-13 23:20:09 +0000934 if (II && AllowBuiltinCreation) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000935 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor411889e2009-02-13 23:20:09 +0000936 if (unsigned BuiltinID = II->getBuiltinID()) {
937 // In C++, we don't have any predefined library functions like
938 // 'malloc'. Instead, we'll just error.
939 if (getLangOptions().CPlusPlus &&
940 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
941 return LookupResult::CreateLookupResult(Context, 0);
942
Douglas Gregord07474b2009-01-17 01:13:24 +0000943 return LookupResult::CreateLookupResult(Context,
Douglas Gregor78d70132009-01-14 22:20:51 +0000944 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
Douglas Gregor411889e2009-02-13 23:20:09 +0000945 S, RedeclarationOnly, Loc));
946 }
Douglas Gregor78d70132009-01-14 22:20:51 +0000947 }
Douglas Gregor78d70132009-01-14 22:20:51 +0000948 }
Douglas Gregord07474b2009-01-17 01:13:24 +0000949 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000950}
951
952/// @brief Perform qualified name lookup into a given context.
953///
954/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
955/// names when the context of those names is explicit specified, e.g.,
956/// "std::vector" or "x->member".
957///
958/// Different lookup criteria can find different names. For example, a
959/// particular scope can have both a struct and a function of the same
960/// name, and each can be found by certain lookup criteria. For more
961/// information about lookup criteria, see the documentation for the
962/// class LookupCriteria.
963///
964/// @param LookupCtx The context in which qualified name lookup will
965/// search. If the lookup criteria permits, name lookup may also search
966/// in the parent contexts or (for C++ classes) base classes.
967///
968/// @param Name The name of the entity that we are searching for.
969///
970/// @param Criteria The criteria that this routine will use to
971/// determine which names are visible and which names will be
972/// found. Note that name lookup will find a name that is visible by
973/// the given criteria, but the entity itself may not be semantically
974/// correct or even the kind of entity expected based on the
975/// lookup. For example, searching for a nested-name-specifier name
976/// might result in an EnumDecl, which is visible but is not permitted
977/// as a nested-name-specifier in C++03.
978///
979/// @returns The result of name lookup, which includes zero or more
980/// declarations and possibly additional information used to diagnose
981/// ambiguities.
982Sema::LookupResult
983Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000984 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000985 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
986
Douglas Gregord07474b2009-01-17 01:13:24 +0000987 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000988
989 // If we're performing qualified name lookup (e.g., lookup into a
990 // struct), find fields as part of ordinary name lookup.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000991 unsigned IDNS
992 = getIdentifierNamespacesFromLookupNameKind(NameKind,
993 getLangOptions().CPlusPlus);
994 if (NameKind == LookupOrdinaryName)
995 IDNS |= Decl::IDNS_Member;
Douglas Gregor78d70132009-01-14 22:20:51 +0000996
997 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor78d70132009-01-14 22:20:51 +0000998 DeclContext::lookup_iterator I, E;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000999 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001000 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregord07474b2009-01-17 01:13:24 +00001001 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregor78d70132009-01-14 22:20:51 +00001002
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001003 // If this isn't a C++ class or we aren't allowed to look into base
1004 // classes, we're done.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001005 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregord07474b2009-01-17 01:13:24 +00001006 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001007
1008 // Perform lookup into our base classes.
1009 BasePaths Paths;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001010 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001011
1012 // Look for this member in our base classes
1013 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001014 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregord07474b2009-01-17 01:13:24 +00001015 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001016
1017 // C++ [class.member.lookup]p2:
1018 // [...] If the resulting set of declarations are not all from
1019 // sub-objects of the same type, or the set has a nonstatic member
1020 // and includes members from distinct sub-objects, there is an
1021 // ambiguity and the program is ill-formed. Otherwise that set is
1022 // the result of the lookup.
1023 // FIXME: support using declarations!
1024 QualType SubobjectType;
Daniel Dunbarddebeca2009-01-15 18:32:35 +00001025 int SubobjectNumber = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001026 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1027 Path != PathEnd; ++Path) {
1028 const BasePathElement &PathElement = Path->back();
1029
1030 // Determine whether we're looking at a distinct sub-object or not.
1031 if (SubobjectType.isNull()) {
1032 // This is the first subobject we've looked at. Record it's type.
1033 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1034 SubobjectNumber = PathElement.SubobjectNumber;
1035 } else if (SubobjectType
1036 != Context.getCanonicalType(PathElement.Base->getType())) {
1037 // We found members of the given name in two subobjects of
1038 // different types. This lookup is ambiguous.
1039 BasePaths *PathsOnHeap = new BasePaths;
1040 PathsOnHeap->swap(Paths);
Douglas Gregord07474b2009-01-17 01:13:24 +00001041 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001042 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1043 // We have a different subobject of the same type.
1044
1045 // C++ [class.member.lookup]p5:
1046 // A static member, a nested type or an enumerator defined in
1047 // a base class T can unambiguously be found even if an object
1048 // has more than one base class subobject of type T.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001049 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001050 if (isa<VarDecl>(FirstDecl) ||
1051 isa<TypeDecl>(FirstDecl) ||
1052 isa<EnumConstantDecl>(FirstDecl))
1053 continue;
1054
1055 if (isa<CXXMethodDecl>(FirstDecl)) {
1056 // Determine whether all of the methods are static.
1057 bool AllMethodsAreStatic = true;
1058 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1059 Func != Path->Decls.second; ++Func) {
1060 if (!isa<CXXMethodDecl>(*Func)) {
1061 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1062 break;
1063 }
1064
1065 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1066 AllMethodsAreStatic = false;
1067 break;
1068 }
1069 }
1070
1071 if (AllMethodsAreStatic)
1072 continue;
1073 }
1074
1075 // We have found a nonstatic member name in multiple, distinct
1076 // subobjects. Name lookup is ambiguous.
1077 BasePaths *PathsOnHeap = new BasePaths;
1078 PathsOnHeap->swap(Paths);
Douglas Gregord07474b2009-01-17 01:13:24 +00001079 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001080 }
1081 }
1082
1083 // Lookup in a base class succeeded; return these results.
1084
1085 // If we found a function declaration, return an overload set.
1086 if (isa<FunctionDecl>(*Paths.front().Decls.first))
Douglas Gregord07474b2009-01-17 01:13:24 +00001087 return LookupResult::CreateLookupResult(Context,
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001088 Paths.front().Decls.first, Paths.front().Decls.second);
1089
1090 // We found a non-function declaration; return a single declaration.
Douglas Gregord07474b2009-01-17 01:13:24 +00001091 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregor78d70132009-01-14 22:20:51 +00001092}
1093
1094/// @brief Performs name lookup for a name that was parsed in the
1095/// source code, and may contain a C++ scope specifier.
1096///
1097/// This routine is a convenience routine meant to be called from
1098/// contexts that receive a name and an optional C++ scope specifier
1099/// (e.g., "N::M::x"). It will then perform either qualified or
1100/// unqualified name lookup (with LookupQualifiedName or LookupName,
1101/// respectively) on the given name and return those results.
1102///
1103/// @param S The scope from which unqualified name lookup will
1104/// begin.
1105///
1106/// @param SS An optional C++ scope-specified, e.g., "::N::M".
1107///
1108/// @param Name The name of the entity that name lookup will
1109/// search for.
1110///
Douglas Gregor411889e2009-02-13 23:20:09 +00001111/// @param Loc If provided, the source location where we're performing
1112/// name lookup. At present, this is only used to produce diagnostics when
1113/// C library functions (like "malloc") are implicitly declared.
1114///
Douglas Gregor78d70132009-01-14 22:20:51 +00001115/// @returns The result of qualified or unqualified name lookup.
1116Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001117Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1118 DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor411889e2009-02-13 23:20:09 +00001119 bool RedeclarationOnly, bool AllowBuiltinCreation,
1120 SourceLocation Loc) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00001121 if (SS && (SS->isSet() || SS->isInvalid())) {
1122 // If the scope specifier is invalid, don't even look for
1123 // anything.
1124 if (SS->isInvalid())
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001125 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +00001126
Douglas Gregor3eb20702009-05-11 19:58:34 +00001127 assert(!isUnknownSpecialization(*SS) && "Can't lookup dependent types");
1128
1129 if (isDependentScopeSpecifier(*SS)) {
1130 // Determine whether we are looking into the current
1131 // instantiation.
1132 NestedNameSpecifier *NNS
1133 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1134 CXXRecordDecl *Current = getCurrentInstantiationOf(NNS);
1135 assert(Current && "Bad dependent scope specifier");
1136
1137 // We nested name specifier refers to the current instantiation,
1138 // so now we will look for a member of the current instantiation
1139 // (C++0x [temp.dep.type]).
1140 unsigned IDNS = getIdentifierNamespacesFromLookupNameKind(NameKind, true);
1141 DeclContext::lookup_iterator I, E;
1142 for (llvm::tie(I, E) = Current->lookup(Context, Name); I != E; ++I)
1143 if (isAcceptableLookupResult(*I, NameKind, IDNS))
1144 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001145 }
Douglas Gregor3eb20702009-05-11 19:58:34 +00001146
1147 if (RequireCompleteDeclContext(*SS))
1148 return LookupResult::CreateLookupResult(Context, 0);
1149
1150 return LookupQualifiedName(computeDeclContext(*SS),
1151 Name, NameKind, RedeclarationOnly);
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001152 }
1153
Douglas Gregor683a1142009-06-20 00:51:54 +00001154 LookupResult result(LookupName(S, Name, NameKind, RedeclarationOnly,
1155 AllowBuiltinCreation, Loc));
1156
1157 return(result);
Douglas Gregor78d70132009-01-14 22:20:51 +00001158}
1159
Douglas Gregor7a7be652009-02-03 19:21:40 +00001160
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001161/// @brief Produce a diagnostic describing the ambiguity that resulted
1162/// from name lookup.
1163///
1164/// @param Result The ambiguous name lookup result.
1165///
1166/// @param Name The name of the entity that name lookup was
1167/// searching for.
1168///
1169/// @param NameLoc The location of the name within the source code.
1170///
1171/// @param LookupRange A source range that provides more
1172/// source-location information concerning the lookup itself. For
1173/// example, this range might highlight a nested-name-specifier that
1174/// precedes the name.
1175///
1176/// @returns true
1177bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1178 SourceLocation NameLoc,
1179 SourceRange LookupRange) {
1180 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1181
Douglas Gregord7cb0372009-04-01 21:51:26 +00001182 if (BasePaths *Paths = Result.getBasePaths()) {
Douglas Gregor7a7be652009-02-03 19:21:40 +00001183 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1184 QualType SubobjectType = Paths->front().back().Base->getType();
1185 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1186 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1187 << LookupRange;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001188
Douglas Gregor7a7be652009-02-03 19:21:40 +00001189 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
Douglas Gregord7cb0372009-04-01 21:51:26 +00001190 while (isa<CXXMethodDecl>(*Found) &&
1191 cast<CXXMethodDecl>(*Found)->isStatic())
Douglas Gregor7a7be652009-02-03 19:21:40 +00001192 ++Found;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001193
Douglas Gregor7a7be652009-02-03 19:21:40 +00001194 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1195
Douglas Gregord7cb0372009-04-01 21:51:26 +00001196 Result.Destroy();
Douglas Gregor7a7be652009-02-03 19:21:40 +00001197 return true;
1198 }
1199
1200 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1201 "Unhandled form of name lookup ambiguity");
1202
1203 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1204 << Name << LookupRange;
1205
1206 std::set<Decl *> DeclsPrinted;
1207 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1208 Path != PathEnd; ++Path) {
1209 Decl *D = *Path->Decls.first;
1210 if (DeclsPrinted.insert(D).second)
1211 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1212 }
1213
Douglas Gregord7cb0372009-04-01 21:51:26 +00001214 Result.Destroy();
Douglas Gregor7a7be652009-02-03 19:21:40 +00001215 return true;
1216 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
Douglas Gregor7a7be652009-02-03 19:21:40 +00001217 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1218
Douglas Gregor09be81b2009-02-04 17:27:36 +00001219 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
Douglas Gregord7cb0372009-04-01 21:51:26 +00001220 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor7a7be652009-02-03 19:21:40 +00001221
Chris Lattnerb02f5f22009-02-03 21:29:32 +00001222 for (; DI != DEnd; ++DI)
Douglas Gregor09be81b2009-02-04 17:27:36 +00001223 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor7a7be652009-02-03 19:21:40 +00001224
Douglas Gregord7cb0372009-04-01 21:51:26 +00001225 Result.Destroy();
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001226 return true;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001227 }
1228
Douglas Gregor7a7be652009-02-03 19:21:40 +00001229 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregord07474b2009-01-17 01:13:24 +00001230
Douglas Gregor7a7be652009-02-03 19:21:40 +00001231 // We can't reach here.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001232 return true;
1233}
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001234
1235// \brief Add the associated classes and namespaces for
1236// argument-dependent lookup with an argument of class type
1237// (C++ [basic.lookup.koenig]p2).
1238static void
1239addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1240 ASTContext &Context,
1241 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor6123ae62009-06-23 20:14:09 +00001242 Sema::AssociatedClassSet &AssociatedClasses,
1243 bool &GlobalScope) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001244 // C++ [basic.lookup.koenig]p2:
1245 // [...]
1246 // -- If T is a class type (including unions), its associated
1247 // classes are: the class itself; the class of which it is a
1248 // member, if any; and its direct and indirect base
1249 // classes. Its associated namespaces are the namespaces in
1250 // which its associated classes are defined.
1251
1252 // Add the class of which it is a member, if any.
1253 DeclContext *Ctx = Class->getDeclContext();
1254 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1255 AssociatedClasses.insert(EnclosingClass);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001256 // Add the associated namespace for this class.
1257 while (Ctx->isRecord())
1258 Ctx = Ctx->getParent();
1259 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1260 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor6123ae62009-06-23 20:14:09 +00001261 else if (Ctx->isTranslationUnit())
1262 GlobalScope = true;
1263
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001264 // Add the class itself. If we've already seen this class, we don't
1265 // need to visit base classes.
1266 if (!AssociatedClasses.insert(Class))
1267 return;
1268
1269 // FIXME: Handle class template specializations
1270
1271 // Add direct and indirect base classes along with their associated
1272 // namespaces.
1273 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1274 Bases.push_back(Class);
1275 while (!Bases.empty()) {
1276 // Pop this class off the stack.
1277 Class = Bases.back();
1278 Bases.pop_back();
1279
1280 // Visit the base classes.
1281 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1282 BaseEnd = Class->bases_end();
1283 Base != BaseEnd; ++Base) {
1284 const RecordType *BaseType = Base->getType()->getAsRecordType();
1285 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1286 if (AssociatedClasses.insert(BaseDecl)) {
1287 // Find the associated namespace for this base class.
1288 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1289 while (BaseCtx->isRecord())
1290 BaseCtx = BaseCtx->getParent();
1291 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1292 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor6123ae62009-06-23 20:14:09 +00001293 else if (BaseCtx->isTranslationUnit())
1294 GlobalScope = true;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001295
1296 // Make sure we visit the bases of this base class.
1297 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1298 Bases.push_back(BaseDecl);
1299 }
1300 }
1301 }
1302}
1303
1304// \brief Add the associated classes and namespaces for
1305// argument-dependent lookup with an argument of type T
1306// (C++ [basic.lookup.koenig]p2).
1307static void
1308addAssociatedClassesAndNamespaces(QualType T,
1309 ASTContext &Context,
1310 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor6123ae62009-06-23 20:14:09 +00001311 Sema::AssociatedClassSet &AssociatedClasses,
1312 bool &GlobalScope) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001313 // C++ [basic.lookup.koenig]p2:
1314 //
1315 // For each argument type T in the function call, there is a set
1316 // of zero or more associated namespaces and a set of zero or more
1317 // associated classes to be considered. The sets of namespaces and
1318 // classes is determined entirely by the types of the function
1319 // arguments (and the namespace of any template template
1320 // argument). Typedef names and using-declarations used to specify
1321 // the types do not contribute to this set. The sets of namespaces
1322 // and classes are determined in the following way:
1323 T = Context.getCanonicalType(T).getUnqualifiedType();
1324
1325 // -- If T is a pointer to U or an array of U, its associated
1326 // namespaces and classes are those associated with U.
1327 //
1328 // We handle this by unwrapping pointer and array types immediately,
1329 // to avoid unnecessary recursion.
1330 while (true) {
1331 if (const PointerType *Ptr = T->getAsPointerType())
1332 T = Ptr->getPointeeType();
1333 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1334 T = Ptr->getElementType();
1335 else
1336 break;
1337 }
1338
1339 // -- If T is a fundamental type, its associated sets of
1340 // namespaces and classes are both empty.
1341 if (T->getAsBuiltinType())
1342 return;
1343
1344 // -- If T is a class type (including unions), its associated
1345 // classes are: the class itself; the class of which it is a
1346 // member, if any; and its direct and indirect base
1347 // classes. Its associated namespaces are the namespaces in
1348 // which its associated classes are defined.
Douglas Gregor2e047592009-02-28 01:32:25 +00001349 if (const RecordType *ClassType = T->getAsRecordType())
1350 if (CXXRecordDecl *ClassDecl
1351 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1352 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1353 AssociatedNamespaces,
Douglas Gregor6123ae62009-06-23 20:14:09 +00001354 AssociatedClasses,
1355 GlobalScope);
Douglas Gregor2e047592009-02-28 01:32:25 +00001356 return;
1357 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001358
1359 // -- If T is an enumeration type, its associated namespace is
1360 // the namespace in which it is defined. If it is class
1361 // member, its associated class is the member’s class; else
1362 // it has no associated class.
1363 if (const EnumType *EnumT = T->getAsEnumType()) {
1364 EnumDecl *Enum = EnumT->getDecl();
1365
1366 DeclContext *Ctx = Enum->getDeclContext();
1367 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1368 AssociatedClasses.insert(EnclosingClass);
1369
1370 // Add the associated namespace for this class.
1371 while (Ctx->isRecord())
1372 Ctx = Ctx->getParent();
1373 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1374 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor6123ae62009-06-23 20:14:09 +00001375 else if (Ctx->isTranslationUnit())
1376 GlobalScope = true;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001377
1378 return;
1379 }
1380
1381 // -- If T is a function type, its associated namespaces and
1382 // classes are those associated with the function parameter
1383 // types and those associated with the return type.
1384 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1385 // Return type
1386 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1387 Context,
Douglas Gregor6123ae62009-06-23 20:14:09 +00001388 AssociatedNamespaces, AssociatedClasses,
1389 GlobalScope);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001390
Douglas Gregor4fa58902009-02-26 23:50:07 +00001391 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001392 if (!Proto)
1393 return;
1394
1395 // Argument types
Douglas Gregor4fa58902009-02-26 23:50:07 +00001396 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001397 ArgEnd = Proto->arg_type_end();
1398 Arg != ArgEnd; ++Arg)
1399 addAssociatedClassesAndNamespaces(*Arg, Context,
Douglas Gregor6123ae62009-06-23 20:14:09 +00001400 AssociatedNamespaces, AssociatedClasses,
1401 GlobalScope);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001402
1403 return;
1404 }
1405
1406 // -- If T is a pointer to a member function of a class X, its
1407 // associated namespaces and classes are those associated
1408 // with the function parameter types and return type,
1409 // together with those associated with X.
1410 //
1411 // -- If T is a pointer to a data member of class X, its
1412 // associated namespaces and classes are those associated
1413 // with the member type together with those associated with
1414 // X.
1415 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1416 // Handle the type that the pointer to member points to.
1417 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1418 Context,
Douglas Gregor6123ae62009-06-23 20:14:09 +00001419 AssociatedNamespaces, AssociatedClasses,
1420 GlobalScope);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001421
1422 // Handle the class type into which this points.
1423 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1424 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1425 Context,
Douglas Gregor6123ae62009-06-23 20:14:09 +00001426 AssociatedNamespaces, AssociatedClasses,
1427 GlobalScope);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001428
1429 return;
1430 }
1431
1432 // FIXME: What about block pointers?
1433 // FIXME: What about Objective-C message sends?
1434}
1435
1436/// \brief Find the associated classes and namespaces for
1437/// argument-dependent lookup for a call with the given set of
1438/// arguments.
1439///
1440/// This routine computes the sets of associated classes and associated
1441/// namespaces searched by argument-dependent lookup
1442/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1443void
1444Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1445 AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor6123ae62009-06-23 20:14:09 +00001446 AssociatedClassSet &AssociatedClasses,
1447 bool &GlobalScope) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001448 AssociatedNamespaces.clear();
1449 AssociatedClasses.clear();
1450
1451 // C++ [basic.lookup.koenig]p2:
1452 // For each argument type T in the function call, there is a set
1453 // of zero or more associated namespaces and a set of zero or more
1454 // associated classes to be considered. The sets of namespaces and
1455 // classes is determined entirely by the types of the function
1456 // arguments (and the namespace of any template template
1457 // argument).
1458 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1459 Expr *Arg = Args[ArgIdx];
1460
1461 if (Arg->getType() != Context.OverloadTy) {
1462 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
Douglas Gregor6123ae62009-06-23 20:14:09 +00001463 AssociatedNamespaces, AssociatedClasses,
1464 GlobalScope);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001465 continue;
1466 }
1467
1468 // [...] In addition, if the argument is the name or address of a
1469 // set of overloaded functions and/or function templates, its
1470 // associated classes and namespaces are the union of those
1471 // associated with each of the members of the set: the namespace
1472 // in which the function or function template is defined and the
1473 // classes and namespaces associated with its (non-dependent)
1474 // parameter types and return type.
1475 DeclRefExpr *DRE = 0;
1476 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1477 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1478 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1479 } else
1480 DRE = dyn_cast<DeclRefExpr>(Arg);
1481 if (!DRE)
1482 continue;
1483
1484 OverloadedFunctionDecl *Ovl
1485 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1486 if (!Ovl)
1487 continue;
1488
1489 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1490 FuncEnd = Ovl->function_end();
1491 Func != FuncEnd; ++Func) {
1492 FunctionDecl *FDecl = cast<FunctionDecl>(*Func);
1493
1494 // Add the namespace in which this function was defined. Note
1495 // that, if this is a member function, we do *not* consider the
1496 // enclosing namespace of its class.
1497 DeclContext *Ctx = FDecl->getDeclContext();
1498 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1499 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor6123ae62009-06-23 20:14:09 +00001500 else if (Ctx->isTranslationUnit())
1501 GlobalScope = true;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001502
1503 // Add the classes and namespaces associated with the parameter
1504 // types and return type of this function.
1505 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
Douglas Gregor6123ae62009-06-23 20:14:09 +00001506 AssociatedNamespaces, AssociatedClasses,
1507 GlobalScope);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001508 }
1509 }
1510}
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001511
1512/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1513/// an acceptable non-member overloaded operator for a call whose
1514/// arguments have types T1 (and, if non-empty, T2). This routine
1515/// implements the check in C++ [over.match.oper]p3b2 concerning
1516/// enumeration types.
1517static bool
1518IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1519 QualType T1, QualType T2,
1520 ASTContext &Context) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001521 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1522 return true;
1523
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001524 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1525 return true;
1526
1527 const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1528 if (Proto->getNumArgs() < 1)
1529 return false;
1530
1531 if (T1->isEnumeralType()) {
1532 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1533 if (Context.getCanonicalType(T1).getUnqualifiedType()
1534 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1535 return true;
1536 }
1537
1538 if (Proto->getNumArgs() < 2)
1539 return false;
1540
1541 if (!T2.isNull() && T2->isEnumeralType()) {
1542 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1543 if (Context.getCanonicalType(T2).getUnqualifiedType()
1544 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1545 return true;
1546 }
1547
1548 return false;
1549}
1550
Douglas Gregore57c8cc2009-04-23 23:18:26 +00001551/// \brief Find the protocol with the given name, if any.
1552ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
Douglas Gregorafd5eb32009-04-24 00:11:27 +00001553 Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl();
Douglas Gregore57c8cc2009-04-23 23:18:26 +00001554 return cast_or_null<ObjCProtocolDecl>(D);
1555}
1556
Douglas Gregorafd5eb32009-04-24 00:11:27 +00001557/// \brief Find the Objective-C implementation with the given name, if
1558/// any.
1559ObjCImplementationDecl *Sema::LookupObjCImplementation(IdentifierInfo *II) {
1560 Decl *D = LookupName(TUScope, II, LookupObjCImplementationName).getAsDecl();
1561 return cast_or_null<ObjCImplementationDecl>(D);
1562}
1563
1564/// \brief Find the Objective-C category implementation with the given
1565/// name, if any.
1566ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
1567 Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl();
1568 return cast_or_null<ObjCCategoryImplDecl>(D);
1569}
1570
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001571void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1572 QualType T1, QualType T2,
1573 FunctionSet &Functions) {
1574 // C++ [over.match.oper]p3:
1575 // -- The set of non-member candidates is the result of the
1576 // unqualified lookup of operator@ in the context of the
1577 // expression according to the usual rules for name lookup in
1578 // unqualified function calls (3.4.2) except that all member
1579 // functions are ignored. However, if no operand has a class
1580 // type, only those non-member functions in the lookup set
1581 // that have a first parameter of type T1 or “reference to
1582 // (possibly cv-qualified) T1”, when T1 is an enumeration
1583 // type, or (if there is a right operand) a second parameter
1584 // of type T2 or “reference to (possibly cv-qualified) T2”,
1585 // when T2 is an enumeration type, are candidate functions.
1586 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1587 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1588
1589 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1590
1591 if (!Operators)
1592 return;
1593
1594 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1595 Op != OpEnd; ++Op) {
1596 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
1597 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1598 Functions.insert(FD); // FIXME: canonical FD
1599 }
1600}
1601
1602void Sema::ArgumentDependentLookup(DeclarationName Name,
1603 Expr **Args, unsigned NumArgs,
1604 FunctionSet &Functions) {
1605 // Find all of the associated namespaces and classes based on the
1606 // arguments we have.
1607 AssociatedNamespaceSet AssociatedNamespaces;
1608 AssociatedClassSet AssociatedClasses;
Douglas Gregor6123ae62009-06-23 20:14:09 +00001609 bool GlobalScope = false;
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001610 FindAssociatedClassesAndNamespaces(Args, NumArgs,
Douglas Gregor6123ae62009-06-23 20:14:09 +00001611 AssociatedNamespaces, AssociatedClasses,
1612 GlobalScope);
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001613
1614 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001615 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1616 // and let Y be the lookup set produced by argument dependent
1617 // lookup (defined as follows). If X contains [...] then Y is
1618 // empty. Otherwise Y is the set of declarations found in the
1619 // namespaces associated with the argument types as described
1620 // below. The set of declarations found by the lookup of the name
1621 // is the union of X and Y.
1622 //
1623 // Here, we compute Y and add its members to the overloaded
1624 // candidate set.
1625 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1626 NSEnd = AssociatedNamespaces.end();
1627 NS != NSEnd; ++NS) {
1628 // When considering an associated namespace, the lookup is the
1629 // same as the lookup performed when the associated namespace is
1630 // used as a qualifier (3.4.3.2) except that:
1631 //
1632 // -- Any using-directives in the associated namespace are
1633 // ignored.
1634 //
1635 // -- FIXME: Any namespace-scope friend functions declared in
1636 // associated classes are visible within their respective
1637 // namespaces even if they are not visible during an ordinary
1638 // lookup (11.4).
1639 DeclContext::lookup_iterator I, E;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001640 for (llvm::tie(I, E) = (*NS)->lookup(Context, Name); I != E; ++I) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001641 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1642 if (!Func)
1643 break;
1644
1645 Functions.insert(Func);
1646 }
1647 }
Douglas Gregor6123ae62009-06-23 20:14:09 +00001648
1649 if (GlobalScope) {
1650 DeclContext::lookup_iterator I, E;
1651 for (llvm::tie(I, E)
1652 = Context.getTranslationUnitDecl()->lookup(Context, Name);
1653 I != E; ++I) {
1654 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1655 if (!Func)
1656 break;
1657
1658 Functions.insert(Func);
1659 }
1660 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001661}