blob: 67674206fb82e3291769042fa085d1bd0ca38ef0 [file] [log] [blame]
Douglas Gregor34074322009-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 Gregor960b5bc2009-01-15 00:26:24 +000015#include "SemaInherit.h"
16#include "clang/AST/ASTContext.h"
Douglas Gregor34074322009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
Douglas Gregorc9f9b862009-05-11 19:58:34 +000020#include "clang/AST/DeclTemplate.h"
Douglas Gregore254f902009-02-04 00:32:51 +000021#include "clang/AST/Expr.h"
Douglas Gregorbe759252009-07-08 10:57:20 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor34074322009-01-14 22:20:51 +000023#include "clang/Parse/DeclSpec.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregor34074322009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
26#include "llvm/ADT/STLExtras.h"
Douglas Gregore254f902009-02-04 00:32:51 +000027#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor1c846b02009-01-16 00:38:09 +000028#include <set>
Douglas Gregor889ceb72009-02-03 19:21:40 +000029#include <vector>
30#include <iterator>
31#include <utility>
32#include <algorithm>
Douglas Gregor34074322009-01-14 22:20:51 +000033
34using namespace clang;
35
Douglas Gregor889ceb72009-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.
Mike Stump11289f42009-09-09 15:08:12 +000063void AddNamespaceUsingDirectives(ASTContext &Context,
Douglas Gregorbcced4e2009-04-09 21:40:53 +000064 DeclContext *NS,
Douglas Gregor889ceb72009-02-03 19:21:40 +000065 UsingDirectivesTy &UDirs,
66 NamespaceSet &Visited) {
67 DeclContext::udir_iterator I, End;
68
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000069 for (llvm::tie(I, End) = NS->getUsingDirectives(); I !=End; ++I) {
Douglas Gregor889ceb72009-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 Gregorbcced4e2009-04-09 21:40:53 +000074 AddNamespaceUsingDirectives(Context, Nominated, UDirs, /*ref*/ Visited);
Douglas Gregor889ceb72009-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.
Mike Stump11289f42009-09-09 15:08:12 +000080static void AddScopeUsingDirectives(ASTContext &Context, Scope *S,
Douglas Gregorbcced4e2009-04-09 21:40:53 +000081 UsingDirectivesTy &UDirs) {
Douglas Gregor889ceb72009-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 Gregorbcced4e2009-04-09 21:40:53 +000089 AddNamespaceUsingDirectives(Context, Ctx, UDirs, /*ref*/ VisitedNS);
Douglas Gregor889ceb72009-02-03 19:21:40 +000090
91 } else {
Chris Lattner83f095c2009-03-28 19:18:32 +000092 Scope::udir_iterator I = S->using_directives_begin(),
93 End = S->using_directives_end();
Douglas Gregor889ceb72009-02-03 19:21:40 +000094
95 for (; I != End; ++I) {
Chris Lattner83f095c2009-03-28 19:18:32 +000096 UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>();
Douglas Gregor889ceb72009-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);
Mike Stump11289f42009-09-09 15:08:12 +0000103 AddNamespaceUsingDirectives(Context, Nominated, UDirs,
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000104 /*ref*/ VisitedNS);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000105 }
106 }
107 }
108}
109
Douglas Gregor34074322009-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 Gregor889ceb72009-02-03 19:21:40 +0000114/// OverloadedFunctionDecl that represents the overloaded functions in
Mike Stump11289f42009-09-09 15:08:12 +0000115/// [I, IEnd).
Douglas Gregor34074322009-01-14 22:20:51 +0000116///
Douglas Gregored8f2882009-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 Gregor34074322009-01-14 22:20:51 +0000119/// ambiguity and overloaded functions without needing to create a
120/// Decl node.
121template<typename DeclIterator>
Douglas Gregor2ada0482009-02-04 17:27:36 +0000122static NamedDecl *
Mike Stump11289f42009-09-09 15:08:12 +0000123MaybeConstructOverloadSet(ASTContext &Context,
Douglas Gregor34074322009-01-14 22:20:51 +0000124 DeclIterator I, DeclIterator IEnd) {
125 assert(I != IEnd && "Iterator range cannot be empty");
Mike Stump11289f42009-09-09 15:08:12 +0000126 assert(!isa<OverloadedFunctionDecl>(*I) &&
Douglas Gregor34074322009-01-14 22:20:51 +0000127 "Cannot have an overloaded function");
128
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000129 if ((*I)->isFunctionOrFunctionTemplate()) {
Douglas Gregor34074322009-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;
Mike Stump11289f42009-09-09 15:08:12 +0000134 for (++Last;
135 Last != IEnd && (*Last)->isFunctionOrFunctionTemplate();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000136 ++Last) {
Douglas Gregor34074322009-01-14 22:20:51 +0000137 if (!Ovl) {
Mike Stump87c57ac2009-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 Gregor6e6ad602009-01-20 01:17:11 +0000141 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
Douglas Gregor34074322009-01-14 22:20:51 +0000142 (*I)->getDeclName());
Anders Carlsson6915bf62009-06-26 06:29:23 +0000143 NamedDecl *ND = (*I)->getUnderlyingDecl();
Anders Carlssonf057cb22009-06-26 05:26:50 +0000144 if (isa<FunctionDecl>(ND))
145 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000146 else
Anders Carlssonf057cb22009-06-26 05:26:50 +0000147 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
Douglas Gregor34074322009-01-14 22:20:51 +0000148 }
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000149
Anders Carlsson6915bf62009-06-26 06:29:23 +0000150 NamedDecl *ND = (*Last)->getUnderlyingDecl();
Anders Carlssonf057cb22009-06-26 05:26:50 +0000151 if (isa<FunctionDecl>(ND))
152 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000153 else
Anders Carlssonf057cb22009-06-26 05:26:50 +0000154 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
Douglas Gregor34074322009-01-14 22:20:51 +0000155 }
Mike Stump11289f42009-09-09 15:08:12 +0000156
Douglas Gregor34074322009-01-14 22:20:51 +0000157 // If we had more than one function, we built an overload
158 // set. Return it.
159 if (Ovl)
160 return Ovl;
161 }
Mike Stump11289f42009-09-09 15:08:12 +0000162
Douglas Gregor34074322009-01-14 22:20:51 +0000163 return *I;
164}
165
Douglas Gregor889ceb72009-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 Gregor2ada0482009-02-04 17:27:36 +0000170 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000171
Douglas Gregor700792c2009-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 Gregor889ceb72009-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 Gregor700792c2009-02-05 19:25:20 +0000188 DeclsSetTy FoundDecls;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000189
Douglas Gregor700792c2009-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 Gregor2ada0482009-02-04 17:27:36 +0000193
Douglas Gregor700792c2009-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 Carlsson6915bf62009-06-26 06:29:23 +0000217 NamedDecl *ND = I->getAsDecl()->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000218
Douglas Gregor700792c2009-02-05 19:25:20 +0000219 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +0000220 TagFound = TD->getCanonicalDecl();
Douglas Gregor700792c2009-02-05 19:25:20 +0000221 TagNames += FoundDecls.insert(TagFound)? 1 : 0;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000222 } else if (ND->isFunctionOrFunctionTemplate())
Douglas Gregor700792c2009-02-05 19:25:20 +0000223 Functions += FoundDecls.insert(ND)? 1 : 0;
224 else
225 FoundDecls.insert(ND);
226 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000227 }
228
Douglas Gregor700792c2009-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 Gregor889ceb72009-02-03 19:21:40 +0000233 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000234 }
235 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
236 bool Ambiguous = false, NameHidesTags = false;
Mike Stump11289f42009-09-09 15:08:12 +0000237
Douglas Gregor700792c2009-02-05 19:25:20 +0000238 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 Gregor2ada0482009-02-04 17:27:36 +0000248 // C++ [basic.lookup].p1:
249 // ... Name lookup may associate more than one declaration with
Douglas Gregor889ceb72009-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 Gregor2ada0482009-02-04 17:27:36 +0000253 //
Douglas Gregor700792c2009-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 Gregor889ceb72009-02-03 19:21:40 +0000264 }
265
Douglas Gregor700792c2009-02-05 19:25:20 +0000266 if (Ambiguous)
Mike Stump11289f42009-09-09 15:08:12 +0000267 return LResult::CreateLookupResult(Context,
Douglas Gregor700792c2009-02-05 19:25:20 +0000268 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 Gregor889ceb72009-02-03 19:21:40 +0000280}
281
282// Retrieve the set of identifier namespaces that correspond to a
283// specific kind of name lookup.
Mike Stump11289f42009-09-09 15:08:12 +0000284inline unsigned
285getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
Douglas Gregor889ceb72009-02-03 19:21:40 +0000286 bool CPlusPlus) {
287 unsigned IDNS = 0;
288 switch (NameKind) {
289 case Sema::LookupOrdinaryName:
Douglas Gregor94eabf32009-02-04 16:44:47 +0000290 case Sema::LookupOperatorName:
Douglas Gregoreddf4332009-02-24 20:03:32 +0000291 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor889ceb72009-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)
Mike Stump11289f42009-09-09 15:08:12 +0000304 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000305 break;
306
307 case Sema::LookupNestedNameSpecifierName:
308 case Sema::LookupNamespaceName:
309 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
310 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000311
Douglas Gregor79947a22009-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 Gregorde9f17e2009-04-23 23:18:26 +0000322 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000323 }
324 return IDNS;
325}
326
Douglas Gregor889ceb72009-02-03 19:21:40 +0000327Sema::LookupResult
Douglas Gregor2ada0482009-02-04 17:27:36 +0000328Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Anders Carlsson6915bf62009-06-26 06:29:23 +0000329 if (D)
330 D = D->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000331
Douglas Gregor889ceb72009-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 Gregor41c8ba82009-01-15 02:19:31 +0000341/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregorf23311d2009-01-17 01:13:24 +0000342Sema::LookupResult
Mike Stump11289f42009-09-09 15:08:12 +0000343Sema::LookupResult::CreateLookupResult(ASTContext &Context,
344 IdentifierResolver::iterator F,
Douglas Gregorf23311d2009-01-17 01:13:24 +0000345 IdentifierResolver::iterator L) {
346 LookupResult Result;
347 Result.Context = &Context;
348
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000349 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000350 IdentifierResolver::iterator Next = F;
351 ++Next;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000352 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregorf23311d2009-01-17 01:13:24 +0000353 Result.StoredKind = OverloadedDeclFromIdResolver;
354 Result.First = F.getAsOpaqueValue();
355 Result.Last = L.getAsOpaqueValue();
356 return Result;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000357 }
Mike Stump11289f42009-09-09 15:08:12 +0000358 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000359
Anders Carlsson6915bf62009-06-26 06:29:23 +0000360 NamedDecl *D = *F;
361 if (D)
362 D = D->getUnderlyingDecl();
Anders Carlsson8d0f6b72009-06-26 03:37:05 +0000363
Douglas Gregorf23311d2009-01-17 01:13:24 +0000364 Result.StoredKind = SingleDecl;
Douglas Gregor38feed82009-04-24 02:57:34 +0000365 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregorf23311d2009-01-17 01:13:24 +0000366 Result.Last = 0;
367 return Result;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000368}
369
Douglas Gregorf23311d2009-01-17 01:13:24 +0000370Sema::LookupResult
Mike Stump11289f42009-09-09 15:08:12 +0000371Sema::LookupResult::CreateLookupResult(ASTContext &Context,
372 DeclContext::lookup_iterator F,
Douglas Gregorf23311d2009-01-17 01:13:24 +0000373 DeclContext::lookup_iterator L) {
374 LookupResult Result;
375 Result.Context = &Context;
376
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000377 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000378 DeclContext::lookup_iterator Next = F;
379 ++Next;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000380 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregorf23311d2009-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 Gregor960b5bc2009-01-15 00:26:24 +0000385 }
386 }
Douglas Gregor38feed82009-04-24 02:57:34 +0000387
Anders Carlsson6915bf62009-06-26 06:29:23 +0000388 NamedDecl *D = *F;
389 if (D)
390 D = D->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000391
Douglas Gregorf23311d2009-01-17 01:13:24 +0000392 Result.StoredKind = SingleDecl;
Douglas Gregor38feed82009-04-24 02:57:34 +0000393 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregorf23311d2009-01-17 01:13:24 +0000394 Result.Last = 0;
395 return Result;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000396}
397
Douglas Gregor34074322009-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 Gregor889ceb72009-02-03 19:21:40 +0000404 case OverloadedDeclSingleDecl:
Douglas Gregor34074322009-01-14 22:20:51 +0000405 case OverloadedDeclFromIdResolver:
406 case OverloadedDeclFromDeclContext:
407 return FoundOverloaded;
408
Douglas Gregor889ceb72009-02-03 19:21:40 +0000409 case AmbiguousLookupStoresBasePaths:
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000410 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000411
412 case AmbiguousLookupStoresDecls:
413 return AmbiguousReference;
Douglas Gregor34074322009-01-14 22:20:51 +0000414 }
415
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000416 // We can't ever get here.
417 return NotFound;
Douglas Gregor34074322009-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
Mike Stump11289f42009-09-09 15:08:12 +0000427/// used anywhere where name lookup could result in an ambiguity.
Douglas Gregor34074322009-01-14 22:20:51 +0000428///
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 Gregor2ada0482009-02-04 17:27:36 +0000433NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregor34074322009-01-14 22:20:51 +0000434 switch (StoredKind) {
435 case SingleDecl:
Douglas Gregor2ada0482009-02-04 17:27:36 +0000436 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregor34074322009-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:
Mike Stump11289f42009-09-09 15:08:12 +0000444 return MaybeConstructOverloadSet(*Context,
Douglas Gregor34074322009-01-14 22:20:51 +0000445 reinterpret_cast<DeclContext::lookup_iterator>(First),
446 reinterpret_cast<DeclContext::lookup_iterator>(Last));
447
Douglas Gregor889ceb72009-02-03 19:21:40 +0000448 case OverloadedDeclSingleDecl:
449 return reinterpret_cast<OverloadedFunctionDecl*>(First);
450
451 case AmbiguousLookupStoresDecls:
452 case AmbiguousLookupStoresBasePaths:
Mike Stump11289f42009-09-09 15:08:12 +0000453 assert(false &&
Douglas Gregor34074322009-01-14 22:20:51 +0000454 "Name lookup returned an ambiguity that could not be handled");
455 break;
456 }
457
458 return 0;
459}
460
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000461/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor889ceb72009-02-03 19:21:40 +0000462/// name lookup, or null.
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000463BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000464 if (StoredKind == AmbiguousLookupStoresBasePaths)
465 return reinterpret_cast<BasePaths *>(First);
466 return 0;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000467}
468
Mike Stump11289f42009-09-09 15:08:12 +0000469Sema::LookupResult::iterator::reference
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000470Sema::LookupResult::iterator::operator*() const {
471 switch (Result->StoredKind) {
472 case SingleDecl:
Douglas Gregor2ada0482009-02-04 17:27:36 +0000473 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000474
Douglas Gregor889ceb72009-02-03 19:21:40 +0000475 case OverloadedDeclSingleDecl:
Douglas Gregor2ada0482009-02-04 17:27:36 +0000476 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000477
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000478 case OverloadedDeclFromIdResolver:
479 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
480
Douglas Gregor889ceb72009-02-03 19:21:40 +0000481 case AmbiguousLookupStoresBasePaths:
Douglas Gregorfe3d7d02009-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 Gregor0e8fc3c2009-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 Gregor2ada0482009-02-04 17:27:36 +0000499 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000500 break;
501
Douglas Gregor889ceb72009-02-03 19:21:40 +0000502 case OverloadedDeclSingleDecl: {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000503 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000504 ++I;
505 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregor94eabf32009-02-04 16:44:47 +0000506 break;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000507 }
508
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000509 case OverloadedDeclFromIdResolver: {
Mike Stump11289f42009-09-09 15:08:12 +0000510 IdentifierResolver::iterator I
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000511 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
512 ++I;
513 Current = I.getAsOpaqueValue();
514 break;
515 }
516
Mike Stump11289f42009-09-09 15:08:12 +0000517 case AmbiguousLookupStoresBasePaths:
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000518 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: {
Mike Stump11289f42009-09-09 15:08:12 +0000529 DeclContext::lookup_iterator I
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000530 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
531 ++I;
532 Current = reinterpret_cast<uintptr_t>(I);
533 break;
534 }
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +0000535 }
536
537 return *this;
538}
539
540Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000541 switch (StoredKind) {
542 case SingleDecl:
543 case OverloadedDeclFromIdResolver:
544 case OverloadedDeclFromDeclContext:
545 case AmbiguousLookupStoresDecls:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000546 return iterator(this, First);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000547
548 case OverloadedDeclSingleDecl: {
549 OverloadedFunctionDecl * Ovl =
550 reinterpret_cast<OverloadedFunctionDecl*>(First);
Mike Stump11289f42009-09-09 15:08:12 +0000551 return iterator(this,
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000552 reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
553 }
554
555 case AmbiguousLookupStoresBasePaths:
556 if (Last)
Mike Stump11289f42009-09-09 15:08:12 +0000557 return iterator(this,
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000558 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 Gregor0e8fc3c2009-02-02 21:35:47 +0000566}
567
568Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000569 switch (StoredKind) {
570 case SingleDecl:
571 case OverloadedDeclFromIdResolver:
572 case OverloadedDeclFromDeclContext:
573 case AmbiguousLookupStoresDecls:
Douglas Gregor889ceb72009-02-03 19:21:40 +0000574 return iterator(this, Last);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000575
576 case OverloadedDeclSingleDecl: {
577 OverloadedFunctionDecl * Ovl =
578 reinterpret_cast<OverloadedFunctionDecl*>(First);
Mike Stump11289f42009-09-09 15:08:12 +0000579 return iterator(this,
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000580 reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
581 }
582
583 case AmbiguousLookupStoresBasePaths:
584 if (Last)
Mike Stump11289f42009-09-09 15:08:12 +0000585 return iterator(this,
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000586 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 Gregor0e8fc3c2009-02-02 21:35:47 +0000601}
602
Douglas Gregor700792c2009-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;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000613 for (llvm::tie(I, E) = NS->lookup(Name); I != E; ++I)
Douglas Gregor700792c2009-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());
Mike Stump11289f42009-09-09 15:08:12 +0000626
Douglas Gregor700792c2009-02-05 19:25:20 +0000627 for (; UI != UEnd; ++UI)
628 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
629 Name, NameKind, IDNS, Results);
630 }
631}
632
633static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000634 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor700792c2009-02-05 19:25:20 +0000635 return Ctx->isFileContext();
636 return false;
Douglas Gregor889ceb72009-02-03 19:21:40 +0000637}
Douglas Gregored8f2882009-01-30 01:04:22 +0000638
Douglas Gregor7f737c02009-09-10 16:57:35 +0000639// Find the next outer declaration context corresponding to this scope.
640static DeclContext *findOuterContext(Scope *S) {
641 for (S = S->getParent(); S; S = S->getParent())
642 if (S->getEntity())
643 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
644
645 return 0;
646}
647
Douglas Gregor889ceb72009-02-03 19:21:40 +0000648std::pair<bool, Sema::LookupResult>
649Sema::CppLookupName(Scope *S, DeclarationName Name,
650 LookupNameKind NameKind, bool RedeclarationOnly) {
651 assert(getLangOptions().CPlusPlus &&
652 "Can perform only C++ lookup");
Mike Stump11289f42009-09-09 15:08:12 +0000653 unsigned IDNS
Douglas Gregor2ada0482009-02-04 17:27:36 +0000654 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
John McCallaa74a0c2009-08-28 07:59:38 +0000655
656 // If we're testing for redeclarations, also look in the friend namespaces.
657 if (RedeclarationOnly) {
658 if (IDNS & Decl::IDNS_Tag) IDNS |= Decl::IDNS_TagFriend;
659 if (IDNS & Decl::IDNS_Ordinary) IDNS |= Decl::IDNS_OrdinaryFriend;
660 }
661
Douglas Gregor889ceb72009-02-03 19:21:40 +0000662 Scope *Initial = S;
Douglas Gregor700792c2009-02-05 19:25:20 +0000663 DeclContext *OutOfLineCtx = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000664 IdentifierResolver::iterator
Douglas Gregor889ceb72009-02-03 19:21:40 +0000665 I = IdResolver.begin(Name),
666 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000667
Douglas Gregor889ceb72009-02-03 19:21:40 +0000668 // First we lookup local scope.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000669 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor889ceb72009-02-03 19:21:40 +0000670 // ...During unqualified name lookup (3.4.1), the names appear as if
671 // they were declared in the nearest enclosing namespace which contains
672 // both the using-directive and the nominated namespace.
Eli Friedman44b83ee2009-08-05 19:21:58 +0000673 // [Note: in this context, "contains" means "contains directly or
Mike Stump11289f42009-09-09 15:08:12 +0000674 // indirectly".
Douglas Gregor889ceb72009-02-03 19:21:40 +0000675 //
676 // For example:
677 // namespace A { int i; }
678 // void foo() {
679 // int i;
680 // {
681 // using namespace A;
682 // ++i; // finds local 'i', A::i appears at global scope
683 // }
684 // }
Douglas Gregor2ada0482009-02-04 17:27:36 +0000685 //
Douglas Gregor700792c2009-02-05 19:25:20 +0000686 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000687 // Check whether the IdResolver has anything in this scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000688 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000689 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
690 // We found something. Look for anything else in our scope
691 // with this same name and in an acceptable identifier
692 // namespace, so that we can construct an overload set if we
693 // need to.
694 IdentifierResolver::iterator LastI = I;
695 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000696 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor889ceb72009-02-03 19:21:40 +0000697 break;
698 }
699 LookupResult Result =
700 LookupResult::CreateLookupResult(Context, I, LastI);
701 return std::make_pair(true, Result);
702 }
703 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000704 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
705 LookupResult R;
Douglas Gregor7f737c02009-09-10 16:57:35 +0000706
707 DeclContext *OuterCtx = findOuterContext(S);
708 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
709 Ctx = Ctx->getLookupParent()) {
710 if (Ctx->isFunctionOrMethod())
711 continue;
712
713 // Perform qualified name lookup into this context.
714 // FIXME: In some cases, we know that every name that could be found by
715 // this qualified name lookup will also be on the identifier chain. For
716 // example, inside a class without any base classes, we never need to
717 // perform qualified lookup because all of the members are on top of the
718 // identifier chain.
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000719 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
Douglas Gregorf187420f2009-06-17 23:37:01 +0000720 if (R)
Douglas Gregorfdca4a72009-03-27 04:21:56 +0000721 return std::make_pair(true, R);
722 }
Douglas Gregor700792c2009-02-05 19:25:20 +0000723 }
Douglas Gregored8f2882009-01-30 01:04:22 +0000724 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000725
Douglas Gregor700792c2009-02-05 19:25:20 +0000726 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor889ceb72009-02-03 19:21:40 +0000727 // nominated namespaces by those using-directives.
Mike Stump87c57ac2009-05-16 07:39:55 +0000728 // UsingDirectives are pushed to heap, in common ancestor pointer value order.
729 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
730 // don't build it for each lookup!
Douglas Gregor889ceb72009-02-03 19:21:40 +0000731 UsingDirectivesTy UDirs;
732 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor2ada0482009-02-04 17:27:36 +0000733 if (SC->getFlags() & Scope::DeclScope)
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000734 AddScopeUsingDirectives(Context, SC, UDirs);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000735
736 // Sort heapified UsingDirectiveDecls.
Douglas Gregor4182e3212009-05-18 22:06:54 +0000737 std::sort_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000738
Douglas Gregor700792c2009-02-05 19:25:20 +0000739 // Lookup namespace scope, and global scope.
Douglas Gregor889ceb72009-02-03 19:21:40 +0000740 // Unqualified name lookup in C++ requires looking into scopes
741 // that aren't strictly lexical, and therefore we walk through the
742 // context as well as walking through the scopes.
Douglas Gregor700792c2009-02-05 19:25:20 +0000743
744 LookupResultsTy LookupResults;
Sebastian Redl112a97662009-02-07 00:15:38 +0000745 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregor700792c2009-02-05 19:25:20 +0000746 "We should have been looking only at file context here already.");
747 bool LookedInCtx = false;
748 LookupResult Result;
749 while (OutOfLineCtx &&
750 OutOfLineCtx != S->getEntity() &&
751 OutOfLineCtx->isNamespace()) {
752 LookedInCtx = true;
753
754 // Look into context considering using-directives.
755 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
756 LookupResults, &UDirs);
757
758 if ((Result = MergeLookupResults(Context, LookupResults)) ||
759 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
760 return std::make_pair(true, Result);
761
762 OutOfLineCtx = OutOfLineCtx->getParent();
763 }
764
Douglas Gregor889ceb72009-02-03 19:21:40 +0000765 for (; S; S = S->getParent()) {
Douglas Gregor700792c2009-02-05 19:25:20 +0000766 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregorf2270432009-08-24 18:55:03 +0000767 if (Ctx->isTransparentContext())
768 continue;
769
Douglas Gregor700792c2009-02-05 19:25:20 +0000770 assert(Ctx && Ctx->isFileContext() &&
771 "We should have been looking only at file context here already.");
Douglas Gregor889ceb72009-02-03 19:21:40 +0000772
773 // Check whether the IdResolver has anything in this scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000774 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000775 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
776 // We found something. Look for anything else in our scope
777 // with this same name and in an acceptable identifier
778 // namespace, so that we can construct an overload set if we
779 // need to.
780 IdentifierResolver::iterator LastI = I;
781 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000782 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor889ceb72009-02-03 19:21:40 +0000783 break;
784 }
Mike Stump11289f42009-09-09 15:08:12 +0000785
Douglas Gregor889ceb72009-02-03 19:21:40 +0000786 // We store name lookup result, and continue trying to look into
787 // associated context, and maybe namespaces nominated by
788 // using-directives.
789 LookupResults.push_back(
790 LookupResult::CreateLookupResult(Context, I, LastI));
791 break;
792 }
793 }
794
Douglas Gregor700792c2009-02-05 19:25:20 +0000795 LookedInCtx = true;
796 // Look into context considering using-directives.
797 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
798 LookupResults, &UDirs);
Douglas Gregor889ceb72009-02-03 19:21:40 +0000799
Douglas Gregor700792c2009-02-05 19:25:20 +0000800 if ((Result = MergeLookupResults(Context, LookupResults)) ||
801 (RedeclarationOnly && !Ctx->isTransparentContext()))
802 return std::make_pair(true, Result);
803 }
Douglas Gregor889ceb72009-02-03 19:21:40 +0000804
Douglas Gregor700792c2009-02-05 19:25:20 +0000805 if (!(LookedInCtx || LookupResults.empty())) {
806 // We didn't Performed lookup in Scope entity, so we return
807 // result form IdentifierResolver.
808 assert((LookupResults.size() == 1) && "Wrong size!");
809 return std::make_pair(true, LookupResults.front());
Douglas Gregor889ceb72009-02-03 19:21:40 +0000810 }
811 return std::make_pair(false, LookupResult());
Douglas Gregored8f2882009-01-30 01:04:22 +0000812}
813
Douglas Gregor34074322009-01-14 22:20:51 +0000814/// @brief Perform unqualified name lookup starting from a given
815/// scope.
816///
817/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
818/// used to find names within the current scope. For example, 'x' in
819/// @code
820/// int x;
821/// int f() {
822/// return x; // unqualified name look finds 'x' in the global scope
823/// }
824/// @endcode
825///
826/// Different lookup criteria can find different names. For example, a
827/// particular scope can have both a struct and a function of the same
828/// name, and each can be found by certain lookup criteria. For more
829/// information about lookup criteria, see the documentation for the
830/// class LookupCriteria.
831///
832/// @param S The scope from which unqualified name lookup will
833/// begin. If the lookup criteria permits, name lookup may also search
834/// in the parent scopes.
835///
836/// @param Name The name of the entity that we are searching for.
837///
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000838/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +0000839/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000840/// C library functions (like "malloc") are implicitly declared.
Douglas Gregor34074322009-01-14 22:20:51 +0000841///
842/// @returns The result of name lookup, which includes zero or more
843/// declarations and possibly additional information used to diagnose
844/// ambiguities.
Mike Stump11289f42009-09-09 15:08:12 +0000845Sema::LookupResult
Douglas Gregored8f2882009-01-30 01:04:22 +0000846Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000847 bool RedeclarationOnly, bool AllowBuiltinCreation,
848 SourceLocation Loc) {
Douglas Gregorf23311d2009-01-17 01:13:24 +0000849 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor34074322009-01-14 22:20:51 +0000850
851 if (!getLangOptions().CPlusPlus) {
852 // Unqualified name lookup in C/Objective-C is purely lexical, so
853 // search in the declarations attached to the name.
Douglas Gregored8f2882009-01-30 01:04:22 +0000854 unsigned IDNS = 0;
855 switch (NameKind) {
856 case Sema::LookupOrdinaryName:
857 IDNS = Decl::IDNS_Ordinary;
858 break;
Douglas Gregor34074322009-01-14 22:20:51 +0000859
Douglas Gregored8f2882009-01-30 01:04:22 +0000860 case Sema::LookupTagName:
861 IDNS = Decl::IDNS_Tag;
862 break;
863
864 case Sema::LookupMemberName:
865 IDNS = Decl::IDNS_Member;
866 break;
867
Douglas Gregor94eabf32009-02-04 16:44:47 +0000868 case Sema::LookupOperatorName:
Douglas Gregored8f2882009-01-30 01:04:22 +0000869 case Sema::LookupNestedNameSpecifierName:
870 case Sema::LookupNamespaceName:
871 assert(false && "C does not perform these kinds of name lookup");
872 break;
Douglas Gregoreddf4332009-02-24 20:03:32 +0000873
874 case Sema::LookupRedeclarationWithLinkage:
875 // Find the nearest non-transparent declaration scope.
876 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump11289f42009-09-09 15:08:12 +0000877 (S->getEntity() &&
Douglas Gregoreddf4332009-02-24 20:03:32 +0000878 static_cast<DeclContext *>(S->getEntity())
879 ->isTransparentContext()))
880 S = S->getParent();
881 IDNS = Decl::IDNS_Ordinary;
882 break;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000883
Douglas Gregor79947a22009-04-24 00:11:27 +0000884 case Sema::LookupObjCProtocolName:
885 IDNS = Decl::IDNS_ObjCProtocol;
886 break;
887
888 case Sema::LookupObjCImplementationName:
889 IDNS = Decl::IDNS_ObjCImplementation;
890 break;
Mike Stump11289f42009-09-09 15:08:12 +0000891
Douglas Gregor79947a22009-04-24 00:11:27 +0000892 case Sema::LookupObjCCategoryImplName:
893 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000894 break;
Douglas Gregored8f2882009-01-30 01:04:22 +0000895 }
896
Douglas Gregor34074322009-01-14 22:20:51 +0000897 // Scan up the scope chain looking for a decl that matches this
898 // identifier that is in the appropriate namespace. This search
899 // should not take long, as shadowing of names is uncommon, and
900 // deep shadowing is extremely uncommon.
Douglas Gregoreddf4332009-02-24 20:03:32 +0000901 bool LeftStartingScope = false;
902
Douglas Gregored8f2882009-01-30 01:04:22 +0000903 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump11289f42009-09-09 15:08:12 +0000904 IEnd = IdResolver.end();
Douglas Gregored8f2882009-01-30 01:04:22 +0000905 I != IEnd; ++I)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000906 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregoreddf4332009-02-24 20:03:32 +0000907 if (NameKind == LookupRedeclarationWithLinkage) {
908 // Determine whether this (or a previous) declaration is
909 // out-of-scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000910 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregoreddf4332009-02-24 20:03:32 +0000911 LeftStartingScope = true;
912
913 // If we found something outside of our starting scope that
914 // does not have linkage, skip it.
915 if (LeftStartingScope && !((*I)->hasLinkage()))
916 continue;
917 }
918
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000919 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000920 // If this declaration has the "overloadable" attribute, we
921 // might have a set of overloaded functions.
922
923 // Figure out what scope the identifier is in.
Chris Lattner83f095c2009-03-28 19:18:32 +0000924 while (!(S->getFlags() & Scope::DeclScope) ||
925 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000926 S = S->getParent();
927
928 // Find the last declaration in this scope (with the same
929 // name, naturally).
930 IdentifierResolver::iterator LastI = I;
931 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000932 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000933 break;
934 }
935
936 return LookupResult::CreateLookupResult(Context, I, LastI);
937 }
938
939 // We have a single lookup result.
Douglas Gregorf23311d2009-01-17 01:13:24 +0000940 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000941 }
Douglas Gregor34074322009-01-14 22:20:51 +0000942 } else {
Douglas Gregor889ceb72009-02-03 19:21:40 +0000943 // Perform C++ unqualified name lookup.
944 std::pair<bool, LookupResult> MaybeResult =
945 CppLookupName(S, Name, NameKind, RedeclarationOnly);
946 if (MaybeResult.first)
947 return MaybeResult.second;
Douglas Gregor34074322009-01-14 22:20:51 +0000948 }
949
950 // If we didn't find a use of this identifier, and if the identifier
951 // corresponds to a compiler builtin, create the decl object for the builtin
952 // now, injecting it into translation unit scope, and return it.
Mike Stump11289f42009-09-09 15:08:12 +0000953 if (NameKind == LookupOrdinaryName ||
Douglas Gregoreddf4332009-02-24 20:03:32 +0000954 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregor34074322009-01-14 22:20:51 +0000955 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000956 if (II && AllowBuiltinCreation) {
Douglas Gregor34074322009-01-14 22:20:51 +0000957 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000958 if (unsigned BuiltinID = II->getBuiltinID()) {
959 // In C++, we don't have any predefined library functions like
960 // 'malloc'. Instead, we'll just error.
Mike Stump11289f42009-09-09 15:08:12 +0000961 if (getLangOptions().CPlusPlus &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000962 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
963 return LookupResult::CreateLookupResult(Context, 0);
964
Douglas Gregorf23311d2009-01-17 01:13:24 +0000965 return LookupResult::CreateLookupResult(Context,
Douglas Gregor34074322009-01-14 22:20:51 +0000966 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000967 S, RedeclarationOnly, Loc));
968 }
Douglas Gregor34074322009-01-14 22:20:51 +0000969 }
Douglas Gregor34074322009-01-14 22:20:51 +0000970 }
Douglas Gregorf23311d2009-01-17 01:13:24 +0000971 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor34074322009-01-14 22:20:51 +0000972}
973
974/// @brief Perform qualified name lookup into a given context.
975///
976/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
977/// names when the context of those names is explicit specified, e.g.,
978/// "std::vector" or "x->member".
979///
980/// Different lookup criteria can find different names. For example, a
981/// particular scope can have both a struct and a function of the same
982/// name, and each can be found by certain lookup criteria. For more
983/// information about lookup criteria, see the documentation for the
984/// class LookupCriteria.
985///
986/// @param LookupCtx The context in which qualified name lookup will
987/// search. If the lookup criteria permits, name lookup may also search
988/// in the parent contexts or (for C++ classes) base classes.
989///
990/// @param Name The name of the entity that we are searching for.
991///
992/// @param Criteria The criteria that this routine will use to
993/// determine which names are visible and which names will be
994/// found. Note that name lookup will find a name that is visible by
995/// the given criteria, but the entity itself may not be semantically
996/// correct or even the kind of entity expected based on the
997/// lookup. For example, searching for a nested-name-specifier name
998/// might result in an EnumDecl, which is visible but is not permitted
999/// as a nested-name-specifier in C++03.
1000///
1001/// @returns The result of name lookup, which includes zero or more
1002/// declarations and possibly additional information used to diagnose
1003/// ambiguities.
1004Sema::LookupResult
1005Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregored8f2882009-01-30 01:04:22 +00001006 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregor34074322009-01-14 22:20:51 +00001007 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump11289f42009-09-09 15:08:12 +00001008
1009 if (!Name)
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001010 return LookupResult::CreateLookupResult(Context, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001011
Douglas Gregor34074322009-01-14 22:20:51 +00001012 // If we're performing qualified name lookup (e.g., lookup into a
1013 // struct), find fields as part of ordinary name lookup.
Douglas Gregored8f2882009-01-30 01:04:22 +00001014 unsigned IDNS
Mike Stump11289f42009-09-09 15:08:12 +00001015 = getIdentifierNamespacesFromLookupNameKind(NameKind,
Douglas Gregored8f2882009-01-30 01:04:22 +00001016 getLangOptions().CPlusPlus);
1017 if (NameKind == LookupOrdinaryName)
1018 IDNS |= Decl::IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +00001019
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001020 // Make sure that the declaration context is complete.
1021 assert((!isa<TagDecl>(LookupCtx) ||
1022 LookupCtx->isDependentContext() ||
1023 cast<TagDecl>(LookupCtx)->isDefinition() ||
1024 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1025 ->isBeingDefined()) &&
1026 "Declaration context must already be complete!");
Mike Stump11289f42009-09-09 15:08:12 +00001027
Douglas Gregor34074322009-01-14 22:20:51 +00001028 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor34074322009-01-14 22:20:51 +00001029 DeclContext::lookup_iterator I, E;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001030 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Douglas Gregored8f2882009-01-30 01:04:22 +00001031 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregorf23311d2009-01-17 01:13:24 +00001032 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregor34074322009-01-14 22:20:51 +00001033
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001034 // If this isn't a C++ class, we aren't allowed to look into base
1035 // classes, we're done, or the lookup context is dependent, we're done.
Mike Stump11289f42009-09-09 15:08:12 +00001036 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001037 LookupCtx->isDependentContext())
Douglas Gregorf23311d2009-01-17 01:13:24 +00001038 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001039
1040 // Perform lookup into our base classes.
1041 BasePaths Paths;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001042 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001043
1044 // Look for this member in our base classes
Mike Stump11289f42009-09-09 15:08:12 +00001045 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregored8f2882009-01-30 01:04:22 +00001046 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregorf23311d2009-01-17 01:13:24 +00001047 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001048
1049 // C++ [class.member.lookup]p2:
1050 // [...] If the resulting set of declarations are not all from
1051 // sub-objects of the same type, or the set has a nonstatic member
1052 // and includes members from distinct sub-objects, there is an
1053 // ambiguity and the program is ill-formed. Otherwise that set is
1054 // the result of the lookup.
1055 // FIXME: support using declarations!
1056 QualType SubobjectType;
Daniel Dunbar435bbe02009-01-15 18:32:35 +00001057 int SubobjectNumber = 0;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001058 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1059 Path != PathEnd; ++Path) {
1060 const BasePathElement &PathElement = Path->back();
1061
1062 // Determine whether we're looking at a distinct sub-object or not.
1063 if (SubobjectType.isNull()) {
1064 // This is the first subobject we've looked at. Record it's type.
1065 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1066 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump11289f42009-09-09 15:08:12 +00001067 } else if (SubobjectType
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001068 != Context.getCanonicalType(PathElement.Base->getType())) {
1069 // We found members of the given name in two subobjects of
1070 // different types. This lookup is ambiguous.
1071 BasePaths *PathsOnHeap = new BasePaths;
1072 PathsOnHeap->swap(Paths);
Douglas Gregorf23311d2009-01-17 01:13:24 +00001073 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001074 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1075 // We have a different subobject of the same type.
1076
1077 // C++ [class.member.lookup]p5:
1078 // A static member, a nested type or an enumerator defined in
1079 // a base class T can unambiguously be found even if an object
Mike Stump11289f42009-09-09 15:08:12 +00001080 // has more than one base class subobject of type T.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001081 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001082 if (isa<VarDecl>(FirstDecl) ||
1083 isa<TypeDecl>(FirstDecl) ||
1084 isa<EnumConstantDecl>(FirstDecl))
1085 continue;
1086
1087 if (isa<CXXMethodDecl>(FirstDecl)) {
1088 // Determine whether all of the methods are static.
1089 bool AllMethodsAreStatic = true;
1090 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1091 Func != Path->Decls.second; ++Func) {
1092 if (!isa<CXXMethodDecl>(*Func)) {
1093 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1094 break;
1095 }
1096
1097 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1098 AllMethodsAreStatic = false;
1099 break;
1100 }
1101 }
1102
1103 if (AllMethodsAreStatic)
1104 continue;
1105 }
1106
1107 // We have found a nonstatic member name in multiple, distinct
1108 // subobjects. Name lookup is ambiguous.
1109 BasePaths *PathsOnHeap = new BasePaths;
1110 PathsOnHeap->swap(Paths);
Douglas Gregorf23311d2009-01-17 01:13:24 +00001111 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001112 }
1113 }
1114
1115 // Lookup in a base class succeeded; return these results.
1116
1117 // If we found a function declaration, return an overload set.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001118 if ((*Paths.front().Decls.first)->isFunctionOrFunctionTemplate())
Mike Stump11289f42009-09-09 15:08:12 +00001119 return LookupResult::CreateLookupResult(Context,
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001120 Paths.front().Decls.first, Paths.front().Decls.second);
1121
1122 // We found a non-function declaration; return a single declaration.
Douglas Gregorf23311d2009-01-17 01:13:24 +00001123 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregor34074322009-01-14 22:20:51 +00001124}
1125
1126/// @brief Performs name lookup for a name that was parsed in the
1127/// source code, and may contain a C++ scope specifier.
1128///
1129/// This routine is a convenience routine meant to be called from
1130/// contexts that receive a name and an optional C++ scope specifier
1131/// (e.g., "N::M::x"). It will then perform either qualified or
1132/// unqualified name lookup (with LookupQualifiedName or LookupName,
1133/// respectively) on the given name and return those results.
1134///
1135/// @param S The scope from which unqualified name lookup will
1136/// begin.
Mike Stump11289f42009-09-09 15:08:12 +00001137///
Douglas Gregore861bac2009-08-25 22:51:20 +00001138/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregor34074322009-01-14 22:20:51 +00001139///
1140/// @param Name The name of the entity that name lookup will
1141/// search for.
1142///
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001143/// @param Loc If provided, the source location where we're performing
Mike Stump11289f42009-09-09 15:08:12 +00001144/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001145/// C library functions (like "malloc") are implicitly declared.
1146///
Douglas Gregore861bac2009-08-25 22:51:20 +00001147/// @param EnteringContext Indicates whether we are going to enter the
1148/// context of the scope-specifier SS (if present).
1149///
Douglas Gregor34074322009-01-14 22:20:51 +00001150/// @returns The result of qualified or unqualified name lookup.
1151Sema::LookupResult
Mike Stump11289f42009-09-09 15:08:12 +00001152Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
Douglas Gregored8f2882009-01-30 01:04:22 +00001153 DeclarationName Name, LookupNameKind NameKind,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001154 bool RedeclarationOnly, bool AllowBuiltinCreation,
Douglas Gregore861bac2009-08-25 22:51:20 +00001155 SourceLocation Loc,
1156 bool EnteringContext) {
1157 if (SS && SS->isInvalid()) {
1158 // When the scope specifier is invalid, don't even look for
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001159 // anything.
Douglas Gregore861bac2009-08-25 22:51:20 +00001160 return LookupResult::CreateLookupResult(Context, 0);
1161 }
Mike Stump11289f42009-09-09 15:08:12 +00001162
Douglas Gregore861bac2009-08-25 22:51:20 +00001163 if (SS && SS->isSet()) {
1164 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump11289f42009-09-09 15:08:12 +00001165 // We have resolved the scope specifier to a particular declaration
Douglas Gregore861bac2009-08-25 22:51:20 +00001166 // contex, and will perform name lookup in that context.
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001167 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
Douglas Gregore861bac2009-08-25 22:51:20 +00001168 return LookupResult::CreateLookupResult(Context, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001169
Douglas Gregore861bac2009-08-25 22:51:20 +00001170 return LookupQualifiedName(DC, Name, NameKind, RedeclarationOnly);
Douglas Gregor52537682009-03-19 00:18:19 +00001171 }
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001172
Douglas Gregore861bac2009-08-25 22:51:20 +00001173 // We could not resolve the scope specified to a specific declaration
Mike Stump11289f42009-09-09 15:08:12 +00001174 // context, which means that SS refers to an unknown specialization.
Douglas Gregore861bac2009-08-25 22:51:20 +00001175 // Name lookup can't find anything in this case.
1176 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregored8f2882009-01-30 01:04:22 +00001177 }
1178
Mike Stump11289f42009-09-09 15:08:12 +00001179 // Perform unqualified name lookup starting in the given scope.
1180 return LookupName(S, Name, NameKind, RedeclarationOnly, AllowBuiltinCreation,
Douglas Gregore861bac2009-08-25 22:51:20 +00001181 Loc);
Douglas Gregor34074322009-01-14 22:20:51 +00001182}
1183
Douglas Gregor889ceb72009-02-03 19:21:40 +00001184
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001185/// @brief Produce a diagnostic describing the ambiguity that resulted
1186/// from name lookup.
1187///
1188/// @param Result The ambiguous name lookup result.
Mike Stump11289f42009-09-09 15:08:12 +00001189///
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001190/// @param Name The name of the entity that name lookup was
1191/// searching for.
1192///
1193/// @param NameLoc The location of the name within the source code.
1194///
1195/// @param LookupRange A source range that provides more
1196/// source-location information concerning the lookup itself. For
1197/// example, this range might highlight a nested-name-specifier that
1198/// precedes the name.
1199///
1200/// @returns true
1201bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
Mike Stump11289f42009-09-09 15:08:12 +00001202 SourceLocation NameLoc,
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001203 SourceRange LookupRange) {
1204 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1205
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001206 if (BasePaths *Paths = Result.getBasePaths()) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001207 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1208 QualType SubobjectType = Paths->front().back().Base->getType();
1209 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1210 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1211 << LookupRange;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001212
Douglas Gregor889ceb72009-02-03 19:21:40 +00001213 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
Mike Stump11289f42009-09-09 15:08:12 +00001214 while (isa<CXXMethodDecl>(*Found) &&
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001215 cast<CXXMethodDecl>(*Found)->isStatic())
Douglas Gregor889ceb72009-02-03 19:21:40 +00001216 ++Found;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001217
Douglas Gregor889ceb72009-02-03 19:21:40 +00001218 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1219
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001220 Result.Destroy();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001221 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001222 }
Douglas Gregor889ceb72009-02-03 19:21:40 +00001223
1224 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1225 "Unhandled form of name lookup ambiguity");
1226
1227 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1228 << Name << LookupRange;
1229
1230 std::set<Decl *> DeclsPrinted;
1231 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1232 Path != PathEnd; ++Path) {
1233 Decl *D = *Path->Decls.first;
1234 if (DeclsPrinted.insert(D).second)
1235 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1236 }
1237
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001238 Result.Destroy();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001239 return true;
1240 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
Douglas Gregor889ceb72009-02-03 19:21:40 +00001241 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1242
Douglas Gregor2ada0482009-02-04 17:27:36 +00001243 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001244 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor889ceb72009-02-03 19:21:40 +00001245
Chris Lattner19272672009-02-03 21:29:32 +00001246 for (; DI != DEnd; ++DI)
Douglas Gregor2ada0482009-02-04 17:27:36 +00001247 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor889ceb72009-02-03 19:21:40 +00001248
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001249 Result.Destroy();
Douglas Gregor1c846b02009-01-16 00:38:09 +00001250 return true;
Douglas Gregor1c846b02009-01-16 00:38:09 +00001251 }
1252
Douglas Gregor889ceb72009-02-03 19:21:40 +00001253 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregorf23311d2009-01-17 01:13:24 +00001254
Douglas Gregor889ceb72009-02-03 19:21:40 +00001255 // We can't reach here.
Douglas Gregor960b5bc2009-01-15 00:26:24 +00001256 return true;
1257}
Douglas Gregore254f902009-02-04 00:32:51 +00001258
Mike Stump11289f42009-09-09 15:08:12 +00001259static void
1260addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001261 ASTContext &Context,
1262 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001263 Sema::AssociatedClassSet &AssociatedClasses);
1264
1265static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1266 DeclContext *Ctx) {
1267 if (Ctx->isFileContext())
1268 Namespaces.insert(Ctx);
1269}
Douglas Gregor197e5f72009-07-08 07:51:57 +00001270
Mike Stump11289f42009-09-09 15:08:12 +00001271// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor197e5f72009-07-08 07:51:57 +00001272// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump11289f42009-09-09 15:08:12 +00001273static void
1274addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor197e5f72009-07-08 07:51:57 +00001275 ASTContext &Context,
1276 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001277 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor197e5f72009-07-08 07:51:57 +00001278 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump11289f42009-09-09 15:08:12 +00001279 // -- [...] ;
Douglas Gregor197e5f72009-07-08 07:51:57 +00001280 switch (Arg.getKind()) {
1281 case TemplateArgument::Null:
1282 break;
Mike Stump11289f42009-09-09 15:08:12 +00001283
Douglas Gregor197e5f72009-07-08 07:51:57 +00001284 case TemplateArgument::Type:
1285 // [...] the namespaces and classes associated with the types of the
1286 // template arguments provided for template type parameters (excluding
1287 // template template parameters)
1288 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1289 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001290 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001291 break;
Mike Stump11289f42009-09-09 15:08:12 +00001292
Douglas Gregor197e5f72009-07-08 07:51:57 +00001293 case TemplateArgument::Declaration:
Mike Stump11289f42009-09-09 15:08:12 +00001294 // [...] the namespaces in which any template template arguments are
1295 // defined; and the classes in which any member templates used as
Douglas Gregor197e5f72009-07-08 07:51:57 +00001296 // template template arguments are defined.
Mike Stump11289f42009-09-09 15:08:12 +00001297 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor197e5f72009-07-08 07:51:57 +00001298 = dyn_cast<ClassTemplateDecl>(Arg.getAsDecl())) {
1299 DeclContext *Ctx = ClassTemplate->getDeclContext();
1300 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1301 AssociatedClasses.insert(EnclosingClass);
1302 // Add the associated namespace for this class.
1303 while (Ctx->isRecord())
1304 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001305 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001306 }
1307 break;
Mike Stump11289f42009-09-09 15:08:12 +00001308
Douglas Gregor197e5f72009-07-08 07:51:57 +00001309 case TemplateArgument::Integral:
1310 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00001311 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor197e5f72009-07-08 07:51:57 +00001312 // associated namespaces. ]
1313 break;
Mike Stump11289f42009-09-09 15:08:12 +00001314
Douglas Gregor197e5f72009-07-08 07:51:57 +00001315 case TemplateArgument::Pack:
1316 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1317 PEnd = Arg.pack_end();
1318 P != PEnd; ++P)
1319 addAssociatedClassesAndNamespaces(*P, Context,
1320 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001321 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001322 break;
1323 }
1324}
1325
Douglas Gregore254f902009-02-04 00:32:51 +00001326// \brief Add the associated classes and namespaces for
Mike Stump11289f42009-09-09 15:08:12 +00001327// argument-dependent lookup with an argument of class type
1328// (C++ [basic.lookup.koenig]p2).
1329static void
1330addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregore254f902009-02-04 00:32:51 +00001331 ASTContext &Context,
1332 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001333 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001334 // C++ [basic.lookup.koenig]p2:
1335 // [...]
1336 // -- If T is a class type (including unions), its associated
1337 // classes are: the class itself; the class of which it is a
1338 // member, if any; and its direct and indirect base
1339 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001340 // which its associated classes are defined.
Douglas Gregore254f902009-02-04 00:32:51 +00001341
1342 // Add the class of which it is a member, if any.
1343 DeclContext *Ctx = Class->getDeclContext();
1344 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1345 AssociatedClasses.insert(EnclosingClass);
Douglas Gregore254f902009-02-04 00:32:51 +00001346 // Add the associated namespace for this class.
1347 while (Ctx->isRecord())
1348 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001349 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001350
Douglas Gregore254f902009-02-04 00:32:51 +00001351 // Add the class itself. If we've already seen this class, we don't
1352 // need to visit base classes.
1353 if (!AssociatedClasses.insert(Class))
1354 return;
1355
Mike Stump11289f42009-09-09 15:08:12 +00001356 // -- If T is a template-id, its associated namespaces and classes are
1357 // the namespace in which the template is defined; for member
Douglas Gregor197e5f72009-07-08 07:51:57 +00001358 // templates, the member template’s class; the namespaces and classes
Mike Stump11289f42009-09-09 15:08:12 +00001359 // associated with the types of the template arguments provided for
Douglas Gregor197e5f72009-07-08 07:51:57 +00001360 // template type parameters (excluding template template parameters); the
Mike Stump11289f42009-09-09 15:08:12 +00001361 // namespaces in which any template template arguments are defined; and
1362 // the classes in which any member templates used as template template
1363 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor197e5f72009-07-08 07:51:57 +00001364 // contribute to the set of associated namespaces. ]
Mike Stump11289f42009-09-09 15:08:12 +00001365 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor197e5f72009-07-08 07:51:57 +00001366 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1367 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1368 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1369 AssociatedClasses.insert(EnclosingClass);
1370 // Add the associated namespace for this class.
1371 while (Ctx->isRecord())
1372 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001373 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001374
Douglas Gregor197e5f72009-07-08 07:51:57 +00001375 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1376 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1377 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1378 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001379 AssociatedClasses);
Douglas Gregor197e5f72009-07-08 07:51:57 +00001380 }
Mike Stump11289f42009-09-09 15:08:12 +00001381
Douglas Gregore254f902009-02-04 00:32:51 +00001382 // Add direct and indirect base classes along with their associated
1383 // namespaces.
1384 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1385 Bases.push_back(Class);
1386 while (!Bases.empty()) {
1387 // Pop this class off the stack.
1388 Class = Bases.back();
1389 Bases.pop_back();
1390
1391 // Visit the base classes.
1392 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1393 BaseEnd = Class->bases_end();
1394 Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001395 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Douglas Gregore254f902009-02-04 00:32:51 +00001396 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1397 if (AssociatedClasses.insert(BaseDecl)) {
1398 // Find the associated namespace for this base class.
1399 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1400 while (BaseCtx->isRecord())
1401 BaseCtx = BaseCtx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001402 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregore254f902009-02-04 00:32:51 +00001403
1404 // Make sure we visit the bases of this base class.
1405 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1406 Bases.push_back(BaseDecl);
1407 }
1408 }
1409 }
1410}
1411
1412// \brief Add the associated classes and namespaces for
1413// argument-dependent lookup with an argument of type T
Mike Stump11289f42009-09-09 15:08:12 +00001414// (C++ [basic.lookup.koenig]p2).
1415static void
1416addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregore254f902009-02-04 00:32:51 +00001417 ASTContext &Context,
1418 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001419 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001420 // C++ [basic.lookup.koenig]p2:
1421 //
1422 // For each argument type T in the function call, there is a set
1423 // of zero or more associated namespaces and a set of zero or more
1424 // associated classes to be considered. The sets of namespaces and
1425 // classes is determined entirely by the types of the function
1426 // arguments (and the namespace of any template template
1427 // argument). Typedef names and using-declarations used to specify
1428 // the types do not contribute to this set. The sets of namespaces
1429 // and classes are determined in the following way:
1430 T = Context.getCanonicalType(T).getUnqualifiedType();
1431
1432 // -- If T is a pointer to U or an array of U, its associated
Mike Stump11289f42009-09-09 15:08:12 +00001433 // namespaces and classes are those associated with U.
Douglas Gregore254f902009-02-04 00:32:51 +00001434 //
1435 // We handle this by unwrapping pointer and array types immediately,
1436 // to avoid unnecessary recursion.
1437 while (true) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001438 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001439 T = Ptr->getPointeeType();
1440 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1441 T = Ptr->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001442 else
Douglas Gregore254f902009-02-04 00:32:51 +00001443 break;
1444 }
1445
1446 // -- If T is a fundamental type, its associated sets of
1447 // namespaces and classes are both empty.
1448 if (T->getAsBuiltinType())
1449 return;
1450
1451 // -- If T is a class type (including unions), its associated
1452 // classes are: the class itself; the class of which it is a
1453 // member, if any; and its direct and indirect base
1454 // classes. Its associated namespaces are the namespaces in
Mike Stump11289f42009-09-09 15:08:12 +00001455 // which its associated classes are defined.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001456 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump11289f42009-09-09 15:08:12 +00001457 if (CXXRecordDecl *ClassDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001458 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001459 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1460 AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001461 AssociatedClasses);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001462 return;
1463 }
Douglas Gregore254f902009-02-04 00:32:51 +00001464
1465 // -- If T is an enumeration type, its associated namespace is
1466 // the namespace in which it is defined. If it is class
1467 // member, its associated class is the member’s class; else
Mike Stump11289f42009-09-09 15:08:12 +00001468 // it has no associated class.
Douglas Gregore254f902009-02-04 00:32:51 +00001469 if (const EnumType *EnumT = T->getAsEnumType()) {
1470 EnumDecl *Enum = EnumT->getDecl();
1471
1472 DeclContext *Ctx = Enum->getDeclContext();
1473 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1474 AssociatedClasses.insert(EnclosingClass);
1475
1476 // Add the associated namespace for this class.
1477 while (Ctx->isRecord())
1478 Ctx = Ctx->getParent();
John McCallc7e8e792009-08-07 22:18:02 +00001479 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001480
1481 return;
1482 }
1483
1484 // -- If T is a function type, its associated namespaces and
1485 // classes are those associated with the function parameter
1486 // types and those associated with the return type.
1487 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1488 // Return type
Mike Stump11289f42009-09-09 15:08:12 +00001489 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
Douglas Gregore254f902009-02-04 00:32:51 +00001490 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001491 AssociatedNamespaces, AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001492
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001493 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
Douglas Gregore254f902009-02-04 00:32:51 +00001494 if (!Proto)
1495 return;
1496
1497 // Argument types
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001498 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001499 ArgEnd = Proto->arg_type_end();
Douglas Gregore254f902009-02-04 00:32:51 +00001500 Arg != ArgEnd; ++Arg)
1501 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCallc7e8e792009-08-07 22:18:02 +00001502 AssociatedNamespaces, AssociatedClasses);
Mike Stump11289f42009-09-09 15:08:12 +00001503
Douglas Gregore254f902009-02-04 00:32:51 +00001504 return;
1505 }
1506
1507 // -- If T is a pointer to a member function of a class X, its
1508 // associated namespaces and classes are those associated
1509 // with the function parameter types and return type,
Mike Stump11289f42009-09-09 15:08:12 +00001510 // together with those associated with X.
Douglas Gregore254f902009-02-04 00:32:51 +00001511 //
1512 // -- If T is a pointer to a data member of class X, its
1513 // associated namespaces and classes are those associated
1514 // with the member type together with those associated with
Mike Stump11289f42009-09-09 15:08:12 +00001515 // X.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001516 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregore254f902009-02-04 00:32:51 +00001517 // Handle the type that the pointer to member points to.
1518 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1519 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001520 AssociatedNamespaces,
1521 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001522
1523 // Handle the class type into which this points.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001524 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregore254f902009-02-04 00:32:51 +00001525 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1526 Context,
John McCallc7e8e792009-08-07 22:18:02 +00001527 AssociatedNamespaces,
1528 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001529
1530 return;
1531 }
1532
1533 // FIXME: What about block pointers?
1534 // FIXME: What about Objective-C message sends?
1535}
1536
1537/// \brief Find the associated classes and namespaces for
1538/// argument-dependent lookup for a call with the given set of
1539/// arguments.
1540///
1541/// This routine computes the sets of associated classes and associated
Mike Stump11289f42009-09-09 15:08:12 +00001542/// namespaces searched by argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00001543/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001544void
Douglas Gregore254f902009-02-04 00:32:51 +00001545Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1546 AssociatedNamespaceSet &AssociatedNamespaces,
John McCallc7e8e792009-08-07 22:18:02 +00001547 AssociatedClassSet &AssociatedClasses) {
Douglas Gregore254f902009-02-04 00:32:51 +00001548 AssociatedNamespaces.clear();
1549 AssociatedClasses.clear();
1550
1551 // C++ [basic.lookup.koenig]p2:
1552 // For each argument type T in the function call, there is a set
1553 // of zero or more associated namespaces and a set of zero or more
1554 // associated classes to be considered. The sets of namespaces and
1555 // classes is determined entirely by the types of the function
1556 // arguments (and the namespace of any template template
Mike Stump11289f42009-09-09 15:08:12 +00001557 // argument).
Douglas Gregore254f902009-02-04 00:32:51 +00001558 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1559 Expr *Arg = Args[ArgIdx];
1560
1561 if (Arg->getType() != Context.OverloadTy) {
1562 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001563 AssociatedNamespaces,
1564 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001565 continue;
1566 }
1567
1568 // [...] In addition, if the argument is the name or address of a
1569 // set of overloaded functions and/or function templates, its
1570 // associated classes and namespaces are the union of those
1571 // associated with each of the members of the set: the namespace
1572 // in which the function or function template is defined and the
1573 // classes and namespaces associated with its (non-dependent)
1574 // parameter types and return type.
1575 DeclRefExpr *DRE = 0;
Douglas Gregorbe759252009-07-08 10:57:20 +00001576 TemplateIdRefExpr *TIRE = 0;
1577 Arg = Arg->IgnoreParens();
Douglas Gregore254f902009-02-04 00:32:51 +00001578 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorbe759252009-07-08 10:57:20 +00001579 if (unaryOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregore254f902009-02-04 00:32:51 +00001580 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
Douglas Gregorbe759252009-07-08 10:57:20 +00001581 TIRE = dyn_cast<TemplateIdRefExpr>(unaryOp->getSubExpr());
1582 }
1583 } else {
Douglas Gregore254f902009-02-04 00:32:51 +00001584 DRE = dyn_cast<DeclRefExpr>(Arg);
Douglas Gregorbe759252009-07-08 10:57:20 +00001585 TIRE = dyn_cast<TemplateIdRefExpr>(Arg);
1586 }
Mike Stump11289f42009-09-09 15:08:12 +00001587
Douglas Gregorbe759252009-07-08 10:57:20 +00001588 OverloadedFunctionDecl *Ovl = 0;
1589 if (DRE)
1590 Ovl = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1591 else if (TIRE)
Douglas Gregoraa87ebc2009-07-29 18:26:50 +00001592 Ovl = TIRE->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001593 if (!Ovl)
1594 continue;
1595
1596 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1597 FuncEnd = Ovl->function_end();
1598 Func != FuncEnd; ++Func) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001599 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func);
1600 if (!FDecl)
1601 FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl();
Douglas Gregore254f902009-02-04 00:32:51 +00001602
1603 // Add the namespace in which this function was defined. Note
1604 // that, if this is a member function, we do *not* consider the
1605 // enclosing namespace of its class.
1606 DeclContext *Ctx = FDecl->getDeclContext();
John McCallc7e8e792009-08-07 22:18:02 +00001607 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregore254f902009-02-04 00:32:51 +00001608
1609 // Add the classes and namespaces associated with the parameter
1610 // types and return type of this function.
1611 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCallc7e8e792009-08-07 22:18:02 +00001612 AssociatedNamespaces,
1613 AssociatedClasses);
Douglas Gregore254f902009-02-04 00:32:51 +00001614 }
1615 }
1616}
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001617
1618/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1619/// an acceptable non-member overloaded operator for a call whose
1620/// arguments have types T1 (and, if non-empty, T2). This routine
1621/// implements the check in C++ [over.match.oper]p3b2 concerning
1622/// enumeration types.
Mike Stump11289f42009-09-09 15:08:12 +00001623static bool
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001624IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1625 QualType T1, QualType T2,
1626 ASTContext &Context) {
Douglas Gregor0950e412009-03-13 21:01:28 +00001627 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1628 return true;
1629
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001630 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1631 return true;
1632
1633 const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1634 if (Proto->getNumArgs() < 1)
1635 return false;
1636
1637 if (T1->isEnumeralType()) {
1638 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1639 if (Context.getCanonicalType(T1).getUnqualifiedType()
1640 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1641 return true;
1642 }
1643
1644 if (Proto->getNumArgs() < 2)
1645 return false;
1646
1647 if (!T2.isNull() && T2->isEnumeralType()) {
1648 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1649 if (Context.getCanonicalType(T2).getUnqualifiedType()
1650 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1651 return true;
1652 }
1653
1654 return false;
1655}
1656
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001657/// \brief Find the protocol with the given name, if any.
1658ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
Douglas Gregor79947a22009-04-24 00:11:27 +00001659 Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl();
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001660 return cast_or_null<ObjCProtocolDecl>(D);
1661}
1662
Douglas Gregor79947a22009-04-24 00:11:27 +00001663/// \brief Find the Objective-C category implementation with the given
1664/// name, if any.
1665ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
1666 Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl();
1667 return cast_or_null<ObjCCategoryImplDecl>(D);
1668}
1669
John McCall07e91c02009-08-06 02:15:43 +00001670// Attempts to find a declaration in the given declaration context
1671// with exactly the given type. Returns null if no such declaration
1672// was found.
1673Decl *Sema::LookupQualifiedNameWithType(DeclContext *DC,
1674 DeclarationName Name,
1675 QualType T) {
1676 LookupResult result =
1677 LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
1678
1679 CanQualType CQT = Context.getCanonicalType(T);
1680
1681 for (LookupResult::iterator ir = result.begin(), ie = result.end();
1682 ir != ie; ++ir)
1683 if (FunctionDecl *CurFD = dyn_cast<FunctionDecl>(*ir))
1684 if (Context.getCanonicalType(CurFD->getType()) == CQT)
1685 return CurFD;
1686
1687 return NULL;
1688}
1689
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001690void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00001691 QualType T1, QualType T2,
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001692 FunctionSet &Functions) {
1693 // C++ [over.match.oper]p3:
1694 // -- The set of non-member candidates is the result of the
1695 // unqualified lookup of operator@ in the context of the
1696 // expression according to the usual rules for name lookup in
1697 // unqualified function calls (3.4.2) except that all member
1698 // functions are ignored. However, if no operand has a class
1699 // type, only those non-member functions in the lookup set
Eli Friedman44b83ee2009-08-05 19:21:58 +00001700 // that have a first parameter of type T1 or "reference to
1701 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001702 // type, or (if there is a right operand) a second parameter
Eli Friedman44b83ee2009-08-05 19:21:58 +00001703 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001704 // when T2 is an enumeration type, are candidate functions.
1705 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1706 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
Mike Stump11289f42009-09-09 15:08:12 +00001707
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001708 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1709
1710 if (!Operators)
1711 return;
1712
1713 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1714 Op != OpEnd; ++Op) {
Douglas Gregor15448f82009-06-27 21:05:07 +00001715 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001716 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1717 Functions.insert(FD); // FIXME: canonical FD
Mike Stump11289f42009-09-09 15:08:12 +00001718 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor15448f82009-06-27 21:05:07 +00001719 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1720 // FIXME: friend operators?
Mike Stump11289f42009-09-09 15:08:12 +00001721 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor15448f82009-06-27 21:05:07 +00001722 // later?
1723 if (!FunTmpl->getDeclContext()->isRecord())
1724 Functions.insert(FunTmpl);
1725 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001726 }
1727}
1728
John McCallc7e8e792009-08-07 22:18:02 +00001729static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1730 Decl *D) {
1731 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1732 Functions.insert(Func);
1733 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1734 Functions.insert(FunTmpl);
1735}
1736
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001737void Sema::ArgumentDependentLookup(DeclarationName Name,
1738 Expr **Args, unsigned NumArgs,
1739 FunctionSet &Functions) {
1740 // Find all of the associated namespaces and classes based on the
1741 // arguments we have.
1742 AssociatedNamespaceSet AssociatedNamespaces;
1743 AssociatedClassSet AssociatedClasses;
Mike Stump11289f42009-09-09 15:08:12 +00001744 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCallc7e8e792009-08-07 22:18:02 +00001745 AssociatedNamespaces,
1746 AssociatedClasses);
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001747
1748 // C++ [basic.lookup.argdep]p3:
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001749 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1750 // and let Y be the lookup set produced by argument dependent
1751 // lookup (defined as follows). If X contains [...] then Y is
1752 // empty. Otherwise Y is the set of declarations found in the
1753 // namespaces associated with the argument types as described
1754 // below. The set of declarations found by the lookup of the name
1755 // is the union of X and Y.
1756 //
1757 // Here, we compute Y and add its members to the overloaded
1758 // candidate set.
1759 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001760 NSEnd = AssociatedNamespaces.end();
1761 NS != NSEnd; ++NS) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001762 // When considering an associated namespace, the lookup is the
1763 // same as the lookup performed when the associated namespace is
1764 // used as a qualifier (3.4.3.2) except that:
1765 //
1766 // -- Any using-directives in the associated namespace are
1767 // ignored.
1768 //
John McCallc7e8e792009-08-07 22:18:02 +00001769 // -- Any namespace-scope friend functions declared in
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001770 // associated classes are visible within their respective
1771 // namespaces even if they are not visible during an ordinary
1772 // lookup (11.4).
1773 DeclContext::lookup_iterator I, E;
John McCalld1e9d832009-08-11 06:59:38 +00001774 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCallc7e8e792009-08-07 22:18:02 +00001775 Decl *D = *I;
John McCallaa74a0c2009-08-28 07:59:38 +00001776 // If the only declaration here is an ordinary friend, consider
1777 // it only if it was declared in an associated classes.
1778 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCalld1e9d832009-08-11 06:59:38 +00001779 DeclContext *LexDC = D->getLexicalDeclContext();
1780 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1781 continue;
1782 }
Mike Stump11289f42009-09-09 15:08:12 +00001783
John McCallc7e8e792009-08-07 22:18:02 +00001784 CollectFunctionDecl(Functions, D);
Douglas Gregor6127ca42009-06-23 20:14:09 +00001785 }
1786 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00001787}