blob: 4a699de6c8d9597a65b5d0fd3a7b5443beb54bdc [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 Gregor6e264102009-07-08 10:57:20 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor78d70132009-01-14 22:20:51 +000023#include "clang/Parse/DeclSpec.h"
Chris Lattnerc46fcdd2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregor78d70132009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
26#include "llvm/ADT/STLExtras.h"
Douglas Gregoraa1da4a2009-02-04 00:32:51 +000027#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorb9ef0552009-01-16 00:38:09 +000028#include <set>
Douglas Gregor7a7be652009-02-03 19:21:40 +000029#include <vector>
30#include <iterator>
31#include <utility>
32#include <algorithm>
Douglas Gregor78d70132009-01-14 22:20:51 +000033
34using namespace clang;
35
Douglas Gregor7a7be652009-02-03 19:21:40 +000036typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy;
37typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet;
38typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy;
39
40/// UsingDirAncestorCompare - Implements strict weak ordering of
41/// UsingDirectives. It orders them by address of its common ancestor.
42struct UsingDirAncestorCompare {
43
44 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
45 bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const {
46 return U->getCommonAncestor() < Ctx;
47 }
48
49 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
50 bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const {
51 return Ctx < U->getCommonAncestor();
52 }
53
54 /// @brief Compares UsingDirectiveDecl common ancestors.
55 bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const {
56 return U1->getCommonAncestor() < U2->getCommonAncestor();
57 }
58};
59
60/// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs
61/// (ordered by common ancestors), found in namespace NS,
62/// including all found (recursively) in their nominated namespaces.
Douglas Gregorc55b0b02009-04-09 21:40:53 +000063void AddNamespaceUsingDirectives(ASTContext &Context,
64 DeclContext *NS,
Douglas Gregor7a7be652009-02-03 19:21:40 +000065 UsingDirectivesTy &UDirs,
66 NamespaceSet &Visited) {
67 DeclContext::udir_iterator I, End;
68
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +000069 for (llvm::tie(I, End) = NS->getUsingDirectives(); I !=End; ++I) {
Douglas Gregor7a7be652009-02-03 19:21:40 +000070 UDirs.push_back(*I);
71 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
72 NamespaceDecl *Nominated = (*I)->getNominatedNamespace();
73 if (Visited.insert(Nominated).second)
Douglas Gregorc55b0b02009-04-09 21:40:53 +000074 AddNamespaceUsingDirectives(Context, Nominated, UDirs, /*ref*/ Visited);
Douglas Gregor7a7be652009-02-03 19:21:40 +000075 }
76}
77
78/// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S,
79/// including all found in the namespaces they nominate.
Douglas Gregorc55b0b02009-04-09 21:40:53 +000080static void AddScopeUsingDirectives(ASTContext &Context, Scope *S,
81 UsingDirectivesTy &UDirs) {
Douglas Gregor7a7be652009-02-03 19:21:40 +000082 NamespaceSet VisitedNS;
83
84 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
85
86 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx))
87 VisitedNS.insert(NS);
88
Douglas Gregorc55b0b02009-04-09 21:40:53 +000089 AddNamespaceUsingDirectives(Context, Ctx, UDirs, /*ref*/ VisitedNS);
Douglas Gregor7a7be652009-02-03 19:21:40 +000090
91 } else {
Chris Lattner5261d0c2009-03-28 19:18:32 +000092 Scope::udir_iterator I = S->using_directives_begin(),
93 End = S->using_directives_end();
Douglas Gregor7a7be652009-02-03 19:21:40 +000094
95 for (; I != End; ++I) {
Chris Lattner5261d0c2009-03-28 19:18:32 +000096 UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>();
Douglas Gregor7a7be652009-02-03 19:21:40 +000097 UDirs.push_back(UD);
98 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
99
100 NamespaceDecl *Nominated = UD->getNominatedNamespace();
101 if (!VisitedNS.count(Nominated)) {
102 VisitedNS.insert(Nominated);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000103 AddNamespaceUsingDirectives(Context, Nominated, UDirs,
104 /*ref*/ VisitedNS);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000105 }
106 }
107 }
108}
109
Douglas Gregor78d70132009-01-14 22:20:51 +0000110/// MaybeConstructOverloadSet - Name lookup has determined that the
111/// elements in [I, IEnd) have the name that we are looking for, and
112/// *I is a match for the namespace. This routine returns an
113/// appropriate Decl for name lookup, which may either be *I or an
Douglas Gregor7a7be652009-02-03 19:21:40 +0000114/// OverloadedFunctionDecl that represents the overloaded functions in
Douglas Gregor78d70132009-01-14 22:20:51 +0000115/// [I, IEnd).
116///
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000117/// The existance of this routine is temporary; users of LookupResult
118/// should be able to handle multiple results, to deal with cases of
Douglas Gregor78d70132009-01-14 22:20:51 +0000119/// ambiguity and overloaded functions without needing to create a
120/// Decl node.
121template<typename DeclIterator>
Douglas Gregor09be81b2009-02-04 17:27:36 +0000122static NamedDecl *
Douglas Gregor78d70132009-01-14 22:20:51 +0000123MaybeConstructOverloadSet(ASTContext &Context,
124 DeclIterator I, DeclIterator IEnd) {
125 assert(I != IEnd && "Iterator range cannot be empty");
126 assert(!isa<OverloadedFunctionDecl>(*I) &&
127 "Cannot have an overloaded function");
128
Douglas Gregorb60eb752009-06-25 22:08:12 +0000129 if ((*I)->isFunctionOrFunctionTemplate()) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000130 // If we found a function, there might be more functions. If
131 // so, collect them into an overload set.
132 DeclIterator Last = I;
133 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +0000134 for (++Last;
135 Last != IEnd && (*Last)->isFunctionOrFunctionTemplate();
136 ++Last) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000137 if (!Ovl) {
Mike Stumpe127ae32009-05-16 07:39:55 +0000138 // FIXME: We leak this overload set. Eventually, we want to stop
139 // building the declarations for these overload sets, so there will be
140 // nothing to leak.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000141 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
Douglas Gregor78d70132009-01-14 22:20:51 +0000142 (*I)->getDeclName());
Anders Carlssondf5ab842009-06-26 06:29:23 +0000143 NamedDecl *ND = (*I)->getUnderlyingDecl();
Anders Carlsson5847da52009-06-26 05:26:50 +0000144 if (isa<FunctionDecl>(ND))
145 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregorb60eb752009-06-25 22:08:12 +0000146 else
Anders Carlsson5847da52009-06-26 05:26:50 +0000147 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
Douglas Gregor78d70132009-01-14 22:20:51 +0000148 }
Douglas Gregorb60eb752009-06-25 22:08:12 +0000149
Anders Carlssondf5ab842009-06-26 06:29:23 +0000150 NamedDecl *ND = (*Last)->getUnderlyingDecl();
Anders Carlsson5847da52009-06-26 05:26:50 +0000151 if (isa<FunctionDecl>(ND))
152 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregorb60eb752009-06-25 22:08:12 +0000153 else
Anders Carlsson5847da52009-06-26 05:26:50 +0000154 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
Douglas Gregor78d70132009-01-14 22:20:51 +0000155 }
156
157 // If we had more than one function, we built an overload
158 // set. Return it.
159 if (Ovl)
160 return Ovl;
161 }
162
163 return *I;
164}
165
Douglas Gregor7a7be652009-02-03 19:21:40 +0000166/// Merges together multiple LookupResults dealing with duplicated Decl's.
167static Sema::LookupResult
168MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
169 typedef Sema::LookupResult LResult;
Douglas Gregor09be81b2009-02-04 17:27:36 +0000170 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000171
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000172 // Remove duplicated Decl pointing at same Decl, by storing them in
173 // associative collection. This might be case for code like:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000174 //
175 // namespace A { int i; }
176 // namespace B { using namespace A; }
177 // namespace C { using namespace A; }
178 //
179 // void foo() {
180 // using namespace B;
181 // using namespace C;
182 // ++i; // finds A::i, from both namespace B and C at global scope
183 // }
184 //
185 // C++ [namespace.qual].p3:
186 // The same declaration found more than once is not an ambiguity
187 // (because it is still a unique declaration).
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000188 DeclsSetTy FoundDecls;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000189
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000190 // Counter of tag names, and functions for resolving ambiguity
191 // and name hiding.
192 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
Douglas Gregor09be81b2009-02-04 17:27:36 +0000193
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000194 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
195
196 // No name lookup results, return early.
197 if (I == End) return LResult::CreateLookupResult(Context, 0);
198
199 // Keep track of the tag declaration we found. We only use this if
200 // we find a single tag declaration.
201 TagDecl *TagFound = 0;
202
203 for (; I != End; ++I) {
204 switch (I->getKind()) {
205 case LResult::NotFound:
206 assert(false &&
207 "Should be always successful name lookup result here.");
208 break;
209
210 case LResult::AmbiguousReference:
211 case LResult::AmbiguousBaseSubobjectTypes:
212 case LResult::AmbiguousBaseSubobjects:
213 assert(false && "Shouldn't get ambiguous lookup here.");
214 break;
215
216 case LResult::Found: {
Anders Carlssondf5ab842009-06-26 06:29:23 +0000217 NamedDecl *ND = I->getAsDecl()->getUnderlyingDecl();
Anders Carlssonc1b3e762009-06-26 03:54:13 +0000218
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000219 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +0000220 TagFound = TD->getCanonicalDecl();
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000221 TagNames += FoundDecls.insert(TagFound)? 1 : 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +0000222 } else if (ND->isFunctionOrFunctionTemplate())
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000223 Functions += FoundDecls.insert(ND)? 1 : 0;
224 else
225 FoundDecls.insert(ND);
226 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000227 }
228
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000229 case LResult::FoundOverloaded:
230 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
231 Functions += FoundDecls.insert(*FI)? 1 : 0;
232 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000233 }
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000234 }
235 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
236 bool Ambiguous = false, NameHidesTags = false;
237
238 if (FoundDecls.size() == 1) {
239 // 1) Exactly one result.
240 } else if (TagNames > 1) {
241 // 2) Multiple tag names (even though they may be hidden by an
242 // object name).
243 Ambiguous = true;
244 } else if (FoundDecls.size() - TagNames == 1) {
245 // 3) Ordinary name hides (optional) tag.
246 NameHidesTags = TagFound;
247 } else if (Functions) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000248 // C++ [basic.lookup].p1:
249 // ... Name lookup may associate more than one declaration with
Douglas Gregor7a7be652009-02-03 19:21:40 +0000250 // a name if it finds the name to be a function name; the declarations
251 // are said to form a set of overloaded functions (13.1).
252 // Overload resolution (13.3) takes place after name lookup has succeeded.
Douglas Gregor09be81b2009-02-04 17:27:36 +0000253 //
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000254 if (!OrdinaryNonFunc) {
255 // 4) Functions hide tag names.
256 NameHidesTags = TagFound;
257 } else {
258 // 5) Functions + ordinary names.
259 Ambiguous = true;
260 }
261 } else {
262 // 6) Multiple non-tag names
263 Ambiguous = true;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000264 }
265
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000266 if (Ambiguous)
267 return LResult::CreateLookupResult(Context,
268 FoundDecls.begin(), FoundDecls.size());
269 if (NameHidesTags) {
270 // There's only one tag, TagFound. Remove it.
271 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
272 FoundDecls.erase(TagFound);
273 }
274
275 // Return successful name lookup result.
276 return LResult::CreateLookupResult(Context,
277 MaybeConstructOverloadSet(Context,
278 FoundDecls.begin(),
279 FoundDecls.end()));
Douglas Gregor7a7be652009-02-03 19:21:40 +0000280}
281
282// Retrieve the set of identifier namespaces that correspond to a
283// specific kind of name lookup.
284inline unsigned
285getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
286 bool CPlusPlus) {
287 unsigned IDNS = 0;
288 switch (NameKind) {
289 case Sema::LookupOrdinaryName:
Douglas Gregor48a87322009-02-04 16:44:47 +0000290 case Sema::LookupOperatorName:
Douglas Gregor1c52c632009-02-24 20:03:32 +0000291 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000292 IDNS = Decl::IDNS_Ordinary;
293 if (CPlusPlus)
294 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
295 break;
296
297 case Sema::LookupTagName:
298 IDNS = Decl::IDNS_Tag;
299 break;
300
301 case Sema::LookupMemberName:
302 IDNS = Decl::IDNS_Member;
303 if (CPlusPlus)
304 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
305 break;
306
307 case Sema::LookupNestedNameSpecifierName:
308 case Sema::LookupNamespaceName:
309 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
310 break;
Douglas Gregore57c8cc2009-04-23 23:18:26 +0000311
Douglas Gregorafd5eb32009-04-24 00:11:27 +0000312 case Sema::LookupObjCProtocolName:
313 IDNS = Decl::IDNS_ObjCProtocol;
314 break;
315
316 case Sema::LookupObjCImplementationName:
317 IDNS = Decl::IDNS_ObjCImplementation;
318 break;
319
320 case Sema::LookupObjCCategoryImplName:
321 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregore57c8cc2009-04-23 23:18:26 +0000322 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000323 }
324 return IDNS;
325}
326
Douglas Gregor7a7be652009-02-03 19:21:40 +0000327Sema::LookupResult
Douglas Gregor09be81b2009-02-04 17:27:36 +0000328Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Anders Carlssondf5ab842009-06-26 06:29:23 +0000329 if (D)
330 D = D->getUnderlyingDecl();
Anders Carlssond50ff9b2009-06-26 03:37:05 +0000331
Douglas Gregor7a7be652009-02-03 19:21:40 +0000332 LookupResult Result;
333 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
334 OverloadedDeclSingleDecl : SingleDecl;
335 Result.First = reinterpret_cast<uintptr_t>(D);
336 Result.Last = 0;
337 Result.Context = &Context;
338 return Result;
339}
340
Douglas Gregor6beddfe2009-01-15 02:19:31 +0000341/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregord07474b2009-01-17 01:13:24 +0000342Sema::LookupResult
343Sema::LookupResult::CreateLookupResult(ASTContext &Context,
344 IdentifierResolver::iterator F,
345 IdentifierResolver::iterator L) {
346 LookupResult Result;
347 Result.Context = &Context;
348
Douglas Gregorb60eb752009-06-25 22:08:12 +0000349 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000350 IdentifierResolver::iterator Next = F;
351 ++Next;
Douglas Gregorb60eb752009-06-25 22:08:12 +0000352 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000353 Result.StoredKind = OverloadedDeclFromIdResolver;
354 Result.First = F.getAsOpaqueValue();
355 Result.Last = L.getAsOpaqueValue();
356 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000357 }
358 }
Douglas Gregor54713b62009-04-24 02:57:34 +0000359
Anders Carlssondf5ab842009-06-26 06:29:23 +0000360 NamedDecl *D = *F;
361 if (D)
362 D = D->getUnderlyingDecl();
Anders Carlssond50ff9b2009-06-26 03:37:05 +0000363
Douglas Gregord07474b2009-01-17 01:13:24 +0000364 Result.StoredKind = SingleDecl;
Douglas Gregor54713b62009-04-24 02:57:34 +0000365 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregord07474b2009-01-17 01:13:24 +0000366 Result.Last = 0;
367 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000368}
369
Douglas Gregord07474b2009-01-17 01:13:24 +0000370Sema::LookupResult
371Sema::LookupResult::CreateLookupResult(ASTContext &Context,
372 DeclContext::lookup_iterator F,
373 DeclContext::lookup_iterator L) {
374 LookupResult Result;
375 Result.Context = &Context;
376
Douglas Gregorb60eb752009-06-25 22:08:12 +0000377 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000378 DeclContext::lookup_iterator Next = F;
379 ++Next;
Douglas Gregorb60eb752009-06-25 22:08:12 +0000380 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000381 Result.StoredKind = OverloadedDeclFromDeclContext;
382 Result.First = reinterpret_cast<uintptr_t>(F);
383 Result.Last = reinterpret_cast<uintptr_t>(L);
384 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000385 }
386 }
Douglas Gregor54713b62009-04-24 02:57:34 +0000387
Anders Carlssondf5ab842009-06-26 06:29:23 +0000388 NamedDecl *D = *F;
389 if (D)
390 D = D->getUnderlyingDecl();
391
Douglas Gregord07474b2009-01-17 01:13:24 +0000392 Result.StoredKind = SingleDecl;
Douglas Gregor54713b62009-04-24 02:57:34 +0000393 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregord07474b2009-01-17 01:13:24 +0000394 Result.Last = 0;
395 return Result;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000396}
397
Douglas Gregor78d70132009-01-14 22:20:51 +0000398/// @brief Determine the result of name lookup.
399Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
400 switch (StoredKind) {
401 case SingleDecl:
402 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
403
Douglas Gregor7a7be652009-02-03 19:21:40 +0000404 case OverloadedDeclSingleDecl:
Douglas Gregor78d70132009-01-14 22:20:51 +0000405 case OverloadedDeclFromIdResolver:
406 case OverloadedDeclFromDeclContext:
407 return FoundOverloaded;
408
Douglas Gregor7a7be652009-02-03 19:21:40 +0000409 case AmbiguousLookupStoresBasePaths:
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000410 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000411
412 case AmbiguousLookupStoresDecls:
413 return AmbiguousReference;
Douglas Gregor78d70132009-01-14 22:20:51 +0000414 }
415
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000416 // We can't ever get here.
417 return NotFound;
Douglas Gregor78d70132009-01-14 22:20:51 +0000418}
419
420/// @brief Converts the result of name lookup into a single (possible
421/// NULL) pointer to a declaration.
422///
423/// The resulting declaration will either be the declaration we found
424/// (if only a single declaration was found), an
425/// OverloadedFunctionDecl (if an overloaded function was found), or
426/// NULL (if no declaration was found). This conversion must not be
427/// used anywhere where name lookup could result in an ambiguity.
428///
429/// The OverloadedFunctionDecl conversion is meant as a stop-gap
430/// solution, since it causes the OverloadedFunctionDecl to be
431/// leaked. FIXME: Eventually, there will be a better way to iterate
432/// over the set of overloaded functions returned by name lookup.
Douglas Gregor09be81b2009-02-04 17:27:36 +0000433NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregor78d70132009-01-14 22:20:51 +0000434 switch (StoredKind) {
435 case SingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000436 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregor78d70132009-01-14 22:20:51 +0000437
438 case OverloadedDeclFromIdResolver:
439 return MaybeConstructOverloadSet(*Context,
440 IdentifierResolver::iterator::getFromOpaqueValue(First),
441 IdentifierResolver::iterator::getFromOpaqueValue(Last));
442
443 case OverloadedDeclFromDeclContext:
444 return MaybeConstructOverloadSet(*Context,
445 reinterpret_cast<DeclContext::lookup_iterator>(First),
446 reinterpret_cast<DeclContext::lookup_iterator>(Last));
447
Douglas Gregor7a7be652009-02-03 19:21:40 +0000448 case OverloadedDeclSingleDecl:
449 return reinterpret_cast<OverloadedFunctionDecl*>(First);
450
451 case AmbiguousLookupStoresDecls:
452 case AmbiguousLookupStoresBasePaths:
Douglas Gregor78d70132009-01-14 22:20:51 +0000453 assert(false &&
454 "Name lookup returned an ambiguity that could not be handled");
455 break;
456 }
457
458 return 0;
459}
460
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000461/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor7a7be652009-02-03 19:21:40 +0000462/// name lookup, or null.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000463BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000464 if (StoredKind == AmbiguousLookupStoresBasePaths)
465 return reinterpret_cast<BasePaths *>(First);
466 return 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000467}
468
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000469Sema::LookupResult::iterator::reference
470Sema::LookupResult::iterator::operator*() const {
471 switch (Result->StoredKind) {
472 case SingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000473 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000474
Douglas Gregor7a7be652009-02-03 19:21:40 +0000475 case OverloadedDeclSingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000476 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000477
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000478 case OverloadedDeclFromIdResolver:
479 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
480
Douglas Gregor7a7be652009-02-03 19:21:40 +0000481 case AmbiguousLookupStoresBasePaths:
Douglas Gregord7cb0372009-04-01 21:51:26 +0000482 if (Result->Last)
483 return *reinterpret_cast<NamedDecl**>(Current);
484
485 // Fall through to handle the DeclContext::lookup_iterator we're
486 // storing.
487
488 case OverloadedDeclFromDeclContext:
489 case AmbiguousLookupStoresDecls:
490 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000491 }
492
493 return 0;
494}
495
496Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
497 switch (Result->StoredKind) {
498 case SingleDecl:
Douglas Gregor09be81b2009-02-04 17:27:36 +0000499 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000500 break;
501
Douglas Gregor7a7be652009-02-03 19:21:40 +0000502 case OverloadedDeclSingleDecl: {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000503 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000504 ++I;
505 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregor48a87322009-02-04 16:44:47 +0000506 break;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000507 }
508
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000509 case OverloadedDeclFromIdResolver: {
510 IdentifierResolver::iterator I
511 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
512 ++I;
513 Current = I.getAsOpaqueValue();
514 break;
515 }
516
Douglas Gregord7cb0372009-04-01 21:51:26 +0000517 case AmbiguousLookupStoresBasePaths:
518 if (Result->Last) {
519 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
520 ++I;
521 Current = reinterpret_cast<uintptr_t>(I);
522 break;
523 }
524 // Fall through to handle the DeclContext::lookup_iterator we're
525 // storing.
526
527 case OverloadedDeclFromDeclContext:
528 case AmbiguousLookupStoresDecls: {
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000529 DeclContext::lookup_iterator I
530 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
531 ++I;
532 Current = reinterpret_cast<uintptr_t>(I);
533 break;
534 }
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000535 }
536
537 return *this;
538}
539
540Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregord7cb0372009-04-01 21:51:26 +0000541 switch (StoredKind) {
542 case SingleDecl:
543 case OverloadedDeclFromIdResolver:
544 case OverloadedDeclFromDeclContext:
545 case AmbiguousLookupStoresDecls:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000546 return iterator(this, First);
Douglas Gregord7cb0372009-04-01 21:51:26 +0000547
548 case OverloadedDeclSingleDecl: {
549 OverloadedFunctionDecl * Ovl =
550 reinterpret_cast<OverloadedFunctionDecl*>(First);
551 return iterator(this,
552 reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
553 }
554
555 case AmbiguousLookupStoresBasePaths:
556 if (Last)
557 return iterator(this,
558 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin()));
559 else
560 return iterator(this,
561 reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first));
562 }
563
564 // Required to suppress GCC warning.
565 return iterator();
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000566}
567
568Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregord7cb0372009-04-01 21:51:26 +0000569 switch (StoredKind) {
570 case SingleDecl:
571 case OverloadedDeclFromIdResolver:
572 case OverloadedDeclFromDeclContext:
573 case AmbiguousLookupStoresDecls:
Douglas Gregor7a7be652009-02-03 19:21:40 +0000574 return iterator(this, Last);
Douglas Gregord7cb0372009-04-01 21:51:26 +0000575
576 case OverloadedDeclSingleDecl: {
577 OverloadedFunctionDecl * Ovl =
578 reinterpret_cast<OverloadedFunctionDecl*>(First);
579 return iterator(this,
580 reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
581 }
582
583 case AmbiguousLookupStoresBasePaths:
584 if (Last)
585 return iterator(this,
586 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end()));
587 else
588 return iterator(this, reinterpret_cast<uintptr_t>(
589 getBasePaths()->front().Decls.second));
590 }
591
592 // Required to suppress GCC warning.
593 return iterator();
594}
595
596void Sema::LookupResult::Destroy() {
597 if (BasePaths *Paths = getBasePaths())
598 delete Paths;
599 else if (getKind() == AmbiguousReference)
600 delete[] reinterpret_cast<NamedDecl **>(First);
Douglas Gregorbd4b0852009-02-02 21:35:47 +0000601}
602
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000603static void
604CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
605 DeclarationName Name, Sema::LookupNameKind NameKind,
606 unsigned IDNS, LookupResultsTy &Results,
607 UsingDirectivesTy *UDirs = 0) {
608
609 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
610
611 // Perform qualified name lookup into the LookupCtx.
612 DeclContext::lookup_iterator I, E;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000613 for (llvm::tie(I, E) = NS->lookup(Name); I != E; ++I)
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000614 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
615 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
616 break;
617 }
618
619 if (UDirs) {
620 // For each UsingDirectiveDecl, which common ancestor is equal
621 // to NS, we preform qualified name lookup into namespace nominated by it.
622 UsingDirectivesTy::const_iterator UI, UEnd;
623 llvm::tie(UI, UEnd) =
624 std::equal_range(UDirs->begin(), UDirs->end(), NS,
625 UsingDirAncestorCompare());
626
627 for (; UI != UEnd; ++UI)
628 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
629 Name, NameKind, IDNS, Results);
630 }
631}
632
633static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000634 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000635 return Ctx->isFileContext();
636 return false;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000637}
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000638
Douglas Gregor7a7be652009-02-03 19:21:40 +0000639std::pair<bool, Sema::LookupResult>
640Sema::CppLookupName(Scope *S, DeclarationName Name,
641 LookupNameKind NameKind, bool RedeclarationOnly) {
642 assert(getLangOptions().CPlusPlus &&
643 "Can perform only C++ lookup");
Douglas Gregor48a87322009-02-04 16:44:47 +0000644 unsigned IDNS
Douglas Gregor09be81b2009-02-04 17:27:36 +0000645 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
John McCall7de15912009-08-28 07:59:38 +0000646
647 // If we're testing for redeclarations, also look in the friend namespaces.
648 if (RedeclarationOnly) {
649 if (IDNS & Decl::IDNS_Tag) IDNS |= Decl::IDNS_TagFriend;
650 if (IDNS & Decl::IDNS_Ordinary) IDNS |= Decl::IDNS_OrdinaryFriend;
651 }
652
Douglas Gregor7a7be652009-02-03 19:21:40 +0000653 Scope *Initial = S;
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000654 DeclContext *OutOfLineCtx = 0;
Douglas Gregor7a7be652009-02-03 19:21:40 +0000655 IdentifierResolver::iterator
656 I = IdResolver.begin(Name),
657 IEnd = IdResolver.end();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000658
Douglas Gregor7a7be652009-02-03 19:21:40 +0000659 // First we lookup local scope.
Douglas Gregor279272e2009-02-04 19:02:06 +0000660 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor7a7be652009-02-03 19:21:40 +0000661 // ...During unqualified name lookup (3.4.1), the names appear as if
662 // they were declared in the nearest enclosing namespace which contains
663 // both the using-directive and the nominated namespace.
Eli Friedmand5a72f02009-08-05 19:21:58 +0000664 // [Note: in this context, "contains" means "contains directly or
665 // indirectly".
Douglas Gregor7a7be652009-02-03 19:21:40 +0000666 //
667 // For example:
668 // namespace A { int i; }
669 // void foo() {
670 // int i;
671 // {
672 // using namespace A;
673 // ++i; // finds local 'i', A::i appears at global scope
674 // }
675 // }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000676 //
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000677 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000678 // Check whether the IdResolver has anything in this scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000679 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000680 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
681 // We found something. Look for anything else in our scope
682 // with this same name and in an acceptable identifier
683 // namespace, so that we can construct an overload set if we
684 // need to.
685 IdentifierResolver::iterator LastI = I;
686 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000687 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor7a7be652009-02-03 19:21:40 +0000688 break;
689 }
690 LookupResult Result =
691 LookupResult::CreateLookupResult(Context, I, LastI);
692 return std::make_pair(true, Result);
693 }
694 }
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000695 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
696 LookupResult R;
697 // Perform member lookup into struct.
Mike Stumpe127ae32009-05-16 07:39:55 +0000698 // FIXME: In some cases, we know that every name that could be found by
699 // this qualified name lookup will also be on the identifier chain. For
700 // example, inside a class without any base classes, we never need to
701 // perform qualified lookup because all of the members are on top of the
702 // identifier chain.
Douglas Gregord3c78592009-03-27 04:21:56 +0000703 if (isa<RecordDecl>(Ctx)) {
704 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
Douglas Gregor23521802009-06-17 23:37:01 +0000705 if (R)
Douglas Gregord3c78592009-03-27 04:21:56 +0000706 return std::make_pair(true, R);
707 }
Douglas Gregore919fb02009-05-27 17:07:49 +0000708 if (Ctx->getParent() != Ctx->getLexicalParent()
709 || isa<CXXMethodDecl>(Ctx)) {
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000710 // It is out of line defined C++ method or struct, we continue
711 // doing name lookup in parent context. Once we will find namespace
712 // or translation-unit we save it for possible checking
713 // using-directives later.
714 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
715 OutOfLineCtx = OutOfLineCtx->getParent()) {
Douglas Gregord3c78592009-03-27 04:21:56 +0000716 R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
Douglas Gregor23521802009-06-17 23:37:01 +0000717 if (R)
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000718 return std::make_pair(true, R);
719 }
720 }
721 }
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000722 }
Douglas Gregor7a7be652009-02-03 19:21:40 +0000723
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000724 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor7a7be652009-02-03 19:21:40 +0000725 // nominated namespaces by those using-directives.
Mike Stumpe127ae32009-05-16 07:39:55 +0000726 // UsingDirectives are pushed to heap, in common ancestor pointer value order.
727 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
728 // don't build it for each lookup!
Douglas Gregor7a7be652009-02-03 19:21:40 +0000729 UsingDirectivesTy UDirs;
730 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor09be81b2009-02-04 17:27:36 +0000731 if (SC->getFlags() & Scope::DeclScope)
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000732 AddScopeUsingDirectives(Context, SC, UDirs);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000733
734 // Sort heapified UsingDirectiveDecls.
Douglas Gregor69319772009-05-18 22:06:54 +0000735 std::sort_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
Douglas Gregor7a7be652009-02-03 19:21:40 +0000736
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000737 // Lookup namespace scope, and global scope.
Douglas Gregor7a7be652009-02-03 19:21:40 +0000738 // Unqualified name lookup in C++ requires looking into scopes
739 // that aren't strictly lexical, and therefore we walk through the
740 // context as well as walking through the scopes.
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000741
742 LookupResultsTy LookupResults;
Sebastian Redl95216a62009-02-07 00:15:38 +0000743 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000744 "We should have been looking only at file context here already.");
745 bool LookedInCtx = false;
746 LookupResult Result;
747 while (OutOfLineCtx &&
748 OutOfLineCtx != S->getEntity() &&
749 OutOfLineCtx->isNamespace()) {
750 LookedInCtx = true;
751
752 // Look into context considering using-directives.
753 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
754 LookupResults, &UDirs);
755
756 if ((Result = MergeLookupResults(Context, LookupResults)) ||
757 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
758 return std::make_pair(true, Result);
759
760 OutOfLineCtx = OutOfLineCtx->getParent();
761 }
762
Douglas Gregor7a7be652009-02-03 19:21:40 +0000763 for (; S; S = S->getParent()) {
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000764 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregor29b47fc2009-08-24 18:55:03 +0000765 if (Ctx->isTransparentContext())
766 continue;
767
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000768 assert(Ctx && Ctx->isFileContext() &&
769 "We should have been looking only at file context here already.");
Douglas Gregor7a7be652009-02-03 19:21:40 +0000770
771 // Check whether the IdResolver has anything in this scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000772 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000773 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
774 // We found something. Look for anything else in our scope
775 // with this same name and in an acceptable identifier
776 // namespace, so that we can construct an overload set if we
777 // need to.
778 IdentifierResolver::iterator LastI = I;
779 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000780 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor7a7be652009-02-03 19:21:40 +0000781 break;
782 }
783
784 // We store name lookup result, and continue trying to look into
785 // associated context, and maybe namespaces nominated by
786 // using-directives.
787 LookupResults.push_back(
788 LookupResult::CreateLookupResult(Context, I, LastI));
789 break;
790 }
791 }
792
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000793 LookedInCtx = true;
794 // Look into context considering using-directives.
795 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
796 LookupResults, &UDirs);
Douglas Gregor7a7be652009-02-03 19:21:40 +0000797
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000798 if ((Result = MergeLookupResults(Context, LookupResults)) ||
799 (RedeclarationOnly && !Ctx->isTransparentContext()))
800 return std::make_pair(true, Result);
801 }
Douglas Gregor7a7be652009-02-03 19:21:40 +0000802
Douglas Gregorb96b92d2009-02-05 19:25:20 +0000803 if (!(LookedInCtx || LookupResults.empty())) {
804 // We didn't Performed lookup in Scope entity, so we return
805 // result form IdentifierResolver.
806 assert((LookupResults.size() == 1) && "Wrong size!");
807 return std::make_pair(true, LookupResults.front());
Douglas Gregor7a7be652009-02-03 19:21:40 +0000808 }
809 return std::make_pair(false, LookupResult());
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000810}
811
Douglas Gregor78d70132009-01-14 22:20:51 +0000812/// @brief Perform unqualified name lookup starting from a given
813/// scope.
814///
815/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
816/// used to find names within the current scope. For example, 'x' in
817/// @code
818/// int x;
819/// int f() {
820/// return x; // unqualified name look finds 'x' in the global scope
821/// }
822/// @endcode
823///
824/// Different lookup criteria can find different names. For example, a
825/// particular scope can have both a struct and a function of the same
826/// name, and each can be found by certain lookup criteria. For more
827/// information about lookup criteria, see the documentation for the
828/// class LookupCriteria.
829///
830/// @param S The scope from which unqualified name lookup will
831/// begin. If the lookup criteria permits, name lookup may also search
832/// in the parent scopes.
833///
834/// @param Name The name of the entity that we are searching for.
835///
Douglas Gregor411889e2009-02-13 23:20:09 +0000836/// @param Loc If provided, the source location where we're performing
837/// name lookup. At present, this is only used to produce diagnostics when
838/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor78d70132009-01-14 22:20:51 +0000839///
840/// @returns The result of name lookup, which includes zero or more
841/// declarations and possibly additional information used to diagnose
842/// ambiguities.
843Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000844Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor411889e2009-02-13 23:20:09 +0000845 bool RedeclarationOnly, bool AllowBuiltinCreation,
846 SourceLocation Loc) {
Douglas Gregord07474b2009-01-17 01:13:24 +0000847 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000848
849 if (!getLangOptions().CPlusPlus) {
850 // Unqualified name lookup in C/Objective-C is purely lexical, so
851 // search in the declarations attached to the name.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000852 unsigned IDNS = 0;
853 switch (NameKind) {
854 case Sema::LookupOrdinaryName:
855 IDNS = Decl::IDNS_Ordinary;
856 break;
Douglas Gregor78d70132009-01-14 22:20:51 +0000857
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000858 case Sema::LookupTagName:
859 IDNS = Decl::IDNS_Tag;
860 break;
861
862 case Sema::LookupMemberName:
863 IDNS = Decl::IDNS_Member;
864 break;
865
Douglas Gregor48a87322009-02-04 16:44:47 +0000866 case Sema::LookupOperatorName:
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000867 case Sema::LookupNestedNameSpecifierName:
868 case Sema::LookupNamespaceName:
869 assert(false && "C does not perform these kinds of name lookup");
870 break;
Douglas Gregor1c52c632009-02-24 20:03:32 +0000871
872 case Sema::LookupRedeclarationWithLinkage:
873 // Find the nearest non-transparent declaration scope.
874 while (!(S->getFlags() & Scope::DeclScope) ||
875 (S->getEntity() &&
876 static_cast<DeclContext *>(S->getEntity())
877 ->isTransparentContext()))
878 S = S->getParent();
879 IDNS = Decl::IDNS_Ordinary;
880 break;
Douglas Gregore57c8cc2009-04-23 23:18:26 +0000881
Douglas Gregorafd5eb32009-04-24 00:11:27 +0000882 case Sema::LookupObjCProtocolName:
883 IDNS = Decl::IDNS_ObjCProtocol;
884 break;
885
886 case Sema::LookupObjCImplementationName:
887 IDNS = Decl::IDNS_ObjCImplementation;
888 break;
889
890 case Sema::LookupObjCCategoryImplName:
891 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregore57c8cc2009-04-23 23:18:26 +0000892 break;
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000893 }
894
Douglas Gregor78d70132009-01-14 22:20:51 +0000895 // Scan up the scope chain looking for a decl that matches this
896 // identifier that is in the appropriate namespace. This search
897 // should not take long, as shadowing of names is uncommon, and
898 // deep shadowing is extremely uncommon.
Douglas Gregor1c52c632009-02-24 20:03:32 +0000899 bool LeftStartingScope = false;
900
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000901 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
902 IEnd = IdResolver.end();
903 I != IEnd; ++I)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000904 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregor1c52c632009-02-24 20:03:32 +0000905 if (NameKind == LookupRedeclarationWithLinkage) {
906 // Determine whether this (or a previous) declaration is
907 // out-of-scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000908 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor1c52c632009-02-24 20:03:32 +0000909 LeftStartingScope = true;
910
911 // If we found something outside of our starting scope that
912 // does not have linkage, skip it.
913 if (LeftStartingScope && !((*I)->hasLinkage()))
914 continue;
915 }
916
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +0000917 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorfcb19192009-02-11 23:02:49 +0000918 // If this declaration has the "overloadable" attribute, we
919 // might have a set of overloaded functions.
920
921 // Figure out what scope the identifier is in.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000922 while (!(S->getFlags() & Scope::DeclScope) ||
923 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorfcb19192009-02-11 23:02:49 +0000924 S = S->getParent();
925
926 // Find the last declaration in this scope (with the same
927 // name, naturally).
928 IdentifierResolver::iterator LastI = I;
929 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000930 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorfcb19192009-02-11 23:02:49 +0000931 break;
932 }
933
934 return LookupResult::CreateLookupResult(Context, I, LastI);
935 }
936
937 // We have a single lookup result.
Douglas Gregord07474b2009-01-17 01:13:24 +0000938 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregorfcb19192009-02-11 23:02:49 +0000939 }
Douglas Gregor78d70132009-01-14 22:20:51 +0000940 } else {
Douglas Gregor7a7be652009-02-03 19:21:40 +0000941 // Perform C++ unqualified name lookup.
942 std::pair<bool, LookupResult> MaybeResult =
943 CppLookupName(S, Name, NameKind, RedeclarationOnly);
944 if (MaybeResult.first)
945 return MaybeResult.second;
Douglas Gregor78d70132009-01-14 22:20:51 +0000946 }
947
948 // If we didn't find a use of this identifier, and if the identifier
949 // corresponds to a compiler builtin, create the decl object for the builtin
950 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1c52c632009-02-24 20:03:32 +0000951 if (NameKind == LookupOrdinaryName ||
952 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000953 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor411889e2009-02-13 23:20:09 +0000954 if (II && AllowBuiltinCreation) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000955 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor411889e2009-02-13 23:20:09 +0000956 if (unsigned BuiltinID = II->getBuiltinID()) {
957 // In C++, we don't have any predefined library functions like
958 // 'malloc'. Instead, we'll just error.
959 if (getLangOptions().CPlusPlus &&
960 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
961 return LookupResult::CreateLookupResult(Context, 0);
962
Douglas Gregord07474b2009-01-17 01:13:24 +0000963 return LookupResult::CreateLookupResult(Context,
Douglas Gregor78d70132009-01-14 22:20:51 +0000964 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
Douglas Gregor411889e2009-02-13 23:20:09 +0000965 S, RedeclarationOnly, Loc));
966 }
Douglas Gregor78d70132009-01-14 22:20:51 +0000967 }
Douglas Gregor78d70132009-01-14 22:20:51 +0000968 }
Douglas Gregord07474b2009-01-17 01:13:24 +0000969 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +0000970}
971
972/// @brief Perform qualified name lookup into a given context.
973///
974/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
975/// names when the context of those names is explicit specified, e.g.,
976/// "std::vector" or "x->member".
977///
978/// Different lookup criteria can find different names. For example, a
979/// particular scope can have both a struct and a function of the same
980/// name, and each can be found by certain lookup criteria. For more
981/// information about lookup criteria, see the documentation for the
982/// class LookupCriteria.
983///
984/// @param LookupCtx The context in which qualified name lookup will
985/// search. If the lookup criteria permits, name lookup may also search
986/// in the parent contexts or (for C++ classes) base classes.
987///
988/// @param Name The name of the entity that we are searching for.
989///
990/// @param Criteria The criteria that this routine will use to
991/// determine which names are visible and which names will be
992/// found. Note that name lookup will find a name that is visible by
993/// the given criteria, but the entity itself may not be semantically
994/// correct or even the kind of entity expected based on the
995/// lookup. For example, searching for a nested-name-specifier name
996/// might result in an EnumDecl, which is visible but is not permitted
997/// as a nested-name-specifier in C++03.
998///
999/// @returns The result of name lookup, which includes zero or more
1000/// declarations and possibly additional information used to diagnose
1001/// ambiguities.
1002Sema::LookupResult
1003Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001004 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregor78d70132009-01-14 22:20:51 +00001005 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1006
Douglas Gregord07474b2009-01-17 01:13:24 +00001007 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor78d70132009-01-14 22:20:51 +00001008
1009 // If we're performing qualified name lookup (e.g., lookup into a
1010 // struct), find fields as part of ordinary name lookup.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001011 unsigned IDNS
1012 = getIdentifierNamespacesFromLookupNameKind(NameKind,
1013 getLangOptions().CPlusPlus);
1014 if (NameKind == LookupOrdinaryName)
1015 IDNS |= Decl::IDNS_Member;
Douglas Gregor78d70132009-01-14 22:20:51 +00001016
1017 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor78d70132009-01-14 22:20:51 +00001018 DeclContext::lookup_iterator I, E;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001019 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001020 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregord07474b2009-01-17 01:13:24 +00001021 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregor78d70132009-01-14 22:20:51 +00001022
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001023 // If this isn't a C++ class or we aren't allowed to look into base
1024 // classes, we're done.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001025 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregord07474b2009-01-17 01:13:24 +00001026 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001027
1028 // Perform lookup into our base classes.
1029 BasePaths Paths;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001030 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001031
1032 // Look for this member in our base classes
1033 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001034 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregord07474b2009-01-17 01:13:24 +00001035 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001036
1037 // C++ [class.member.lookup]p2:
1038 // [...] If the resulting set of declarations are not all from
1039 // sub-objects of the same type, or the set has a nonstatic member
1040 // and includes members from distinct sub-objects, there is an
1041 // ambiguity and the program is ill-formed. Otherwise that set is
1042 // the result of the lookup.
1043 // FIXME: support using declarations!
1044 QualType SubobjectType;
Daniel Dunbarddebeca2009-01-15 18:32:35 +00001045 int SubobjectNumber = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001046 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1047 Path != PathEnd; ++Path) {
1048 const BasePathElement &PathElement = Path->back();
1049
1050 // Determine whether we're looking at a distinct sub-object or not.
1051 if (SubobjectType.isNull()) {
1052 // This is the first subobject we've looked at. Record it's type.
1053 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1054 SubobjectNumber = PathElement.SubobjectNumber;
1055 } else if (SubobjectType
1056 != Context.getCanonicalType(PathElement.Base->getType())) {
1057 // We found members of the given name in two subobjects of
1058 // different types. This lookup is ambiguous.
1059 BasePaths *PathsOnHeap = new BasePaths;
1060 PathsOnHeap->swap(Paths);
Douglas Gregord07474b2009-01-17 01:13:24 +00001061 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001062 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1063 // We have a different subobject of the same type.
1064
1065 // C++ [class.member.lookup]p5:
1066 // A static member, a nested type or an enumerator defined in
1067 // a base class T can unambiguously be found even if an object
1068 // has more than one base class subobject of type T.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001069 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001070 if (isa<VarDecl>(FirstDecl) ||
1071 isa<TypeDecl>(FirstDecl) ||
1072 isa<EnumConstantDecl>(FirstDecl))
1073 continue;
1074
1075 if (isa<CXXMethodDecl>(FirstDecl)) {
1076 // Determine whether all of the methods are static.
1077 bool AllMethodsAreStatic = true;
1078 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1079 Func != Path->Decls.second; ++Func) {
1080 if (!isa<CXXMethodDecl>(*Func)) {
1081 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1082 break;
1083 }
1084
1085 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1086 AllMethodsAreStatic = false;
1087 break;
1088 }
1089 }
1090
1091 if (AllMethodsAreStatic)
1092 continue;
1093 }
1094
1095 // We have found a nonstatic member name in multiple, distinct
1096 // subobjects. Name lookup is ambiguous.
1097 BasePaths *PathsOnHeap = new BasePaths;
1098 PathsOnHeap->swap(Paths);
Douglas Gregord07474b2009-01-17 01:13:24 +00001099 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001100 }
1101 }
1102
1103 // Lookup in a base class succeeded; return these results.
1104
1105 // If we found a function declaration, return an overload set.
Douglas Gregorb60eb752009-06-25 22:08:12 +00001106 if ((*Paths.front().Decls.first)->isFunctionOrFunctionTemplate())
Douglas Gregord07474b2009-01-17 01:13:24 +00001107 return LookupResult::CreateLookupResult(Context,
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001108 Paths.front().Decls.first, Paths.front().Decls.second);
1109
1110 // We found a non-function declaration; return a single declaration.
Douglas Gregord07474b2009-01-17 01:13:24 +00001111 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregor78d70132009-01-14 22:20:51 +00001112}
1113
1114/// @brief Performs name lookup for a name that was parsed in the
1115/// source code, and may contain a C++ scope specifier.
1116///
1117/// This routine is a convenience routine meant to be called from
1118/// contexts that receive a name and an optional C++ scope specifier
1119/// (e.g., "N::M::x"). It will then perform either qualified or
1120/// unqualified name lookup (with LookupQualifiedName or LookupName,
1121/// respectively) on the given name and return those results.
1122///
1123/// @param S The scope from which unqualified name lookup will
1124/// begin.
1125///
Douglas Gregorc03d3302009-08-25 22:51:20 +00001126/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor78d70132009-01-14 22:20:51 +00001127///
1128/// @param Name The name of the entity that name lookup will
1129/// search for.
1130///
Douglas Gregor411889e2009-02-13 23:20:09 +00001131/// @param Loc If provided, the source location where we're performing
1132/// name lookup. At present, this is only used to produce diagnostics when
1133/// C library functions (like "malloc") are implicitly declared.
1134///
Douglas Gregorc03d3302009-08-25 22:51:20 +00001135/// @param EnteringContext Indicates whether we are going to enter the
1136/// context of the scope-specifier SS (if present).
1137///
Douglas Gregor78d70132009-01-14 22:20:51 +00001138/// @returns The result of qualified or unqualified name lookup.
1139Sema::LookupResult
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001140Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1141 DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor411889e2009-02-13 23:20:09 +00001142 bool RedeclarationOnly, bool AllowBuiltinCreation,
Douglas Gregorc03d3302009-08-25 22:51:20 +00001143 SourceLocation Loc,
1144 bool EnteringContext) {
1145 if (SS && SS->isInvalid()) {
1146 // When the scope specifier is invalid, don't even look for
Douglas Gregor3eb20702009-05-11 19:58:34 +00001147 // anything.
Douglas Gregorc03d3302009-08-25 22:51:20 +00001148 return LookupResult::CreateLookupResult(Context, 0);
1149 }
1150
1151 if (SS && SS->isSet()) {
1152 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1153 // We have resolved the scope specifier to a particular declaration
1154 // contex, and will perform name lookup in that context.
Douglas Gregor3eb20702009-05-11 19:58:34 +00001155
Douglas Gregorc03d3302009-08-25 22:51:20 +00001156 if (DC->isDependentContext()) {
1157 // If this is a dependent context, then we are looking for a member of
1158 // the current instantiation. This is a narrow search that looks into
1159 // just the described declaration context (C++0x [temp.dep.type]).
1160 unsigned IDNS = getIdentifierNamespacesFromLookupNameKind(NameKind,
1161 true);
1162 DeclContext::lookup_iterator I, E;
1163 for (llvm::tie(I, E) = DC->lookup(Name); I != E; ++I)
1164 if (isAcceptableLookupResult(*I, NameKind, IDNS))
1165 return LookupResult::CreateLookupResult(Context, I, E);
1166 }
1167
1168 // Qualified name lookup into the named declaration context.
1169 // The declaration context must be complete.
1170 if (RequireCompleteDeclContext(*SS))
1171 return LookupResult::CreateLookupResult(Context, 0);
1172
1173 return LookupQualifiedName(DC, Name, NameKind, RedeclarationOnly);
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001174 }
Douglas Gregor3eb20702009-05-11 19:58:34 +00001175
Douglas Gregorc03d3302009-08-25 22:51:20 +00001176 // We could not resolve the scope specified to a specific declaration
1177 // context, which means that SS refers to an unknown specialization.
1178 // Name lookup can't find anything in this case.
1179 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001180 }
1181
Douglas Gregorc03d3302009-08-25 22:51:20 +00001182 // Perform unqualified name lookup starting in the given scope.
1183 return LookupName(S, Name, NameKind, RedeclarationOnly, AllowBuiltinCreation,
1184 Loc);
Douglas Gregor78d70132009-01-14 22:20:51 +00001185}
1186
Douglas Gregor7a7be652009-02-03 19:21:40 +00001187
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001188/// @brief Produce a diagnostic describing the ambiguity that resulted
1189/// from name lookup.
1190///
1191/// @param Result The ambiguous name lookup result.
1192///
1193/// @param Name The name of the entity that name lookup was
1194/// searching for.
1195///
1196/// @param NameLoc The location of the name within the source code.
1197///
1198/// @param LookupRange A source range that provides more
1199/// source-location information concerning the lookup itself. For
1200/// example, this range might highlight a nested-name-specifier that
1201/// precedes the name.
1202///
1203/// @returns true
1204bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1205 SourceLocation NameLoc,
1206 SourceRange LookupRange) {
1207 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1208
Douglas Gregord7cb0372009-04-01 21:51:26 +00001209 if (BasePaths *Paths = Result.getBasePaths()) {
Douglas Gregor7a7be652009-02-03 19:21:40 +00001210 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1211 QualType SubobjectType = Paths->front().back().Base->getType();
1212 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1213 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1214 << LookupRange;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001215
Douglas Gregor7a7be652009-02-03 19:21:40 +00001216 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
Douglas Gregord7cb0372009-04-01 21:51:26 +00001217 while (isa<CXXMethodDecl>(*Found) &&
1218 cast<CXXMethodDecl>(*Found)->isStatic())
Douglas Gregor7a7be652009-02-03 19:21:40 +00001219 ++Found;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001220
Douglas Gregor7a7be652009-02-03 19:21:40 +00001221 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1222
Douglas Gregord7cb0372009-04-01 21:51:26 +00001223 Result.Destroy();
Douglas Gregor7a7be652009-02-03 19:21:40 +00001224 return true;
1225 }
1226
1227 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1228 "Unhandled form of name lookup ambiguity");
1229
1230 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1231 << Name << LookupRange;
1232
1233 std::set<Decl *> DeclsPrinted;
1234 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1235 Path != PathEnd; ++Path) {
1236 Decl *D = *Path->Decls.first;
1237 if (DeclsPrinted.insert(D).second)
1238 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1239 }
1240
Douglas Gregord7cb0372009-04-01 21:51:26 +00001241 Result.Destroy();
Douglas Gregor7a7be652009-02-03 19:21:40 +00001242 return true;
1243 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
Douglas Gregor7a7be652009-02-03 19:21:40 +00001244 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1245
Douglas Gregor09be81b2009-02-04 17:27:36 +00001246 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
Douglas Gregord7cb0372009-04-01 21:51:26 +00001247 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor7a7be652009-02-03 19:21:40 +00001248
Chris Lattnerb02f5f22009-02-03 21:29:32 +00001249 for (; DI != DEnd; ++DI)
Douglas Gregor09be81b2009-02-04 17:27:36 +00001250 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor7a7be652009-02-03 19:21:40 +00001251
Douglas Gregord7cb0372009-04-01 21:51:26 +00001252 Result.Destroy();
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001253 return true;
Douglas Gregorb9ef0552009-01-16 00:38:09 +00001254 }
1255
Douglas Gregor7a7be652009-02-03 19:21:40 +00001256 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregord07474b2009-01-17 01:13:24 +00001257
Douglas Gregor7a7be652009-02-03 19:21:40 +00001258 // We can't reach here.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001259 return true;
1260}
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001261
Douglas Gregora850d3c2009-07-08 07:51:57 +00001262static void
1263addAssociatedClassesAndNamespaces(QualType T,
1264 ASTContext &Context,
1265 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallb41b2052009-08-07 22:18:02 +00001266 Sema::AssociatedClassSet &AssociatedClasses);
1267
1268static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1269 DeclContext *Ctx) {
1270 if (Ctx->isFileContext())
1271 Namespaces.insert(Ctx);
1272}
Douglas Gregora850d3c2009-07-08 07:51:57 +00001273
1274// \brief Add the associated classes and namespaces for argument-dependent
1275// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1276static void
1277addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
1278 ASTContext &Context,
1279 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallb41b2052009-08-07 22:18:02 +00001280 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregora850d3c2009-07-08 07:51:57 +00001281 // C++ [basic.lookup.koenig]p2, last bullet:
1282 // -- [...] ;
1283 switch (Arg.getKind()) {
1284 case TemplateArgument::Null:
1285 break;
1286
1287 case TemplateArgument::Type:
1288 // [...] the namespaces and classes associated with the types of the
1289 // template arguments provided for template type parameters (excluding
1290 // template template parameters)
1291 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1292 AssociatedNamespaces,
John McCallb41b2052009-08-07 22:18:02 +00001293 AssociatedClasses);
Douglas Gregora850d3c2009-07-08 07:51:57 +00001294 break;
1295
1296 case TemplateArgument::Declaration:
1297 // [...] the namespaces in which any template template arguments are
1298 // defined; and the classes in which any member templates used as
1299 // template template arguments are defined.
1300 if (ClassTemplateDecl *ClassTemplate
1301 = dyn_cast<ClassTemplateDecl>(Arg.getAsDecl())) {
1302 DeclContext *Ctx = ClassTemplate->getDeclContext();
1303 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1304 AssociatedClasses.insert(EnclosingClass);
1305 // Add the associated namespace for this class.
1306 while (Ctx->isRecord())
1307 Ctx = Ctx->getParent();
John McCallb41b2052009-08-07 22:18:02 +00001308 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregora850d3c2009-07-08 07:51:57 +00001309 }
1310 break;
1311
1312 case TemplateArgument::Integral:
1313 case TemplateArgument::Expression:
1314 // [Note: non-type template arguments do not contribute to the set of
1315 // associated namespaces. ]
1316 break;
1317
1318 case TemplateArgument::Pack:
1319 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1320 PEnd = Arg.pack_end();
1321 P != PEnd; ++P)
1322 addAssociatedClassesAndNamespaces(*P, Context,
1323 AssociatedNamespaces,
John McCallb41b2052009-08-07 22:18:02 +00001324 AssociatedClasses);
Douglas Gregora850d3c2009-07-08 07:51:57 +00001325 break;
1326 }
1327}
1328
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001329// \brief Add the associated classes and namespaces for
1330// argument-dependent lookup with an argument of class type
1331// (C++ [basic.lookup.koenig]p2).
1332static void
1333addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1334 ASTContext &Context,
1335 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallb41b2052009-08-07 22:18:02 +00001336 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001337 // C++ [basic.lookup.koenig]p2:
1338 // [...]
1339 // -- If T is a class type (including unions), its associated
1340 // classes are: the class itself; the class of which it is a
1341 // member, if any; and its direct and indirect base
1342 // classes. Its associated namespaces are the namespaces in
1343 // which its associated classes are defined.
1344
1345 // Add the class of which it is a member, if any.
1346 DeclContext *Ctx = Class->getDeclContext();
1347 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1348 AssociatedClasses.insert(EnclosingClass);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001349 // Add the associated namespace for this class.
1350 while (Ctx->isRecord())
1351 Ctx = Ctx->getParent();
John McCallb41b2052009-08-07 22:18:02 +00001352 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor6123ae62009-06-23 20:14:09 +00001353
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001354 // Add the class itself. If we've already seen this class, we don't
1355 // need to visit base classes.
1356 if (!AssociatedClasses.insert(Class))
1357 return;
1358
Douglas Gregora850d3c2009-07-08 07:51:57 +00001359 // -- If T is a template-id, its associated namespaces and classes are
1360 // the namespace in which the template is defined; for member
1361 // templates, the member template’s class; the namespaces and classes
1362 // associated with the types of the template arguments provided for
1363 // template type parameters (excluding template template parameters); the
1364 // namespaces in which any template template arguments are defined; and
1365 // the classes in which any member templates used as template template
1366 // arguments are defined. [Note: non-type template arguments do not
1367 // contribute to the set of associated namespaces. ]
1368 if (ClassTemplateSpecializationDecl *Spec
1369 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1370 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1371 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1372 AssociatedClasses.insert(EnclosingClass);
1373 // Add the associated namespace for this class.
1374 while (Ctx->isRecord())
1375 Ctx = Ctx->getParent();
John McCallb41b2052009-08-07 22:18:02 +00001376 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregora850d3c2009-07-08 07:51:57 +00001377
1378 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1379 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1380 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1381 AssociatedNamespaces,
John McCallb41b2052009-08-07 22:18:02 +00001382 AssociatedClasses);
Douglas Gregora850d3c2009-07-08 07:51:57 +00001383 }
1384
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001385 // Add direct and indirect base classes along with their associated
1386 // namespaces.
1387 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1388 Bases.push_back(Class);
1389 while (!Bases.empty()) {
1390 // Pop this class off the stack.
1391 Class = Bases.back();
1392 Bases.pop_back();
1393
1394 // Visit the base classes.
1395 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1396 BaseEnd = Class->bases_end();
1397 Base != BaseEnd; ++Base) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001398 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001399 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1400 if (AssociatedClasses.insert(BaseDecl)) {
1401 // Find the associated namespace for this base class.
1402 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1403 while (BaseCtx->isRecord())
1404 BaseCtx = BaseCtx->getParent();
John McCallb41b2052009-08-07 22:18:02 +00001405 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001406
1407 // Make sure we visit the bases of this base class.
1408 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1409 Bases.push_back(BaseDecl);
1410 }
1411 }
1412 }
1413}
1414
1415// \brief Add the associated classes and namespaces for
1416// argument-dependent lookup with an argument of type T
1417// (C++ [basic.lookup.koenig]p2).
1418static void
1419addAssociatedClassesAndNamespaces(QualType T,
1420 ASTContext &Context,
1421 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallb41b2052009-08-07 22:18:02 +00001422 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001423 // C++ [basic.lookup.koenig]p2:
1424 //
1425 // For each argument type T in the function call, there is a set
1426 // of zero or more associated namespaces and a set of zero or more
1427 // associated classes to be considered. The sets of namespaces and
1428 // classes is determined entirely by the types of the function
1429 // arguments (and the namespace of any template template
1430 // argument). Typedef names and using-declarations used to specify
1431 // the types do not contribute to this set. The sets of namespaces
1432 // and classes are determined in the following way:
1433 T = Context.getCanonicalType(T).getUnqualifiedType();
1434
1435 // -- If T is a pointer to U or an array of U, its associated
1436 // namespaces and classes are those associated with U.
1437 //
1438 // We handle this by unwrapping pointer and array types immediately,
1439 // to avoid unnecessary recursion.
1440 while (true) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001441 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001442 T = Ptr->getPointeeType();
1443 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1444 T = Ptr->getElementType();
1445 else
1446 break;
1447 }
1448
1449 // -- If T is a fundamental type, its associated sets of
1450 // namespaces and classes are both empty.
1451 if (T->getAsBuiltinType())
1452 return;
1453
1454 // -- If T is a class type (including unions), its associated
1455 // classes are: the class itself; the class of which it is a
1456 // member, if any; and its direct and indirect base
1457 // classes. Its associated namespaces are the namespaces in
1458 // which its associated classes are defined.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001459 if (const RecordType *ClassType = T->getAs<RecordType>())
Douglas Gregor2e047592009-02-28 01:32:25 +00001460 if (CXXRecordDecl *ClassDecl
1461 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1462 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1463 AssociatedNamespaces,
John McCallb41b2052009-08-07 22:18:02 +00001464 AssociatedClasses);
Douglas Gregor2e047592009-02-28 01:32:25 +00001465 return;
1466 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001467
1468 // -- If T is an enumeration type, its associated namespace is
1469 // the namespace in which it is defined. If it is class
1470 // member, its associated class is the member’s class; else
1471 // it has no associated class.
1472 if (const EnumType *EnumT = T->getAsEnumType()) {
1473 EnumDecl *Enum = EnumT->getDecl();
1474
1475 DeclContext *Ctx = Enum->getDeclContext();
1476 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1477 AssociatedClasses.insert(EnclosingClass);
1478
1479 // Add the associated namespace for this class.
1480 while (Ctx->isRecord())
1481 Ctx = Ctx->getParent();
John McCallb41b2052009-08-07 22:18:02 +00001482 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001483
1484 return;
1485 }
1486
1487 // -- If T is a function type, its associated namespaces and
1488 // classes are those associated with the function parameter
1489 // types and those associated with the return type.
1490 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1491 // Return type
1492 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1493 Context,
John McCallb41b2052009-08-07 22:18:02 +00001494 AssociatedNamespaces, AssociatedClasses);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001495
Douglas Gregor4fa58902009-02-26 23:50:07 +00001496 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001497 if (!Proto)
1498 return;
1499
1500 // Argument types
Douglas Gregor4fa58902009-02-26 23:50:07 +00001501 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001502 ArgEnd = Proto->arg_type_end();
1503 Arg != ArgEnd; ++Arg)
1504 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallb41b2052009-08-07 22:18:02 +00001505 AssociatedNamespaces, AssociatedClasses);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001506
1507 return;
1508 }
1509
1510 // -- If T is a pointer to a member function of a class X, its
1511 // associated namespaces and classes are those associated
1512 // with the function parameter types and return type,
1513 // together with those associated with X.
1514 //
1515 // -- If T is a pointer to a data member of class X, its
1516 // associated namespaces and classes are those associated
1517 // with the member type together with those associated with
1518 // X.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001519 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001520 // Handle the type that the pointer to member points to.
1521 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1522 Context,
John McCallb41b2052009-08-07 22:18:02 +00001523 AssociatedNamespaces,
1524 AssociatedClasses);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001525
1526 // Handle the class type into which this points.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001527 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001528 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1529 Context,
John McCallb41b2052009-08-07 22:18:02 +00001530 AssociatedNamespaces,
1531 AssociatedClasses);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001532
1533 return;
1534 }
1535
1536 // FIXME: What about block pointers?
1537 // FIXME: What about Objective-C message sends?
1538}
1539
1540/// \brief Find the associated classes and namespaces for
1541/// argument-dependent lookup for a call with the given set of
1542/// arguments.
1543///
1544/// This routine computes the sets of associated classes and associated
1545/// namespaces searched by argument-dependent lookup
1546/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1547void
1548Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1549 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallb41b2052009-08-07 22:18:02 +00001550 AssociatedClassSet &AssociatedClasses) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001551 AssociatedNamespaces.clear();
1552 AssociatedClasses.clear();
1553
1554 // C++ [basic.lookup.koenig]p2:
1555 // For each argument type T in the function call, there is a set
1556 // of zero or more associated namespaces and a set of zero or more
1557 // associated classes to be considered. The sets of namespaces and
1558 // classes is determined entirely by the types of the function
1559 // arguments (and the namespace of any template template
1560 // argument).
1561 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1562 Expr *Arg = Args[ArgIdx];
1563
1564 if (Arg->getType() != Context.OverloadTy) {
1565 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallb41b2052009-08-07 22:18:02 +00001566 AssociatedNamespaces,
1567 AssociatedClasses);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001568 continue;
1569 }
1570
1571 // [...] In addition, if the argument is the name or address of a
1572 // set of overloaded functions and/or function templates, its
1573 // associated classes and namespaces are the union of those
1574 // associated with each of the members of the set: the namespace
1575 // in which the function or function template is defined and the
1576 // classes and namespaces associated with its (non-dependent)
1577 // parameter types and return type.
1578 DeclRefExpr *DRE = 0;
Douglas Gregor6e264102009-07-08 10:57:20 +00001579 TemplateIdRefExpr *TIRE = 0;
1580 Arg = Arg->IgnoreParens();
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001581 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor6e264102009-07-08 10:57:20 +00001582 if (unaryOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001583 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
Douglas Gregor6e264102009-07-08 10:57:20 +00001584 TIRE = dyn_cast<TemplateIdRefExpr>(unaryOp->getSubExpr());
1585 }
1586 } else {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001587 DRE = dyn_cast<DeclRefExpr>(Arg);
Douglas Gregor6e264102009-07-08 10:57:20 +00001588 TIRE = dyn_cast<TemplateIdRefExpr>(Arg);
1589 }
1590
1591 OverloadedFunctionDecl *Ovl = 0;
1592 if (DRE)
1593 Ovl = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1594 else if (TIRE)
Douglas Gregor6631cb42009-07-29 18:26:50 +00001595 Ovl = TIRE->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001596 if (!Ovl)
1597 continue;
1598
1599 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1600 FuncEnd = Ovl->function_end();
1601 Func != FuncEnd; ++Func) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00001602 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func);
1603 if (!FDecl)
1604 FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl();
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001605
1606 // Add the namespace in which this function was defined. Note
1607 // that, if this is a member function, we do *not* consider the
1608 // enclosing namespace of its class.
1609 DeclContext *Ctx = FDecl->getDeclContext();
John McCallb41b2052009-08-07 22:18:02 +00001610 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001611
1612 // Add the classes and namespaces associated with the parameter
1613 // types and return type of this function.
1614 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallb41b2052009-08-07 22:18:02 +00001615 AssociatedNamespaces,
1616 AssociatedClasses);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001617 }
1618 }
1619}
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001620
1621/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1622/// an acceptable non-member overloaded operator for a call whose
1623/// arguments have types T1 (and, if non-empty, T2). This routine
1624/// implements the check in C++ [over.match.oper]p3b2 concerning
1625/// enumeration types.
1626static bool
1627IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1628 QualType T1, QualType T2,
1629 ASTContext &Context) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001630 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1631 return true;
1632
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001633 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1634 return true;
1635
1636 const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1637 if (Proto->getNumArgs() < 1)
1638 return false;
1639
1640 if (T1->isEnumeralType()) {
1641 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1642 if (Context.getCanonicalType(T1).getUnqualifiedType()
1643 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1644 return true;
1645 }
1646
1647 if (Proto->getNumArgs() < 2)
1648 return false;
1649
1650 if (!T2.isNull() && T2->isEnumeralType()) {
1651 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1652 if (Context.getCanonicalType(T2).getUnqualifiedType()
1653 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1654 return true;
1655 }
1656
1657 return false;
1658}
1659
Douglas Gregore57c8cc2009-04-23 23:18:26 +00001660/// \brief Find the protocol with the given name, if any.
1661ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
Douglas Gregorafd5eb32009-04-24 00:11:27 +00001662 Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl();
Douglas Gregore57c8cc2009-04-23 23:18:26 +00001663 return cast_or_null<ObjCProtocolDecl>(D);
1664}
1665
Douglas Gregorafd5eb32009-04-24 00:11:27 +00001666/// \brief Find the Objective-C category implementation with the given
1667/// name, if any.
1668ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
1669 Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl();
1670 return cast_or_null<ObjCCategoryImplDecl>(D);
1671}
1672
John McCall140607b2009-08-06 02:15:43 +00001673// Attempts to find a declaration in the given declaration context
1674// with exactly the given type. Returns null if no such declaration
1675// was found.
1676Decl *Sema::LookupQualifiedNameWithType(DeclContext *DC,
1677 DeclarationName Name,
1678 QualType T) {
1679 LookupResult result =
1680 LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
1681
1682 CanQualType CQT = Context.getCanonicalType(T);
1683
1684 for (LookupResult::iterator ir = result.begin(), ie = result.end();
1685 ir != ie; ++ir)
1686 if (FunctionDecl *CurFD = dyn_cast<FunctionDecl>(*ir))
1687 if (Context.getCanonicalType(CurFD->getType()) == CQT)
1688 return CurFD;
1689
1690 return NULL;
1691}
1692
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001693void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1694 QualType T1, QualType T2,
1695 FunctionSet &Functions) {
1696 // C++ [over.match.oper]p3:
1697 // -- The set of non-member candidates is the result of the
1698 // unqualified lookup of operator@ in the context of the
1699 // expression according to the usual rules for name lookup in
1700 // unqualified function calls (3.4.2) except that all member
1701 // functions are ignored. However, if no operand has a class
1702 // type, only those non-member functions in the lookup set
Eli Friedmand5a72f02009-08-05 19:21:58 +00001703 // that have a first parameter of type T1 or "reference to
1704 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001705 // type, or (if there is a right operand) a second parameter
Eli Friedmand5a72f02009-08-05 19:21:58 +00001706 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001707 // when T2 is an enumeration type, are candidate functions.
1708 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1709 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1710
1711 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1712
1713 if (!Operators)
1714 return;
1715
1716 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1717 Op != OpEnd; ++Op) {
Douglas Gregor993a0602009-06-27 21:05:07 +00001718 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001719 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1720 Functions.insert(FD); // FIXME: canonical FD
Douglas Gregor993a0602009-06-27 21:05:07 +00001721 } else if (FunctionTemplateDecl *FunTmpl
1722 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1723 // FIXME: friend operators?
1724 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
1725 // later?
1726 if (!FunTmpl->getDeclContext()->isRecord())
1727 Functions.insert(FunTmpl);
1728 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001729 }
1730}
1731
John McCallb41b2052009-08-07 22:18:02 +00001732static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1733 Decl *D) {
1734 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1735 Functions.insert(Func);
1736 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1737 Functions.insert(FunTmpl);
1738}
1739
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001740void Sema::ArgumentDependentLookup(DeclarationName Name,
1741 Expr **Args, unsigned NumArgs,
1742 FunctionSet &Functions) {
1743 // Find all of the associated namespaces and classes based on the
1744 // arguments we have.
1745 AssociatedNamespaceSet AssociatedNamespaces;
1746 AssociatedClassSet AssociatedClasses;
1747 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallb41b2052009-08-07 22:18:02 +00001748 AssociatedNamespaces,
1749 AssociatedClasses);
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001750
1751 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001752 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1753 // and let Y be the lookup set produced by argument dependent
1754 // lookup (defined as follows). If X contains [...] then Y is
1755 // empty. Otherwise Y is the set of declarations found in the
1756 // namespaces associated with the argument types as described
1757 // below. The set of declarations found by the lookup of the name
1758 // is the union of X and Y.
1759 //
1760 // Here, we compute Y and add its members to the overloaded
1761 // candidate set.
1762 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1763 NSEnd = AssociatedNamespaces.end();
1764 NS != NSEnd; ++NS) {
1765 // When considering an associated namespace, the lookup is the
1766 // same as the lookup performed when the associated namespace is
1767 // used as a qualifier (3.4.3.2) except that:
1768 //
1769 // -- Any using-directives in the associated namespace are
1770 // ignored.
1771 //
John McCallb41b2052009-08-07 22:18:02 +00001772 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001773 // associated classes are visible within their respective
1774 // namespaces even if they are not visible during an ordinary
1775 // lookup (11.4).
1776 DeclContext::lookup_iterator I, E;
John McCall36493082009-08-11 06:59:38 +00001777 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCallb41b2052009-08-07 22:18:02 +00001778 Decl *D = *I;
John McCall7de15912009-08-28 07:59:38 +00001779 // If the only declaration here is an ordinary friend, consider
1780 // it only if it was declared in an associated classes.
1781 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall36493082009-08-11 06:59:38 +00001782 DeclContext *LexDC = D->getLexicalDeclContext();
1783 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1784 continue;
1785 }
1786
John McCallb41b2052009-08-07 22:18:02 +00001787 CollectFunctionDecl(Functions, D);
Douglas Gregor6123ae62009-06-23 20:14:09 +00001788 }
1789 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00001790}