blob: d76761c696351f199468364a5b83181e5d9c4bad [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000015#include "SemaInherit.h"
16#include "clang/AST/ASTContext.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000020#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000021#include "clang/AST/Expr.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000022#include "clang/Parse/DeclSpec.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000024#include "clang/Basic/LangOptions.h"
25#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000026#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000027#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000028#include <vector>
29#include <iterator>
30#include <utility>
31#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000032
33using namespace clang;
34
Douglas Gregor2a3009a2009-02-03 19:21:40 +000035typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy;
36typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet;
37typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy;
38
39/// UsingDirAncestorCompare - Implements strict weak ordering of
40/// UsingDirectives. It orders them by address of its common ancestor.
41struct UsingDirAncestorCompare {
42
43 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
44 bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const {
45 return U->getCommonAncestor() < Ctx;
46 }
47
48 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
49 bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const {
50 return Ctx < U->getCommonAncestor();
51 }
52
53 /// @brief Compares UsingDirectiveDecl common ancestors.
54 bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const {
55 return U1->getCommonAncestor() < U2->getCommonAncestor();
56 }
57};
58
59/// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs
60/// (ordered by common ancestors), found in namespace NS,
61/// including all found (recursively) in their nominated namespaces.
Douglas Gregor6ab35242009-04-09 21:40:53 +000062void AddNamespaceUsingDirectives(ASTContext &Context,
63 DeclContext *NS,
Douglas Gregor2a3009a2009-02-03 19:21:40 +000064 UsingDirectivesTy &UDirs,
65 NamespaceSet &Visited) {
66 DeclContext::udir_iterator I, End;
67
Douglas Gregor6ab35242009-04-09 21:40:53 +000068 for (llvm::tie(I, End) = NS->getUsingDirectives(Context); I !=End; ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +000069 UDirs.push_back(*I);
70 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
71 NamespaceDecl *Nominated = (*I)->getNominatedNamespace();
72 if (Visited.insert(Nominated).second)
Douglas Gregor6ab35242009-04-09 21:40:53 +000073 AddNamespaceUsingDirectives(Context, Nominated, UDirs, /*ref*/ Visited);
Douglas Gregor2a3009a2009-02-03 19:21:40 +000074 }
75}
76
77/// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S,
78/// including all found in the namespaces they nominate.
Douglas Gregor6ab35242009-04-09 21:40:53 +000079static void AddScopeUsingDirectives(ASTContext &Context, Scope *S,
80 UsingDirectivesTy &UDirs) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +000081 NamespaceSet VisitedNS;
82
83 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
84
85 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx))
86 VisitedNS.insert(NS);
87
Douglas Gregor6ab35242009-04-09 21:40:53 +000088 AddNamespaceUsingDirectives(Context, Ctx, UDirs, /*ref*/ VisitedNS);
Douglas Gregor2a3009a2009-02-03 19:21:40 +000089
90 } else {
Chris Lattnerb28317a2009-03-28 19:18:32 +000091 Scope::udir_iterator I = S->using_directives_begin(),
92 End = S->using_directives_end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +000093
94 for (; I != End; ++I) {
Chris Lattnerb28317a2009-03-28 19:18:32 +000095 UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>();
Douglas Gregor2a3009a2009-02-03 19:21:40 +000096 UDirs.push_back(UD);
97 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
98
99 NamespaceDecl *Nominated = UD->getNominatedNamespace();
100 if (!VisitedNS.count(Nominated)) {
101 VisitedNS.insert(Nominated);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000102 AddNamespaceUsingDirectives(Context, Nominated, UDirs,
103 /*ref*/ VisitedNS);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000104 }
105 }
106 }
107}
108
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000109/// MaybeConstructOverloadSet - Name lookup has determined that the
110/// elements in [I, IEnd) have the name that we are looking for, and
111/// *I is a match for the namespace. This routine returns an
112/// appropriate Decl for name lookup, which may either be *I or an
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000113/// OverloadedFunctionDecl that represents the overloaded functions in
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000114/// [I, IEnd).
115///
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000116/// The existance of this routine is temporary; users of LookupResult
117/// should be able to handle multiple results, to deal with cases of
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000118/// ambiguity and overloaded functions without needing to create a
119/// Decl node.
120template<typename DeclIterator>
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000121static NamedDecl *
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000122MaybeConstructOverloadSet(ASTContext &Context,
123 DeclIterator I, DeclIterator IEnd) {
124 assert(I != IEnd && "Iterator range cannot be empty");
125 assert(!isa<OverloadedFunctionDecl>(*I) &&
126 "Cannot have an overloaded function");
127
Douglas Gregore53060f2009-06-25 22:08:12 +0000128 if ((*I)->isFunctionOrFunctionTemplate()) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000129 // If we found a function, there might be more functions. If
130 // so, collect them into an overload set.
131 DeclIterator Last = I;
132 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregore53060f2009-06-25 22:08:12 +0000133 for (++Last;
134 Last != IEnd && (*Last)->isFunctionOrFunctionTemplate();
135 ++Last) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000136 if (!Ovl) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000137 // FIXME: We leak this overload set. Eventually, we want to stop
138 // building the declarations for these overload sets, so there will be
139 // nothing to leak.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000140 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000141 (*I)->getDeclName());
Anders Carlsson58badb72009-06-26 05:26:50 +0000142 NamedDecl *ND = (*I);
143 if (UsingDecl *UD = dyn_cast<UsingDecl>(ND))
144 ND = UD->getTargetDecl();
145
146 if (isa<FunctionDecl>(ND))
147 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregore53060f2009-06-25 22:08:12 +0000148 else
Anders Carlsson58badb72009-06-26 05:26:50 +0000149 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000150 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000151
Anders Carlsson58badb72009-06-26 05:26:50 +0000152 NamedDecl *ND = (*Last);
153 if (UsingDecl *UD = dyn_cast<UsingDecl>(ND))
154 ND = UD->getTargetDecl();
155
156 if (isa<FunctionDecl>(ND))
157 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregore53060f2009-06-25 22:08:12 +0000158 else
Anders Carlsson58badb72009-06-26 05:26:50 +0000159 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000160 }
161
162 // If we had more than one function, we built an overload
163 // set. Return it.
164 if (Ovl)
165 return Ovl;
166 }
167
168 return *I;
169}
170
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000171/// Merges together multiple LookupResults dealing with duplicated Decl's.
172static Sema::LookupResult
173MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
174 typedef Sema::LookupResult LResult;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000175 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000176
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000177 // Remove duplicated Decl pointing at same Decl, by storing them in
178 // associative collection. This might be case for code like:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000179 //
180 // namespace A { int i; }
181 // namespace B { using namespace A; }
182 // namespace C { using namespace A; }
183 //
184 // void foo() {
185 // using namespace B;
186 // using namespace C;
187 // ++i; // finds A::i, from both namespace B and C at global scope
188 // }
189 //
190 // C++ [namespace.qual].p3:
191 // The same declaration found more than once is not an ambiguity
192 // (because it is still a unique declaration).
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000193 DeclsSetTy FoundDecls;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000194
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000195 // Counter of tag names, and functions for resolving ambiguity
196 // and name hiding.
197 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000198
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000199 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
200
201 // No name lookup results, return early.
202 if (I == End) return LResult::CreateLookupResult(Context, 0);
203
204 // Keep track of the tag declaration we found. We only use this if
205 // we find a single tag declaration.
206 TagDecl *TagFound = 0;
207
208 for (; I != End; ++I) {
209 switch (I->getKind()) {
210 case LResult::NotFound:
211 assert(false &&
212 "Should be always successful name lookup result here.");
213 break;
214
215 case LResult::AmbiguousReference:
216 case LResult::AmbiguousBaseSubobjectTypes:
217 case LResult::AmbiguousBaseSubobjects:
218 assert(false && "Shouldn't get ambiguous lookup here.");
219 break;
220
221 case LResult::Found: {
222 NamedDecl *ND = I->getAsDecl();
Anders Carlssonbc13ab22009-06-26 03:54:13 +0000223 if (UsingDecl *UD = dyn_cast<UsingDecl>(ND))
224 ND = UD->getTargetDecl();
225
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000226 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
227 TagFound = Context.getCanonicalDecl(TD);
228 TagNames += FoundDecls.insert(TagFound)? 1 : 0;
Douglas Gregore53060f2009-06-25 22:08:12 +0000229 } else if (ND->isFunctionOrFunctionTemplate())
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000230 Functions += FoundDecls.insert(ND)? 1 : 0;
231 else
232 FoundDecls.insert(ND);
233 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000234 }
235
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000236 case LResult::FoundOverloaded:
237 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
238 Functions += FoundDecls.insert(*FI)? 1 : 0;
239 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000240 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000241 }
242 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
243 bool Ambiguous = false, NameHidesTags = false;
244
245 if (FoundDecls.size() == 1) {
246 // 1) Exactly one result.
247 } else if (TagNames > 1) {
248 // 2) Multiple tag names (even though they may be hidden by an
249 // object name).
250 Ambiguous = true;
251 } else if (FoundDecls.size() - TagNames == 1) {
252 // 3) Ordinary name hides (optional) tag.
253 NameHidesTags = TagFound;
254 } else if (Functions) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000255 // C++ [basic.lookup].p1:
256 // ... Name lookup may associate more than one declaration with
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000257 // a name if it finds the name to be a function name; the declarations
258 // are said to form a set of overloaded functions (13.1).
259 // Overload resolution (13.3) takes place after name lookup has succeeded.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000260 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000261 if (!OrdinaryNonFunc) {
262 // 4) Functions hide tag names.
263 NameHidesTags = TagFound;
264 } else {
265 // 5) Functions + ordinary names.
266 Ambiguous = true;
267 }
268 } else {
269 // 6) Multiple non-tag names
270 Ambiguous = true;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000271 }
272
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000273 if (Ambiguous)
274 return LResult::CreateLookupResult(Context,
275 FoundDecls.begin(), FoundDecls.size());
276 if (NameHidesTags) {
277 // There's only one tag, TagFound. Remove it.
278 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
279 FoundDecls.erase(TagFound);
280 }
281
282 // Return successful name lookup result.
283 return LResult::CreateLookupResult(Context,
284 MaybeConstructOverloadSet(Context,
285 FoundDecls.begin(),
286 FoundDecls.end()));
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000287}
288
289// Retrieve the set of identifier namespaces that correspond to a
290// specific kind of name lookup.
291inline unsigned
292getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
293 bool CPlusPlus) {
294 unsigned IDNS = 0;
295 switch (NameKind) {
296 case Sema::LookupOrdinaryName:
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000297 case Sema::LookupOperatorName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000298 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000299 IDNS = Decl::IDNS_Ordinary;
300 if (CPlusPlus)
301 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
302 break;
303
304 case Sema::LookupTagName:
305 IDNS = Decl::IDNS_Tag;
306 break;
307
308 case Sema::LookupMemberName:
309 IDNS = Decl::IDNS_Member;
310 if (CPlusPlus)
311 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
312 break;
313
314 case Sema::LookupNestedNameSpecifierName:
315 case Sema::LookupNamespaceName:
316 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
317 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000318
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000319 case Sema::LookupObjCProtocolName:
320 IDNS = Decl::IDNS_ObjCProtocol;
321 break;
322
323 case Sema::LookupObjCImplementationName:
324 IDNS = Decl::IDNS_ObjCImplementation;
325 break;
326
327 case Sema::LookupObjCCategoryImplName:
328 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000329 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000330 }
331 return IDNS;
332}
333
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000334Sema::LookupResult
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000335Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Douglas Gregor516ff432009-04-24 02:57:34 +0000336 if (ObjCCompatibleAliasDecl *Alias
337 = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
338 D = Alias->getClassInterface();
Anders Carlsson8b50d012009-06-26 03:37:05 +0000339 if (UsingDecl *UD = dyn_cast_or_null<UsingDecl>(D))
340 D = UD->getTargetDecl();
341
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000342 LookupResult Result;
343 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
344 OverloadedDeclSingleDecl : SingleDecl;
345 Result.First = reinterpret_cast<uintptr_t>(D);
346 Result.Last = 0;
347 Result.Context = &Context;
348 return Result;
349}
350
Douglas Gregor4bb64e72009-01-15 02:19:31 +0000351/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000352Sema::LookupResult
353Sema::LookupResult::CreateLookupResult(ASTContext &Context,
354 IdentifierResolver::iterator F,
355 IdentifierResolver::iterator L) {
356 LookupResult Result;
357 Result.Context = &Context;
358
Douglas Gregore53060f2009-06-25 22:08:12 +0000359 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor7176fff2009-01-15 00:26:24 +0000360 IdentifierResolver::iterator Next = F;
361 ++Next;
Douglas Gregore53060f2009-06-25 22:08:12 +0000362 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000363 Result.StoredKind = OverloadedDeclFromIdResolver;
364 Result.First = F.getAsOpaqueValue();
365 Result.Last = L.getAsOpaqueValue();
366 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000367 }
368 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000369
370 Decl *D = *F;
371 if (ObjCCompatibleAliasDecl *Alias
372 = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
373 D = Alias->getClassInterface();
Anders Carlsson8b50d012009-06-26 03:37:05 +0000374 if (UsingDecl *UD = dyn_cast_or_null<UsingDecl>(D))
375 D = UD->getTargetDecl();
376
Douglas Gregor69d993a2009-01-17 01:13:24 +0000377 Result.StoredKind = SingleDecl;
Douglas Gregor516ff432009-04-24 02:57:34 +0000378 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000379 Result.Last = 0;
380 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000381}
382
Douglas Gregor69d993a2009-01-17 01:13:24 +0000383Sema::LookupResult
384Sema::LookupResult::CreateLookupResult(ASTContext &Context,
385 DeclContext::lookup_iterator F,
386 DeclContext::lookup_iterator L) {
387 LookupResult Result;
388 Result.Context = &Context;
389
Douglas Gregore53060f2009-06-25 22:08:12 +0000390 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor7176fff2009-01-15 00:26:24 +0000391 DeclContext::lookup_iterator Next = F;
392 ++Next;
Douglas Gregore53060f2009-06-25 22:08:12 +0000393 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000394 Result.StoredKind = OverloadedDeclFromDeclContext;
395 Result.First = reinterpret_cast<uintptr_t>(F);
396 Result.Last = reinterpret_cast<uintptr_t>(L);
397 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000398 }
399 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000400
401 Decl *D = *F;
402 if (ObjCCompatibleAliasDecl *Alias
403 = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
404 D = Alias->getClassInterface();
Anders Carlsson5e505692009-06-26 05:14:36 +0000405 if (UsingDecl *UD = dyn_cast_or_null<UsingDecl>(D))
406 D = UD->getTargetDecl();
407
Douglas Gregor69d993a2009-01-17 01:13:24 +0000408 Result.StoredKind = SingleDecl;
Douglas Gregor516ff432009-04-24 02:57:34 +0000409 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000410 Result.Last = 0;
411 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000412}
413
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000414/// @brief Determine the result of name lookup.
415Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
416 switch (StoredKind) {
417 case SingleDecl:
418 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
419
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000420 case OverloadedDeclSingleDecl:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000421 case OverloadedDeclFromIdResolver:
422 case OverloadedDeclFromDeclContext:
423 return FoundOverloaded;
424
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000425 case AmbiguousLookupStoresBasePaths:
Douglas Gregor7176fff2009-01-15 00:26:24 +0000426 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000427
428 case AmbiguousLookupStoresDecls:
429 return AmbiguousReference;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000430 }
431
Douglas Gregor7176fff2009-01-15 00:26:24 +0000432 // We can't ever get here.
433 return NotFound;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000434}
435
436/// @brief Converts the result of name lookup into a single (possible
437/// NULL) pointer to a declaration.
438///
439/// The resulting declaration will either be the declaration we found
440/// (if only a single declaration was found), an
441/// OverloadedFunctionDecl (if an overloaded function was found), or
442/// NULL (if no declaration was found). This conversion must not be
443/// used anywhere where name lookup could result in an ambiguity.
444///
445/// The OverloadedFunctionDecl conversion is meant as a stop-gap
446/// solution, since it causes the OverloadedFunctionDecl to be
447/// leaked. FIXME: Eventually, there will be a better way to iterate
448/// over the set of overloaded functions returned by name lookup.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000449NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000450 switch (StoredKind) {
451 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000452 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000453
454 case OverloadedDeclFromIdResolver:
455 return MaybeConstructOverloadSet(*Context,
456 IdentifierResolver::iterator::getFromOpaqueValue(First),
457 IdentifierResolver::iterator::getFromOpaqueValue(Last));
458
459 case OverloadedDeclFromDeclContext:
460 return MaybeConstructOverloadSet(*Context,
461 reinterpret_cast<DeclContext::lookup_iterator>(First),
462 reinterpret_cast<DeclContext::lookup_iterator>(Last));
463
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000464 case OverloadedDeclSingleDecl:
465 return reinterpret_cast<OverloadedFunctionDecl*>(First);
466
467 case AmbiguousLookupStoresDecls:
468 case AmbiguousLookupStoresBasePaths:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000469 assert(false &&
470 "Name lookup returned an ambiguity that could not be handled");
471 break;
472 }
473
474 return 0;
475}
476
Douglas Gregor7176fff2009-01-15 00:26:24 +0000477/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000478/// name lookup, or null.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000479BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000480 if (StoredKind == AmbiguousLookupStoresBasePaths)
481 return reinterpret_cast<BasePaths *>(First);
482 return 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000483}
484
Douglas Gregord8635172009-02-02 21:35:47 +0000485Sema::LookupResult::iterator::reference
486Sema::LookupResult::iterator::operator*() const {
487 switch (Result->StoredKind) {
488 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000489 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000490
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000491 case OverloadedDeclSingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000492 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000493
Douglas Gregord8635172009-02-02 21:35:47 +0000494 case OverloadedDeclFromIdResolver:
495 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
496
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000497 case AmbiguousLookupStoresBasePaths:
Douglas Gregor31a19b62009-04-01 21:51:26 +0000498 if (Result->Last)
499 return *reinterpret_cast<NamedDecl**>(Current);
500
501 // Fall through to handle the DeclContext::lookup_iterator we're
502 // storing.
503
504 case OverloadedDeclFromDeclContext:
505 case AmbiguousLookupStoresDecls:
506 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000507 }
508
509 return 0;
510}
511
512Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
513 switch (Result->StoredKind) {
514 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000515 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregord8635172009-02-02 21:35:47 +0000516 break;
517
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000518 case OverloadedDeclSingleDecl: {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000519 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000520 ++I;
521 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000522 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000523 }
524
Douglas Gregord8635172009-02-02 21:35:47 +0000525 case OverloadedDeclFromIdResolver: {
526 IdentifierResolver::iterator I
527 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
528 ++I;
529 Current = I.getAsOpaqueValue();
530 break;
531 }
532
Douglas Gregor31a19b62009-04-01 21:51:26 +0000533 case AmbiguousLookupStoresBasePaths:
534 if (Result->Last) {
535 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
536 ++I;
537 Current = reinterpret_cast<uintptr_t>(I);
538 break;
539 }
540 // Fall through to handle the DeclContext::lookup_iterator we're
541 // storing.
542
543 case OverloadedDeclFromDeclContext:
544 case AmbiguousLookupStoresDecls: {
Douglas Gregord8635172009-02-02 21:35:47 +0000545 DeclContext::lookup_iterator I
546 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
547 ++I;
548 Current = reinterpret_cast<uintptr_t>(I);
549 break;
550 }
Douglas Gregord8635172009-02-02 21:35:47 +0000551 }
552
553 return *this;
554}
555
556Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregor31a19b62009-04-01 21:51:26 +0000557 switch (StoredKind) {
558 case SingleDecl:
559 case OverloadedDeclFromIdResolver:
560 case OverloadedDeclFromDeclContext:
561 case AmbiguousLookupStoresDecls:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000562 return iterator(this, First);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000563
564 case OverloadedDeclSingleDecl: {
565 OverloadedFunctionDecl * Ovl =
566 reinterpret_cast<OverloadedFunctionDecl*>(First);
567 return iterator(this,
568 reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
569 }
570
571 case AmbiguousLookupStoresBasePaths:
572 if (Last)
573 return iterator(this,
574 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin()));
575 else
576 return iterator(this,
577 reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first));
578 }
579
580 // Required to suppress GCC warning.
581 return iterator();
Douglas Gregord8635172009-02-02 21:35:47 +0000582}
583
584Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregor31a19b62009-04-01 21:51:26 +0000585 switch (StoredKind) {
586 case SingleDecl:
587 case OverloadedDeclFromIdResolver:
588 case OverloadedDeclFromDeclContext:
589 case AmbiguousLookupStoresDecls:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000590 return iterator(this, Last);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000591
592 case OverloadedDeclSingleDecl: {
593 OverloadedFunctionDecl * Ovl =
594 reinterpret_cast<OverloadedFunctionDecl*>(First);
595 return iterator(this,
596 reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
597 }
598
599 case AmbiguousLookupStoresBasePaths:
600 if (Last)
601 return iterator(this,
602 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end()));
603 else
604 return iterator(this, reinterpret_cast<uintptr_t>(
605 getBasePaths()->front().Decls.second));
606 }
607
608 // Required to suppress GCC warning.
609 return iterator();
610}
611
612void Sema::LookupResult::Destroy() {
613 if (BasePaths *Paths = getBasePaths())
614 delete Paths;
615 else if (getKind() == AmbiguousReference)
616 delete[] reinterpret_cast<NamedDecl **>(First);
Douglas Gregord8635172009-02-02 21:35:47 +0000617}
618
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000619static void
620CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
621 DeclarationName Name, Sema::LookupNameKind NameKind,
622 unsigned IDNS, LookupResultsTy &Results,
623 UsingDirectivesTy *UDirs = 0) {
624
625 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
626
627 // Perform qualified name lookup into the LookupCtx.
628 DeclContext::lookup_iterator I, E;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000629 for (llvm::tie(I, E) = NS->lookup(Context, Name); I != E; ++I)
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000630 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
631 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
632 break;
633 }
634
635 if (UDirs) {
636 // For each UsingDirectiveDecl, which common ancestor is equal
637 // to NS, we preform qualified name lookup into namespace nominated by it.
638 UsingDirectivesTy::const_iterator UI, UEnd;
639 llvm::tie(UI, UEnd) =
640 std::equal_range(UDirs->begin(), UDirs->end(), NS,
641 UsingDirAncestorCompare());
642
643 for (; UI != UEnd; ++UI)
644 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
645 Name, NameKind, IDNS, Results);
646 }
647}
648
649static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000650 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000651 return Ctx->isFileContext();
652 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000653}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000654
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000655std::pair<bool, Sema::LookupResult>
656Sema::CppLookupName(Scope *S, DeclarationName Name,
657 LookupNameKind NameKind, bool RedeclarationOnly) {
658 assert(getLangOptions().CPlusPlus &&
659 "Can perform only C++ lookup");
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000660 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000661 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000662 Scope *Initial = S;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000663 DeclContext *OutOfLineCtx = 0;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000664 IdentifierResolver::iterator
665 I = IdResolver.begin(Name),
666 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000667
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000668 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000669 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-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.
673 // [Note: in this context, “contains” means “contains directly or
674 // indirectly”.
675 //
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 Gregor47b9a1c2009-02-04 17:27:36 +0000685 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000686 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000687 // Check whether the IdResolver has anything in this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000688 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-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 Lattnerb28317a2009-03-28 19:18:32 +0000696 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor2a3009a2009-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 Gregor7dda67d2009-02-05 19:25:20 +0000704 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
705 LookupResult R;
706 // Perform member lookup into struct.
Mike Stump390b4cc2009-05-16 07:39:55 +0000707 // FIXME: In some cases, we know that every name that could be found by
708 // this qualified name lookup will also be on the identifier chain. For
709 // example, inside a class without any base classes, we never need to
710 // perform qualified lookup because all of the members are on top of the
711 // identifier chain.
Douglas Gregor551f48c2009-03-27 04:21:56 +0000712 if (isa<RecordDecl>(Ctx)) {
713 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000714 if (R)
Douglas Gregor551f48c2009-03-27 04:21:56 +0000715 return std::make_pair(true, R);
716 }
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000717 if (Ctx->getParent() != Ctx->getLexicalParent()
718 || isa<CXXMethodDecl>(Ctx)) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000719 // It is out of line defined C++ method or struct, we continue
720 // doing name lookup in parent context. Once we will find namespace
721 // or translation-unit we save it for possible checking
722 // using-directives later.
723 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
724 OutOfLineCtx = OutOfLineCtx->getParent()) {
Douglas Gregor551f48c2009-03-27 04:21:56 +0000725 R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000726 if (R)
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000727 return std::make_pair(true, R);
728 }
729 }
730 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000731 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000732
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000733 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000734 // nominated namespaces by those using-directives.
Mike Stump390b4cc2009-05-16 07:39:55 +0000735 // UsingDirectives are pushed to heap, in common ancestor pointer value order.
736 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
737 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000738 UsingDirectivesTy UDirs;
739 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000740 if (SC->getFlags() & Scope::DeclScope)
Douglas Gregor6ab35242009-04-09 21:40:53 +0000741 AddScopeUsingDirectives(Context, SC, UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000742
743 // Sort heapified UsingDirectiveDecls.
Douglas Gregorb738e082009-05-18 22:06:54 +0000744 std::sort_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000745
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000746 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000747 // Unqualified name lookup in C++ requires looking into scopes
748 // that aren't strictly lexical, and therefore we walk through the
749 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000750
751 LookupResultsTy LookupResults;
Sebastian Redl22460502009-02-07 00:15:38 +0000752 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000753 "We should have been looking only at file context here already.");
754 bool LookedInCtx = false;
755 LookupResult Result;
756 while (OutOfLineCtx &&
757 OutOfLineCtx != S->getEntity() &&
758 OutOfLineCtx->isNamespace()) {
759 LookedInCtx = true;
760
761 // Look into context considering using-directives.
762 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
763 LookupResults, &UDirs);
764
765 if ((Result = MergeLookupResults(Context, LookupResults)) ||
766 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
767 return std::make_pair(true, Result);
768
769 OutOfLineCtx = OutOfLineCtx->getParent();
770 }
771
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000772 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000773 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
774 assert(Ctx && Ctx->isFileContext() &&
775 "We should have been looking only at file context here already.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000776
777 // Check whether the IdResolver has anything in this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000778 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000779 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
780 // We found something. Look for anything else in our scope
781 // with this same name and in an acceptable identifier
782 // namespace, so that we can construct an overload set if we
783 // need to.
784 IdentifierResolver::iterator LastI = I;
785 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000786 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000787 break;
788 }
789
790 // We store name lookup result, and continue trying to look into
791 // associated context, and maybe namespaces nominated by
792 // using-directives.
793 LookupResults.push_back(
794 LookupResult::CreateLookupResult(Context, I, LastI));
795 break;
796 }
797 }
798
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000799 LookedInCtx = true;
800 // Look into context considering using-directives.
801 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
802 LookupResults, &UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000803
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000804 if ((Result = MergeLookupResults(Context, LookupResults)) ||
805 (RedeclarationOnly && !Ctx->isTransparentContext()))
806 return std::make_pair(true, Result);
807 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000808
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000809 if (!(LookedInCtx || LookupResults.empty())) {
810 // We didn't Performed lookup in Scope entity, so we return
811 // result form IdentifierResolver.
812 assert((LookupResults.size() == 1) && "Wrong size!");
813 return std::make_pair(true, LookupResults.front());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000814 }
815 return std::make_pair(false, LookupResult());
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000816}
817
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000818/// @brief Perform unqualified name lookup starting from a given
819/// scope.
820///
821/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
822/// used to find names within the current scope. For example, 'x' in
823/// @code
824/// int x;
825/// int f() {
826/// return x; // unqualified name look finds 'x' in the global scope
827/// }
828/// @endcode
829///
830/// Different lookup criteria can find different names. For example, a
831/// particular scope can have both a struct and a function of the same
832/// name, and each can be found by certain lookup criteria. For more
833/// information about lookup criteria, see the documentation for the
834/// class LookupCriteria.
835///
836/// @param S The scope from which unqualified name lookup will
837/// begin. If the lookup criteria permits, name lookup may also search
838/// in the parent scopes.
839///
840/// @param Name The name of the entity that we are searching for.
841///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000842/// @param Loc If provided, the source location where we're performing
843/// name lookup. At present, this is only used to produce diagnostics when
844/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000845///
846/// @returns The result of name lookup, which includes zero or more
847/// declarations and possibly additional information used to diagnose
848/// ambiguities.
849Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000850Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000851 bool RedeclarationOnly, bool AllowBuiltinCreation,
852 SourceLocation Loc) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000853 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000854
855 if (!getLangOptions().CPlusPlus) {
856 // Unqualified name lookup in C/Objective-C is purely lexical, so
857 // search in the declarations attached to the name.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000858 unsigned IDNS = 0;
859 switch (NameKind) {
860 case Sema::LookupOrdinaryName:
861 IDNS = Decl::IDNS_Ordinary;
862 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000863
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000864 case Sema::LookupTagName:
865 IDNS = Decl::IDNS_Tag;
866 break;
867
868 case Sema::LookupMemberName:
869 IDNS = Decl::IDNS_Member;
870 break;
871
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000872 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000873 case Sema::LookupNestedNameSpecifierName:
874 case Sema::LookupNamespaceName:
875 assert(false && "C does not perform these kinds of name lookup");
876 break;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000877
878 case Sema::LookupRedeclarationWithLinkage:
879 // Find the nearest non-transparent declaration scope.
880 while (!(S->getFlags() & Scope::DeclScope) ||
881 (S->getEntity() &&
882 static_cast<DeclContext *>(S->getEntity())
883 ->isTransparentContext()))
884 S = S->getParent();
885 IDNS = Decl::IDNS_Ordinary;
886 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000887
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000888 case Sema::LookupObjCProtocolName:
889 IDNS = Decl::IDNS_ObjCProtocol;
890 break;
891
892 case Sema::LookupObjCImplementationName:
893 IDNS = Decl::IDNS_ObjCImplementation;
894 break;
895
896 case Sema::LookupObjCCategoryImplName:
897 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000898 break;
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000899 }
900
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000901 // Scan up the scope chain looking for a decl that matches this
902 // identifier that is in the appropriate namespace. This search
903 // should not take long, as shadowing of names is uncommon, and
904 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000905 bool LeftStartingScope = false;
906
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000907 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
908 IEnd = IdResolver.end();
909 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000910 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000911 if (NameKind == LookupRedeclarationWithLinkage) {
912 // Determine whether this (or a previous) declaration is
913 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000914 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000915 LeftStartingScope = true;
916
917 // If we found something outside of our starting scope that
918 // does not have linkage, skip it.
919 if (LeftStartingScope && !((*I)->hasLinkage()))
920 continue;
921 }
922
Douglas Gregor68584ed2009-06-18 16:11:24 +0000923 if ((*I)->getAttr<OverloadableAttr>(Context)) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000924 // If this declaration has the "overloadable" attribute, we
925 // might have a set of overloaded functions.
926
927 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000928 while (!(S->getFlags() & Scope::DeclScope) ||
929 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000930 S = S->getParent();
931
932 // Find the last declaration in this scope (with the same
933 // name, naturally).
934 IdentifierResolver::iterator LastI = I;
935 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000936 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000937 break;
938 }
939
940 return LookupResult::CreateLookupResult(Context, I, LastI);
941 }
942
943 // We have a single lookup result.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000944 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000945 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000946 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000947 // Perform C++ unqualified name lookup.
948 std::pair<bool, LookupResult> MaybeResult =
949 CppLookupName(S, Name, NameKind, RedeclarationOnly);
950 if (MaybeResult.first)
951 return MaybeResult.second;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000952 }
953
954 // If we didn't find a use of this identifier, and if the identifier
955 // corresponds to a compiler builtin, create the decl object for the builtin
956 // now, injecting it into translation unit scope, and return it.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000957 if (NameKind == LookupOrdinaryName ||
958 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000959 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000960 if (II && AllowBuiltinCreation) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000961 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor3e41d602009-02-13 23:20:09 +0000962 if (unsigned BuiltinID = II->getBuiltinID()) {
963 // In C++, we don't have any predefined library functions like
964 // 'malloc'. Instead, we'll just error.
965 if (getLangOptions().CPlusPlus &&
966 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
967 return LookupResult::CreateLookupResult(Context, 0);
968
Douglas Gregor69d993a2009-01-17 01:13:24 +0000969 return LookupResult::CreateLookupResult(Context,
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000970 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000971 S, RedeclarationOnly, Loc));
972 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000973 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000974 }
Douglas Gregor69d993a2009-01-17 01:13:24 +0000975 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000976}
977
978/// @brief Perform qualified name lookup into a given context.
979///
980/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
981/// names when the context of those names is explicit specified, e.g.,
982/// "std::vector" or "x->member".
983///
984/// Different lookup criteria can find different names. For example, a
985/// particular scope can have both a struct and a function of the same
986/// name, and each can be found by certain lookup criteria. For more
987/// information about lookup criteria, see the documentation for the
988/// class LookupCriteria.
989///
990/// @param LookupCtx The context in which qualified name lookup will
991/// search. If the lookup criteria permits, name lookup may also search
992/// in the parent contexts or (for C++ classes) base classes.
993///
994/// @param Name The name of the entity that we are searching for.
995///
996/// @param Criteria The criteria that this routine will use to
997/// determine which names are visible and which names will be
998/// found. Note that name lookup will find a name that is visible by
999/// the given criteria, but the entity itself may not be semantically
1000/// correct or even the kind of entity expected based on the
1001/// lookup. For example, searching for a nested-name-specifier name
1002/// might result in an EnumDecl, which is visible but is not permitted
1003/// as a nested-name-specifier in C++03.
1004///
1005/// @returns The result of name lookup, which includes zero or more
1006/// declarations and possibly additional information used to diagnose
1007/// ambiguities.
1008Sema::LookupResult
1009Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001010 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001011 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1012
Douglas Gregor69d993a2009-01-17 01:13:24 +00001013 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001014
1015 // If we're performing qualified name lookup (e.g., lookup into a
1016 // struct), find fields as part of ordinary name lookup.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001017 unsigned IDNS
1018 = getIdentifierNamespacesFromLookupNameKind(NameKind,
1019 getLangOptions().CPlusPlus);
1020 if (NameKind == LookupOrdinaryName)
1021 IDNS |= Decl::IDNS_Member;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001022
1023 // Perform qualified name lookup into the LookupCtx.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001024 DeclContext::lookup_iterator I, E;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001025 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001026 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001027 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001028
Douglas Gregor7176fff2009-01-15 00:26:24 +00001029 // If this isn't a C++ class or we aren't allowed to look into base
1030 // classes, we're done.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001031 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001032 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001033
1034 // Perform lookup into our base classes.
1035 BasePaths Paths;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001036 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor7176fff2009-01-15 00:26:24 +00001037
1038 // Look for this member in our base classes
1039 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001040 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001041 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001042
1043 // C++ [class.member.lookup]p2:
1044 // [...] If the resulting set of declarations are not all from
1045 // sub-objects of the same type, or the set has a nonstatic member
1046 // and includes members from distinct sub-objects, there is an
1047 // ambiguity and the program is ill-formed. Otherwise that set is
1048 // the result of the lookup.
1049 // FIXME: support using declarations!
1050 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001051 int SubobjectNumber = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001052 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1053 Path != PathEnd; ++Path) {
1054 const BasePathElement &PathElement = Path->back();
1055
1056 // Determine whether we're looking at a distinct sub-object or not.
1057 if (SubobjectType.isNull()) {
1058 // This is the first subobject we've looked at. Record it's type.
1059 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1060 SubobjectNumber = PathElement.SubobjectNumber;
1061 } else if (SubobjectType
1062 != Context.getCanonicalType(PathElement.Base->getType())) {
1063 // We found members of the given name in two subobjects of
1064 // different types. This lookup is ambiguous.
1065 BasePaths *PathsOnHeap = new BasePaths;
1066 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +00001067 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001068 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1069 // We have a different subobject of the same type.
1070
1071 // C++ [class.member.lookup]p5:
1072 // A static member, a nested type or an enumerator defined in
1073 // a base class T can unambiguously be found even if an object
1074 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001075 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001076 if (isa<VarDecl>(FirstDecl) ||
1077 isa<TypeDecl>(FirstDecl) ||
1078 isa<EnumConstantDecl>(FirstDecl))
1079 continue;
1080
1081 if (isa<CXXMethodDecl>(FirstDecl)) {
1082 // Determine whether all of the methods are static.
1083 bool AllMethodsAreStatic = true;
1084 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1085 Func != Path->Decls.second; ++Func) {
1086 if (!isa<CXXMethodDecl>(*Func)) {
1087 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1088 break;
1089 }
1090
1091 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1092 AllMethodsAreStatic = false;
1093 break;
1094 }
1095 }
1096
1097 if (AllMethodsAreStatic)
1098 continue;
1099 }
1100
1101 // We have found a nonstatic member name in multiple, distinct
1102 // subobjects. Name lookup is ambiguous.
1103 BasePaths *PathsOnHeap = new BasePaths;
1104 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +00001105 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001106 }
1107 }
1108
1109 // Lookup in a base class succeeded; return these results.
1110
1111 // If we found a function declaration, return an overload set.
Douglas Gregore53060f2009-06-25 22:08:12 +00001112 if ((*Paths.front().Decls.first)->isFunctionOrFunctionTemplate())
Douglas Gregor69d993a2009-01-17 01:13:24 +00001113 return LookupResult::CreateLookupResult(Context,
Douglas Gregor7176fff2009-01-15 00:26:24 +00001114 Paths.front().Decls.first, Paths.front().Decls.second);
1115
1116 // We found a non-function declaration; return a single declaration.
Douglas Gregor69d993a2009-01-17 01:13:24 +00001117 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001118}
1119
1120/// @brief Performs name lookup for a name that was parsed in the
1121/// source code, and may contain a C++ scope specifier.
1122///
1123/// This routine is a convenience routine meant to be called from
1124/// contexts that receive a name and an optional C++ scope specifier
1125/// (e.g., "N::M::x"). It will then perform either qualified or
1126/// unqualified name lookup (with LookupQualifiedName or LookupName,
1127/// respectively) on the given name and return those results.
1128///
1129/// @param S The scope from which unqualified name lookup will
1130/// begin.
1131///
1132/// @param SS An optional C++ scope-specified, e.g., "::N::M".
1133///
1134/// @param Name The name of the entity that name lookup will
1135/// search for.
1136///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001137/// @param Loc If provided, the source location where we're performing
1138/// name lookup. At present, this is only used to produce diagnostics when
1139/// C library functions (like "malloc") are implicitly declared.
1140///
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001141/// @returns The result of qualified or unqualified name lookup.
1142Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001143Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1144 DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001145 bool RedeclarationOnly, bool AllowBuiltinCreation,
1146 SourceLocation Loc) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00001147 if (SS && (SS->isSet() || SS->isInvalid())) {
1148 // If the scope specifier is invalid, don't even look for
1149 // anything.
1150 if (SS->isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001151 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001152
Douglas Gregor42af25f2009-05-11 19:58:34 +00001153 assert(!isUnknownSpecialization(*SS) && "Can't lookup dependent types");
1154
1155 if (isDependentScopeSpecifier(*SS)) {
1156 // Determine whether we are looking into the current
1157 // instantiation.
1158 NestedNameSpecifier *NNS
1159 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1160 CXXRecordDecl *Current = getCurrentInstantiationOf(NNS);
1161 assert(Current && "Bad dependent scope specifier");
1162
1163 // We nested name specifier refers to the current instantiation,
1164 // so now we will look for a member of the current instantiation
1165 // (C++0x [temp.dep.type]).
1166 unsigned IDNS = getIdentifierNamespacesFromLookupNameKind(NameKind, true);
1167 DeclContext::lookup_iterator I, E;
1168 for (llvm::tie(I, E) = Current->lookup(Context, Name); I != E; ++I)
1169 if (isAcceptableLookupResult(*I, NameKind, IDNS))
1170 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001171 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001172
1173 if (RequireCompleteDeclContext(*SS))
1174 return LookupResult::CreateLookupResult(Context, 0);
1175
1176 return LookupQualifiedName(computeDeclContext(*SS),
1177 Name, NameKind, RedeclarationOnly);
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001178 }
1179
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001180 LookupResult result(LookupName(S, Name, NameKind, RedeclarationOnly,
1181 AllowBuiltinCreation, Loc));
1182
1183 return(result);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001184}
1185
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001186
Douglas Gregor7176fff2009-01-15 00:26:24 +00001187/// @brief Produce a diagnostic describing the ambiguity that resulted
1188/// from name lookup.
1189///
1190/// @param Result The ambiguous name lookup result.
1191///
1192/// @param Name The name of the entity that name lookup was
1193/// searching for.
1194///
1195/// @param NameLoc The location of the name within the source code.
1196///
1197/// @param LookupRange A source range that provides more
1198/// source-location information concerning the lookup itself. For
1199/// example, this range might highlight a nested-name-specifier that
1200/// precedes the name.
1201///
1202/// @returns true
1203bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1204 SourceLocation NameLoc,
1205 SourceRange LookupRange) {
1206 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1207
Douglas Gregor31a19b62009-04-01 21:51:26 +00001208 if (BasePaths *Paths = Result.getBasePaths()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001209 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1210 QualType SubobjectType = Paths->front().back().Base->getType();
1211 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1212 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1213 << LookupRange;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001214
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001215 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
Douglas Gregor31a19b62009-04-01 21:51:26 +00001216 while (isa<CXXMethodDecl>(*Found) &&
1217 cast<CXXMethodDecl>(*Found)->isStatic())
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001218 ++Found;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001219
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001220 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1221
Douglas Gregor31a19b62009-04-01 21:51:26 +00001222 Result.Destroy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001223 return true;
1224 }
1225
1226 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1227 "Unhandled form of name lookup ambiguity");
1228
1229 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1230 << Name << LookupRange;
1231
1232 std::set<Decl *> DeclsPrinted;
1233 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1234 Path != PathEnd; ++Path) {
1235 Decl *D = *Path->Decls.first;
1236 if (DeclsPrinted.insert(D).second)
1237 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1238 }
1239
Douglas Gregor31a19b62009-04-01 21:51:26 +00001240 Result.Destroy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001241 return true;
1242 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001243 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1244
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001245 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
Douglas Gregor31a19b62009-04-01 21:51:26 +00001246 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001247
Chris Lattner48458d22009-02-03 21:29:32 +00001248 for (; DI != DEnd; ++DI)
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001249 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001250
Douglas Gregor31a19b62009-04-01 21:51:26 +00001251 Result.Destroy();
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001252 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001253 }
1254
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001255 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregor69d993a2009-01-17 01:13:24 +00001256
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001257 // We can't reach here.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001258 return true;
1259}
Douglas Gregorfa047642009-02-04 00:32:51 +00001260
1261// \brief Add the associated classes and namespaces for
1262// argument-dependent lookup with an argument of class type
1263// (C++ [basic.lookup.koenig]p2).
1264static void
1265addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1266 ASTContext &Context,
1267 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001268 Sema::AssociatedClassSet &AssociatedClasses,
1269 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001270 // C++ [basic.lookup.koenig]p2:
1271 // [...]
1272 // -- If T is a class type (including unions), its associated
1273 // classes are: the class itself; the class of which it is a
1274 // member, if any; and its direct and indirect base
1275 // classes. Its associated namespaces are the namespaces in
1276 // which its associated classes are defined.
1277
1278 // Add the class of which it is a member, if any.
1279 DeclContext *Ctx = Class->getDeclContext();
1280 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1281 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001282 // Add the associated namespace for this class.
1283 while (Ctx->isRecord())
1284 Ctx = Ctx->getParent();
1285 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1286 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001287 else if (Ctx->isTranslationUnit())
1288 GlobalScope = true;
1289
Douglas Gregorfa047642009-02-04 00:32:51 +00001290 // Add the class itself. If we've already seen this class, we don't
1291 // need to visit base classes.
1292 if (!AssociatedClasses.insert(Class))
1293 return;
1294
1295 // FIXME: Handle class template specializations
1296
1297 // Add direct and indirect base classes along with their associated
1298 // namespaces.
1299 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1300 Bases.push_back(Class);
1301 while (!Bases.empty()) {
1302 // Pop this class off the stack.
1303 Class = Bases.back();
1304 Bases.pop_back();
1305
1306 // Visit the base classes.
1307 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1308 BaseEnd = Class->bases_end();
1309 Base != BaseEnd; ++Base) {
1310 const RecordType *BaseType = Base->getType()->getAsRecordType();
1311 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1312 if (AssociatedClasses.insert(BaseDecl)) {
1313 // Find the associated namespace for this base class.
1314 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1315 while (BaseCtx->isRecord())
1316 BaseCtx = BaseCtx->getParent();
1317 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1318 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001319 else if (BaseCtx->isTranslationUnit())
1320 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001321
1322 // Make sure we visit the bases of this base class.
1323 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1324 Bases.push_back(BaseDecl);
1325 }
1326 }
1327 }
1328}
1329
1330// \brief Add the associated classes and namespaces for
1331// argument-dependent lookup with an argument of type T
1332// (C++ [basic.lookup.koenig]p2).
1333static void
1334addAssociatedClassesAndNamespaces(QualType T,
1335 ASTContext &Context,
1336 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001337 Sema::AssociatedClassSet &AssociatedClasses,
1338 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001339 // C++ [basic.lookup.koenig]p2:
1340 //
1341 // For each argument type T in the function call, there is a set
1342 // of zero or more associated namespaces and a set of zero or more
1343 // associated classes to be considered. The sets of namespaces and
1344 // classes is determined entirely by the types of the function
1345 // arguments (and the namespace of any template template
1346 // argument). Typedef names and using-declarations used to specify
1347 // the types do not contribute to this set. The sets of namespaces
1348 // and classes are determined in the following way:
1349 T = Context.getCanonicalType(T).getUnqualifiedType();
1350
1351 // -- If T is a pointer to U or an array of U, its associated
1352 // namespaces and classes are those associated with U.
1353 //
1354 // We handle this by unwrapping pointer and array types immediately,
1355 // to avoid unnecessary recursion.
1356 while (true) {
1357 if (const PointerType *Ptr = T->getAsPointerType())
1358 T = Ptr->getPointeeType();
1359 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1360 T = Ptr->getElementType();
1361 else
1362 break;
1363 }
1364
1365 // -- If T is a fundamental type, its associated sets of
1366 // namespaces and classes are both empty.
1367 if (T->getAsBuiltinType())
1368 return;
1369
1370 // -- If T is a class type (including unions), its associated
1371 // classes are: the class itself; the class of which it is a
1372 // member, if any; and its direct and indirect base
1373 // classes. Its associated namespaces are the namespaces in
1374 // which its associated classes are defined.
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001375 if (const RecordType *ClassType = T->getAsRecordType())
1376 if (CXXRecordDecl *ClassDecl
1377 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1378 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1379 AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001380 AssociatedClasses,
1381 GlobalScope);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001382 return;
1383 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001384
1385 // -- If T is an enumeration type, its associated namespace is
1386 // the namespace in which it is defined. If it is class
1387 // member, its associated class is the member’s class; else
1388 // it has no associated class.
1389 if (const EnumType *EnumT = T->getAsEnumType()) {
1390 EnumDecl *Enum = EnumT->getDecl();
1391
1392 DeclContext *Ctx = Enum->getDeclContext();
1393 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1394 AssociatedClasses.insert(EnclosingClass);
1395
1396 // Add the associated namespace for this class.
1397 while (Ctx->isRecord())
1398 Ctx = Ctx->getParent();
1399 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1400 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001401 else if (Ctx->isTranslationUnit())
1402 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001403
1404 return;
1405 }
1406
1407 // -- If T is a function type, its associated namespaces and
1408 // classes are those associated with the function parameter
1409 // types and those associated with the return type.
1410 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1411 // Return type
1412 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1413 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001414 AssociatedNamespaces, AssociatedClasses,
1415 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001416
Douglas Gregor72564e72009-02-26 23:50:07 +00001417 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001418 if (!Proto)
1419 return;
1420
1421 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001422 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001423 ArgEnd = Proto->arg_type_end();
1424 Arg != ArgEnd; ++Arg)
1425 addAssociatedClassesAndNamespaces(*Arg, Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001426 AssociatedNamespaces, AssociatedClasses,
1427 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001428
1429 return;
1430 }
1431
1432 // -- If T is a pointer to a member function of a class X, its
1433 // associated namespaces and classes are those associated
1434 // with the function parameter types and return type,
1435 // together with those associated with X.
1436 //
1437 // -- If T is a pointer to a data member of class X, its
1438 // associated namespaces and classes are those associated
1439 // with the member type together with those associated with
1440 // X.
1441 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1442 // Handle the type that the pointer to member points to.
1443 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1444 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001445 AssociatedNamespaces, AssociatedClasses,
1446 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001447
1448 // Handle the class type into which this points.
1449 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1450 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1451 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001452 AssociatedNamespaces, AssociatedClasses,
1453 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001454
1455 return;
1456 }
1457
1458 // FIXME: What about block pointers?
1459 // FIXME: What about Objective-C message sends?
1460}
1461
1462/// \brief Find the associated classes and namespaces for
1463/// argument-dependent lookup for a call with the given set of
1464/// arguments.
1465///
1466/// This routine computes the sets of associated classes and associated
1467/// namespaces searched by argument-dependent lookup
1468/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1469void
1470Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1471 AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001472 AssociatedClassSet &AssociatedClasses,
1473 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001474 AssociatedNamespaces.clear();
1475 AssociatedClasses.clear();
1476
1477 // C++ [basic.lookup.koenig]p2:
1478 // For each argument type T in the function call, there is a set
1479 // of zero or more associated namespaces and a set of zero or more
1480 // associated classes to be considered. The sets of namespaces and
1481 // classes is determined entirely by the types of the function
1482 // arguments (and the namespace of any template template
1483 // argument).
1484 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1485 Expr *Arg = Args[ArgIdx];
1486
1487 if (Arg->getType() != Context.OverloadTy) {
1488 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001489 AssociatedNamespaces, AssociatedClasses,
1490 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001491 continue;
1492 }
1493
1494 // [...] In addition, if the argument is the name or address of a
1495 // set of overloaded functions and/or function templates, its
1496 // associated classes and namespaces are the union of those
1497 // associated with each of the members of the set: the namespace
1498 // in which the function or function template is defined and the
1499 // classes and namespaces associated with its (non-dependent)
1500 // parameter types and return type.
1501 DeclRefExpr *DRE = 0;
1502 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1503 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1504 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1505 } else
1506 DRE = dyn_cast<DeclRefExpr>(Arg);
1507 if (!DRE)
1508 continue;
1509
1510 OverloadedFunctionDecl *Ovl
1511 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1512 if (!Ovl)
1513 continue;
1514
1515 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1516 FuncEnd = Ovl->function_end();
1517 Func != FuncEnd; ++Func) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001518 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func);
1519 if (!FDecl)
1520 FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001521
1522 // Add the namespace in which this function was defined. Note
1523 // that, if this is a member function, we do *not* consider the
1524 // enclosing namespace of its class.
1525 DeclContext *Ctx = FDecl->getDeclContext();
1526 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1527 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001528 else if (Ctx->isTranslationUnit())
1529 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001530
1531 // Add the classes and namespaces associated with the parameter
1532 // types and return type of this function.
1533 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001534 AssociatedNamespaces, AssociatedClasses,
1535 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001536 }
1537 }
1538}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001539
1540/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1541/// an acceptable non-member overloaded operator for a call whose
1542/// arguments have types T1 (and, if non-empty, T2). This routine
1543/// implements the check in C++ [over.match.oper]p3b2 concerning
1544/// enumeration types.
1545static bool
1546IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1547 QualType T1, QualType T2,
1548 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001549 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1550 return true;
1551
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001552 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1553 return true;
1554
1555 const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1556 if (Proto->getNumArgs() < 1)
1557 return false;
1558
1559 if (T1->isEnumeralType()) {
1560 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1561 if (Context.getCanonicalType(T1).getUnqualifiedType()
1562 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1563 return true;
1564 }
1565
1566 if (Proto->getNumArgs() < 2)
1567 return false;
1568
1569 if (!T2.isNull() && T2->isEnumeralType()) {
1570 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1571 if (Context.getCanonicalType(T2).getUnqualifiedType()
1572 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1573 return true;
1574 }
1575
1576 return false;
1577}
1578
Douglas Gregor6e378de2009-04-23 23:18:26 +00001579/// \brief Find the protocol with the given name, if any.
1580ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001581 Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl();
Douglas Gregor6e378de2009-04-23 23:18:26 +00001582 return cast_or_null<ObjCProtocolDecl>(D);
1583}
1584
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001585/// \brief Find the Objective-C implementation with the given name, if
1586/// any.
1587ObjCImplementationDecl *Sema::LookupObjCImplementation(IdentifierInfo *II) {
1588 Decl *D = LookupName(TUScope, II, LookupObjCImplementationName).getAsDecl();
1589 return cast_or_null<ObjCImplementationDecl>(D);
1590}
1591
1592/// \brief Find the Objective-C category implementation with the given
1593/// name, if any.
1594ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
1595 Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl();
1596 return cast_or_null<ObjCCategoryImplDecl>(D);
1597}
1598
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001599void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1600 QualType T1, QualType T2,
1601 FunctionSet &Functions) {
1602 // C++ [over.match.oper]p3:
1603 // -- The set of non-member candidates is the result of the
1604 // unqualified lookup of operator@ in the context of the
1605 // expression according to the usual rules for name lookup in
1606 // unqualified function calls (3.4.2) except that all member
1607 // functions are ignored. However, if no operand has a class
1608 // type, only those non-member functions in the lookup set
1609 // that have a first parameter of type T1 or “reference to
1610 // (possibly cv-qualified) T1”, when T1 is an enumeration
1611 // type, or (if there is a right operand) a second parameter
1612 // of type T2 or “reference to (possibly cv-qualified) T2”,
1613 // when T2 is an enumeration type, are candidate functions.
1614 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1615 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1616
1617 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1618
1619 if (!Operators)
1620 return;
1621
1622 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1623 Op != OpEnd; ++Op) {
1624 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
1625 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1626 Functions.insert(FD); // FIXME: canonical FD
1627 }
1628}
1629
1630void Sema::ArgumentDependentLookup(DeclarationName Name,
1631 Expr **Args, unsigned NumArgs,
1632 FunctionSet &Functions) {
1633 // Find all of the associated namespaces and classes based on the
1634 // arguments we have.
1635 AssociatedNamespaceSet AssociatedNamespaces;
1636 AssociatedClassSet AssociatedClasses;
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001637 bool GlobalScope = false;
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001638 FindAssociatedClassesAndNamespaces(Args, NumArgs,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001639 AssociatedNamespaces, AssociatedClasses,
1640 GlobalScope);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001641
1642 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001643 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1644 // and let Y be the lookup set produced by argument dependent
1645 // lookup (defined as follows). If X contains [...] then Y is
1646 // empty. Otherwise Y is the set of declarations found in the
1647 // namespaces associated with the argument types as described
1648 // below. The set of declarations found by the lookup of the name
1649 // is the union of X and Y.
1650 //
1651 // Here, we compute Y and add its members to the overloaded
1652 // candidate set.
1653 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1654 NSEnd = AssociatedNamespaces.end();
1655 NS != NSEnd; ++NS) {
1656 // When considering an associated namespace, the lookup is the
1657 // same as the lookup performed when the associated namespace is
1658 // used as a qualifier (3.4.3.2) except that:
1659 //
1660 // -- Any using-directives in the associated namespace are
1661 // ignored.
1662 //
1663 // -- FIXME: Any namespace-scope friend functions declared in
1664 // associated classes are visible within their respective
1665 // namespaces even if they are not visible during an ordinary
1666 // lookup (11.4).
1667 DeclContext::lookup_iterator I, E;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001668 for (llvm::tie(I, E) = (*NS)->lookup(Context, Name); I != E; ++I) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001669 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1670 if (!Func)
1671 break;
1672
1673 Functions.insert(Func);
1674 }
1675 }
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001676
1677 if (GlobalScope) {
1678 DeclContext::lookup_iterator I, E;
1679 for (llvm::tie(I, E)
1680 = Context.getTranslationUnitDecl()->lookup(Context, Name);
1681 I != E; ++I) {
1682 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1683 if (!Func)
1684 break;
1685
1686 Functions.insert(Func);
1687 }
1688 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001689}