blob: 0d5c54530a37f3c9279c5e8fc8d2245708947946 [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());
Douglas Gregore53060f2009-06-25 22:08:12 +0000142 if (isa<FunctionDecl>(*I))
143 Ovl->addOverload(cast<FunctionDecl>(*I));
144 else
145 Ovl->addOverload(cast<FunctionTemplateDecl>(*I));
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000146 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000147
148 if (isa<FunctionDecl>(*Last))
149 Ovl->addOverload(cast<FunctionDecl>(*Last));
150 else
151 Ovl->addOverload(cast<FunctionTemplateDecl>(*Last));
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000152 }
153
154 // If we had more than one function, we built an overload
155 // set. Return it.
156 if (Ovl)
157 return Ovl;
158 }
159
160 return *I;
161}
162
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000163/// Merges together multiple LookupResults dealing with duplicated Decl's.
164static Sema::LookupResult
165MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
166 typedef Sema::LookupResult LResult;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000167 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000168
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000169 // Remove duplicated Decl pointing at same Decl, by storing them in
170 // associative collection. This might be case for code like:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000171 //
172 // namespace A { int i; }
173 // namespace B { using namespace A; }
174 // namespace C { using namespace A; }
175 //
176 // void foo() {
177 // using namespace B;
178 // using namespace C;
179 // ++i; // finds A::i, from both namespace B and C at global scope
180 // }
181 //
182 // C++ [namespace.qual].p3:
183 // The same declaration found more than once is not an ambiguity
184 // (because it is still a unique declaration).
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000185 DeclsSetTy FoundDecls;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000186
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000187 // Counter of tag names, and functions for resolving ambiguity
188 // and name hiding.
189 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000190
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000191 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
192
193 // No name lookup results, return early.
194 if (I == End) return LResult::CreateLookupResult(Context, 0);
195
196 // Keep track of the tag declaration we found. We only use this if
197 // we find a single tag declaration.
198 TagDecl *TagFound = 0;
199
200 for (; I != End; ++I) {
201 switch (I->getKind()) {
202 case LResult::NotFound:
203 assert(false &&
204 "Should be always successful name lookup result here.");
205 break;
206
207 case LResult::AmbiguousReference:
208 case LResult::AmbiguousBaseSubobjectTypes:
209 case LResult::AmbiguousBaseSubobjects:
210 assert(false && "Shouldn't get ambiguous lookup here.");
211 break;
212
213 case LResult::Found: {
214 NamedDecl *ND = I->getAsDecl();
Anders Carlssonbc13ab22009-06-26 03:54:13 +0000215 if (UsingDecl *UD = dyn_cast<UsingDecl>(ND))
216 ND = UD->getTargetDecl();
217
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000218 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
219 TagFound = Context.getCanonicalDecl(TD);
220 TagNames += FoundDecls.insert(TagFound)? 1 : 0;
Douglas Gregore53060f2009-06-25 22:08:12 +0000221 } else if (ND->isFunctionOrFunctionTemplate())
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000222 Functions += FoundDecls.insert(ND)? 1 : 0;
223 else
224 FoundDecls.insert(ND);
225 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000226 }
227
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000228 case LResult::FoundOverloaded:
229 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
230 Functions += FoundDecls.insert(*FI)? 1 : 0;
231 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000232 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000233 }
234 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
235 bool Ambiguous = false, NameHidesTags = false;
236
237 if (FoundDecls.size() == 1) {
238 // 1) Exactly one result.
239 } else if (TagNames > 1) {
240 // 2) Multiple tag names (even though they may be hidden by an
241 // object name).
242 Ambiguous = true;
243 } else if (FoundDecls.size() - TagNames == 1) {
244 // 3) Ordinary name hides (optional) tag.
245 NameHidesTags = TagFound;
246 } else if (Functions) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000247 // C++ [basic.lookup].p1:
248 // ... Name lookup may associate more than one declaration with
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000249 // a name if it finds the name to be a function name; the declarations
250 // are said to form a set of overloaded functions (13.1).
251 // Overload resolution (13.3) takes place after name lookup has succeeded.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000252 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000253 if (!OrdinaryNonFunc) {
254 // 4) Functions hide tag names.
255 NameHidesTags = TagFound;
256 } else {
257 // 5) Functions + ordinary names.
258 Ambiguous = true;
259 }
260 } else {
261 // 6) Multiple non-tag names
262 Ambiguous = true;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000263 }
264
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000265 if (Ambiguous)
266 return LResult::CreateLookupResult(Context,
267 FoundDecls.begin(), FoundDecls.size());
268 if (NameHidesTags) {
269 // There's only one tag, TagFound. Remove it.
270 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
271 FoundDecls.erase(TagFound);
272 }
273
274 // Return successful name lookup result.
275 return LResult::CreateLookupResult(Context,
276 MaybeConstructOverloadSet(Context,
277 FoundDecls.begin(),
278 FoundDecls.end()));
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000279}
280
281// Retrieve the set of identifier namespaces that correspond to a
282// specific kind of name lookup.
283inline unsigned
284getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
285 bool CPlusPlus) {
286 unsigned IDNS = 0;
287 switch (NameKind) {
288 case Sema::LookupOrdinaryName:
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000289 case Sema::LookupOperatorName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000290 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000291 IDNS = Decl::IDNS_Ordinary;
292 if (CPlusPlus)
293 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
294 break;
295
296 case Sema::LookupTagName:
297 IDNS = Decl::IDNS_Tag;
298 break;
299
300 case Sema::LookupMemberName:
301 IDNS = Decl::IDNS_Member;
302 if (CPlusPlus)
303 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
304 break;
305
306 case Sema::LookupNestedNameSpecifierName:
307 case Sema::LookupNamespaceName:
308 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
309 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000310
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000311 case Sema::LookupObjCProtocolName:
312 IDNS = Decl::IDNS_ObjCProtocol;
313 break;
314
315 case Sema::LookupObjCImplementationName:
316 IDNS = Decl::IDNS_ObjCImplementation;
317 break;
318
319 case Sema::LookupObjCCategoryImplName:
320 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000321 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000322 }
323 return IDNS;
324}
325
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000326Sema::LookupResult
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000327Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Douglas Gregor516ff432009-04-24 02:57:34 +0000328 if (ObjCCompatibleAliasDecl *Alias
329 = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
330 D = Alias->getClassInterface();
Anders Carlsson8b50d012009-06-26 03:37:05 +0000331 if (UsingDecl *UD = dyn_cast_or_null<UsingDecl>(D))
332 D = UD->getTargetDecl();
333
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000334 LookupResult Result;
335 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
336 OverloadedDeclSingleDecl : SingleDecl;
337 Result.First = reinterpret_cast<uintptr_t>(D);
338 Result.Last = 0;
339 Result.Context = &Context;
340 return Result;
341}
342
Douglas Gregor4bb64e72009-01-15 02:19:31 +0000343/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000344Sema::LookupResult
345Sema::LookupResult::CreateLookupResult(ASTContext &Context,
346 IdentifierResolver::iterator F,
347 IdentifierResolver::iterator L) {
348 LookupResult Result;
349 Result.Context = &Context;
350
Douglas Gregore53060f2009-06-25 22:08:12 +0000351 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor7176fff2009-01-15 00:26:24 +0000352 IdentifierResolver::iterator Next = F;
353 ++Next;
Douglas Gregore53060f2009-06-25 22:08:12 +0000354 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000355 Result.StoredKind = OverloadedDeclFromIdResolver;
356 Result.First = F.getAsOpaqueValue();
357 Result.Last = L.getAsOpaqueValue();
358 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000359 }
360 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000361
362 Decl *D = *F;
363 if (ObjCCompatibleAliasDecl *Alias
364 = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
365 D = Alias->getClassInterface();
Anders Carlsson8b50d012009-06-26 03:37:05 +0000366 if (UsingDecl *UD = dyn_cast_or_null<UsingDecl>(D))
367 D = UD->getTargetDecl();
368
Douglas Gregor69d993a2009-01-17 01:13:24 +0000369 Result.StoredKind = SingleDecl;
Douglas Gregor516ff432009-04-24 02:57:34 +0000370 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000371 Result.Last = 0;
372 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000373}
374
Douglas Gregor69d993a2009-01-17 01:13:24 +0000375Sema::LookupResult
376Sema::LookupResult::CreateLookupResult(ASTContext &Context,
377 DeclContext::lookup_iterator F,
378 DeclContext::lookup_iterator L) {
379 LookupResult Result;
380 Result.Context = &Context;
381
Douglas Gregore53060f2009-06-25 22:08:12 +0000382 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor7176fff2009-01-15 00:26:24 +0000383 DeclContext::lookup_iterator Next = F;
384 ++Next;
Douglas Gregore53060f2009-06-25 22:08:12 +0000385 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000386 Result.StoredKind = OverloadedDeclFromDeclContext;
387 Result.First = reinterpret_cast<uintptr_t>(F);
388 Result.Last = reinterpret_cast<uintptr_t>(L);
389 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000390 }
391 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000392
393 Decl *D = *F;
394 if (ObjCCompatibleAliasDecl *Alias
395 = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
396 D = Alias->getClassInterface();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000397
Douglas Gregor69d993a2009-01-17 01:13:24 +0000398 Result.StoredKind = SingleDecl;
Douglas Gregor516ff432009-04-24 02:57:34 +0000399 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000400 Result.Last = 0;
401 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000402}
403
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000404/// @brief Determine the result of name lookup.
405Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
406 switch (StoredKind) {
407 case SingleDecl:
408 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
409
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000410 case OverloadedDeclSingleDecl:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000411 case OverloadedDeclFromIdResolver:
412 case OverloadedDeclFromDeclContext:
413 return FoundOverloaded;
414
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000415 case AmbiguousLookupStoresBasePaths:
Douglas Gregor7176fff2009-01-15 00:26:24 +0000416 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000417
418 case AmbiguousLookupStoresDecls:
419 return AmbiguousReference;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000420 }
421
Douglas Gregor7176fff2009-01-15 00:26:24 +0000422 // We can't ever get here.
423 return NotFound;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000424}
425
426/// @brief Converts the result of name lookup into a single (possible
427/// NULL) pointer to a declaration.
428///
429/// The resulting declaration will either be the declaration we found
430/// (if only a single declaration was found), an
431/// OverloadedFunctionDecl (if an overloaded function was found), or
432/// NULL (if no declaration was found). This conversion must not be
433/// used anywhere where name lookup could result in an ambiguity.
434///
435/// The OverloadedFunctionDecl conversion is meant as a stop-gap
436/// solution, since it causes the OverloadedFunctionDecl to be
437/// leaked. FIXME: Eventually, there will be a better way to iterate
438/// over the set of overloaded functions returned by name lookup.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000439NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000440 switch (StoredKind) {
441 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000442 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000443
444 case OverloadedDeclFromIdResolver:
445 return MaybeConstructOverloadSet(*Context,
446 IdentifierResolver::iterator::getFromOpaqueValue(First),
447 IdentifierResolver::iterator::getFromOpaqueValue(Last));
448
449 case OverloadedDeclFromDeclContext:
450 return MaybeConstructOverloadSet(*Context,
451 reinterpret_cast<DeclContext::lookup_iterator>(First),
452 reinterpret_cast<DeclContext::lookup_iterator>(Last));
453
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000454 case OverloadedDeclSingleDecl:
455 return reinterpret_cast<OverloadedFunctionDecl*>(First);
456
457 case AmbiguousLookupStoresDecls:
458 case AmbiguousLookupStoresBasePaths:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000459 assert(false &&
460 "Name lookup returned an ambiguity that could not be handled");
461 break;
462 }
463
464 return 0;
465}
466
Douglas Gregor7176fff2009-01-15 00:26:24 +0000467/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000468/// name lookup, or null.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000469BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000470 if (StoredKind == AmbiguousLookupStoresBasePaths)
471 return reinterpret_cast<BasePaths *>(First);
472 return 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000473}
474
Douglas Gregord8635172009-02-02 21:35:47 +0000475Sema::LookupResult::iterator::reference
476Sema::LookupResult::iterator::operator*() const {
477 switch (Result->StoredKind) {
478 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000479 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000480
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000481 case OverloadedDeclSingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000482 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000483
Douglas Gregord8635172009-02-02 21:35:47 +0000484 case OverloadedDeclFromIdResolver:
485 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
486
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000487 case AmbiguousLookupStoresBasePaths:
Douglas Gregor31a19b62009-04-01 21:51:26 +0000488 if (Result->Last)
489 return *reinterpret_cast<NamedDecl**>(Current);
490
491 // Fall through to handle the DeclContext::lookup_iterator we're
492 // storing.
493
494 case OverloadedDeclFromDeclContext:
495 case AmbiguousLookupStoresDecls:
496 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000497 }
498
499 return 0;
500}
501
502Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
503 switch (Result->StoredKind) {
504 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000505 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregord8635172009-02-02 21:35:47 +0000506 break;
507
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000508 case OverloadedDeclSingleDecl: {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000509 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000510 ++I;
511 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000512 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000513 }
514
Douglas Gregord8635172009-02-02 21:35:47 +0000515 case OverloadedDeclFromIdResolver: {
516 IdentifierResolver::iterator I
517 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
518 ++I;
519 Current = I.getAsOpaqueValue();
520 break;
521 }
522
Douglas Gregor31a19b62009-04-01 21:51:26 +0000523 case AmbiguousLookupStoresBasePaths:
524 if (Result->Last) {
525 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
526 ++I;
527 Current = reinterpret_cast<uintptr_t>(I);
528 break;
529 }
530 // Fall through to handle the DeclContext::lookup_iterator we're
531 // storing.
532
533 case OverloadedDeclFromDeclContext:
534 case AmbiguousLookupStoresDecls: {
Douglas Gregord8635172009-02-02 21:35:47 +0000535 DeclContext::lookup_iterator I
536 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
537 ++I;
538 Current = reinterpret_cast<uintptr_t>(I);
539 break;
540 }
Douglas Gregord8635172009-02-02 21:35:47 +0000541 }
542
543 return *this;
544}
545
546Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregor31a19b62009-04-01 21:51:26 +0000547 switch (StoredKind) {
548 case SingleDecl:
549 case OverloadedDeclFromIdResolver:
550 case OverloadedDeclFromDeclContext:
551 case AmbiguousLookupStoresDecls:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000552 return iterator(this, First);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000553
554 case OverloadedDeclSingleDecl: {
555 OverloadedFunctionDecl * Ovl =
556 reinterpret_cast<OverloadedFunctionDecl*>(First);
557 return iterator(this,
558 reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
559 }
560
561 case AmbiguousLookupStoresBasePaths:
562 if (Last)
563 return iterator(this,
564 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin()));
565 else
566 return iterator(this,
567 reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first));
568 }
569
570 // Required to suppress GCC warning.
571 return iterator();
Douglas Gregord8635172009-02-02 21:35:47 +0000572}
573
574Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregor31a19b62009-04-01 21:51:26 +0000575 switch (StoredKind) {
576 case SingleDecl:
577 case OverloadedDeclFromIdResolver:
578 case OverloadedDeclFromDeclContext:
579 case AmbiguousLookupStoresDecls:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000580 return iterator(this, Last);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000581
582 case OverloadedDeclSingleDecl: {
583 OverloadedFunctionDecl * Ovl =
584 reinterpret_cast<OverloadedFunctionDecl*>(First);
585 return iterator(this,
586 reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
587 }
588
589 case AmbiguousLookupStoresBasePaths:
590 if (Last)
591 return iterator(this,
592 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end()));
593 else
594 return iterator(this, reinterpret_cast<uintptr_t>(
595 getBasePaths()->front().Decls.second));
596 }
597
598 // Required to suppress GCC warning.
599 return iterator();
600}
601
602void Sema::LookupResult::Destroy() {
603 if (BasePaths *Paths = getBasePaths())
604 delete Paths;
605 else if (getKind() == AmbiguousReference)
606 delete[] reinterpret_cast<NamedDecl **>(First);
Douglas Gregord8635172009-02-02 21:35:47 +0000607}
608
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000609static void
610CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
611 DeclarationName Name, Sema::LookupNameKind NameKind,
612 unsigned IDNS, LookupResultsTy &Results,
613 UsingDirectivesTy *UDirs = 0) {
614
615 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
616
617 // Perform qualified name lookup into the LookupCtx.
618 DeclContext::lookup_iterator I, E;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000619 for (llvm::tie(I, E) = NS->lookup(Context, Name); I != E; ++I)
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000620 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
621 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
622 break;
623 }
624
625 if (UDirs) {
626 // For each UsingDirectiveDecl, which common ancestor is equal
627 // to NS, we preform qualified name lookup into namespace nominated by it.
628 UsingDirectivesTy::const_iterator UI, UEnd;
629 llvm::tie(UI, UEnd) =
630 std::equal_range(UDirs->begin(), UDirs->end(), NS,
631 UsingDirAncestorCompare());
632
633 for (; UI != UEnd; ++UI)
634 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
635 Name, NameKind, IDNS, Results);
636 }
637}
638
639static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000640 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000641 return Ctx->isFileContext();
642 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000643}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000644
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000645std::pair<bool, Sema::LookupResult>
646Sema::CppLookupName(Scope *S, DeclarationName Name,
647 LookupNameKind NameKind, bool RedeclarationOnly) {
648 assert(getLangOptions().CPlusPlus &&
649 "Can perform only C++ lookup");
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000650 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000651 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000652 Scope *Initial = S;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000653 DeclContext *OutOfLineCtx = 0;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000654 IdentifierResolver::iterator
655 I = IdResolver.begin(Name),
656 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000657
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000658 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000659 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000660 // ...During unqualified name lookup (3.4.1), the names appear as if
661 // they were declared in the nearest enclosing namespace which contains
662 // both the using-directive and the nominated namespace.
663 // [Note: in this context, “contains” means “contains directly or
664 // indirectly”.
665 //
666 // For example:
667 // namespace A { int i; }
668 // void foo() {
669 // int i;
670 // {
671 // using namespace A;
672 // ++i; // finds local 'i', A::i appears at global scope
673 // }
674 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000675 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000676 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000677 // Check whether the IdResolver has anything in this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000678 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000679 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
680 // We found something. Look for anything else in our scope
681 // with this same name and in an acceptable identifier
682 // namespace, so that we can construct an overload set if we
683 // need to.
684 IdentifierResolver::iterator LastI = I;
685 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000686 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000687 break;
688 }
689 LookupResult Result =
690 LookupResult::CreateLookupResult(Context, I, LastI);
691 return std::make_pair(true, Result);
692 }
693 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000694 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
695 LookupResult R;
696 // Perform member lookup into struct.
Mike Stump390b4cc2009-05-16 07:39:55 +0000697 // FIXME: In some cases, we know that every name that could be found by
698 // this qualified name lookup will also be on the identifier chain. For
699 // example, inside a class without any base classes, we never need to
700 // perform qualified lookup because all of the members are on top of the
701 // identifier chain.
Douglas Gregor551f48c2009-03-27 04:21:56 +0000702 if (isa<RecordDecl>(Ctx)) {
703 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000704 if (R)
Douglas Gregor551f48c2009-03-27 04:21:56 +0000705 return std::make_pair(true, R);
706 }
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000707 if (Ctx->getParent() != Ctx->getLexicalParent()
708 || isa<CXXMethodDecl>(Ctx)) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000709 // It is out of line defined C++ method or struct, we continue
710 // doing name lookup in parent context. Once we will find namespace
711 // or translation-unit we save it for possible checking
712 // using-directives later.
713 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
714 OutOfLineCtx = OutOfLineCtx->getParent()) {
Douglas Gregor551f48c2009-03-27 04:21:56 +0000715 R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000716 if (R)
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000717 return std::make_pair(true, R);
718 }
719 }
720 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000721 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000722
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000723 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000724 // nominated namespaces by those using-directives.
Mike Stump390b4cc2009-05-16 07:39:55 +0000725 // UsingDirectives are pushed to heap, in common ancestor pointer value order.
726 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
727 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000728 UsingDirectivesTy UDirs;
729 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000730 if (SC->getFlags() & Scope::DeclScope)
Douglas Gregor6ab35242009-04-09 21:40:53 +0000731 AddScopeUsingDirectives(Context, SC, UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000732
733 // Sort heapified UsingDirectiveDecls.
Douglas Gregorb738e082009-05-18 22:06:54 +0000734 std::sort_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000735
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000736 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000737 // Unqualified name lookup in C++ requires looking into scopes
738 // that aren't strictly lexical, and therefore we walk through the
739 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000740
741 LookupResultsTy LookupResults;
Sebastian Redl22460502009-02-07 00:15:38 +0000742 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000743 "We should have been looking only at file context here already.");
744 bool LookedInCtx = false;
745 LookupResult Result;
746 while (OutOfLineCtx &&
747 OutOfLineCtx != S->getEntity() &&
748 OutOfLineCtx->isNamespace()) {
749 LookedInCtx = true;
750
751 // Look into context considering using-directives.
752 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
753 LookupResults, &UDirs);
754
755 if ((Result = MergeLookupResults(Context, LookupResults)) ||
756 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
757 return std::make_pair(true, Result);
758
759 OutOfLineCtx = OutOfLineCtx->getParent();
760 }
761
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000762 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000763 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
764 assert(Ctx && Ctx->isFileContext() &&
765 "We should have been looking only at file context here already.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000766
767 // Check whether the IdResolver has anything in this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000768 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000769 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
770 // We found something. Look for anything else in our scope
771 // with this same name and in an acceptable identifier
772 // namespace, so that we can construct an overload set if we
773 // need to.
774 IdentifierResolver::iterator LastI = I;
775 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000776 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000777 break;
778 }
779
780 // We store name lookup result, and continue trying to look into
781 // associated context, and maybe namespaces nominated by
782 // using-directives.
783 LookupResults.push_back(
784 LookupResult::CreateLookupResult(Context, I, LastI));
785 break;
786 }
787 }
788
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000789 LookedInCtx = true;
790 // Look into context considering using-directives.
791 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
792 LookupResults, &UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000793
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000794 if ((Result = MergeLookupResults(Context, LookupResults)) ||
795 (RedeclarationOnly && !Ctx->isTransparentContext()))
796 return std::make_pair(true, Result);
797 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000798
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000799 if (!(LookedInCtx || LookupResults.empty())) {
800 // We didn't Performed lookup in Scope entity, so we return
801 // result form IdentifierResolver.
802 assert((LookupResults.size() == 1) && "Wrong size!");
803 return std::make_pair(true, LookupResults.front());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000804 }
805 return std::make_pair(false, LookupResult());
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000806}
807
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000808/// @brief Perform unqualified name lookup starting from a given
809/// scope.
810///
811/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
812/// used to find names within the current scope. For example, 'x' in
813/// @code
814/// int x;
815/// int f() {
816/// return x; // unqualified name look finds 'x' in the global scope
817/// }
818/// @endcode
819///
820/// Different lookup criteria can find different names. For example, a
821/// particular scope can have both a struct and a function of the same
822/// name, and each can be found by certain lookup criteria. For more
823/// information about lookup criteria, see the documentation for the
824/// class LookupCriteria.
825///
826/// @param S The scope from which unqualified name lookup will
827/// begin. If the lookup criteria permits, name lookup may also search
828/// in the parent scopes.
829///
830/// @param Name The name of the entity that we are searching for.
831///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000832/// @param Loc If provided, the source location where we're performing
833/// name lookup. At present, this is only used to produce diagnostics when
834/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000835///
836/// @returns The result of name lookup, which includes zero or more
837/// declarations and possibly additional information used to diagnose
838/// ambiguities.
839Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000840Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000841 bool RedeclarationOnly, bool AllowBuiltinCreation,
842 SourceLocation Loc) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000843 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000844
845 if (!getLangOptions().CPlusPlus) {
846 // Unqualified name lookup in C/Objective-C is purely lexical, so
847 // search in the declarations attached to the name.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000848 unsigned IDNS = 0;
849 switch (NameKind) {
850 case Sema::LookupOrdinaryName:
851 IDNS = Decl::IDNS_Ordinary;
852 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000853
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000854 case Sema::LookupTagName:
855 IDNS = Decl::IDNS_Tag;
856 break;
857
858 case Sema::LookupMemberName:
859 IDNS = Decl::IDNS_Member;
860 break;
861
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000862 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000863 case Sema::LookupNestedNameSpecifierName:
864 case Sema::LookupNamespaceName:
865 assert(false && "C does not perform these kinds of name lookup");
866 break;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000867
868 case Sema::LookupRedeclarationWithLinkage:
869 // Find the nearest non-transparent declaration scope.
870 while (!(S->getFlags() & Scope::DeclScope) ||
871 (S->getEntity() &&
872 static_cast<DeclContext *>(S->getEntity())
873 ->isTransparentContext()))
874 S = S->getParent();
875 IDNS = Decl::IDNS_Ordinary;
876 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000877
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000878 case Sema::LookupObjCProtocolName:
879 IDNS = Decl::IDNS_ObjCProtocol;
880 break;
881
882 case Sema::LookupObjCImplementationName:
883 IDNS = Decl::IDNS_ObjCImplementation;
884 break;
885
886 case Sema::LookupObjCCategoryImplName:
887 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000888 break;
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000889 }
890
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000891 // Scan up the scope chain looking for a decl that matches this
892 // identifier that is in the appropriate namespace. This search
893 // should not take long, as shadowing of names is uncommon, and
894 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000895 bool LeftStartingScope = false;
896
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000897 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
898 IEnd = IdResolver.end();
899 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000900 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000901 if (NameKind == LookupRedeclarationWithLinkage) {
902 // Determine whether this (or a previous) declaration is
903 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000904 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000905 LeftStartingScope = true;
906
907 // If we found something outside of our starting scope that
908 // does not have linkage, skip it.
909 if (LeftStartingScope && !((*I)->hasLinkage()))
910 continue;
911 }
912
Douglas Gregor68584ed2009-06-18 16:11:24 +0000913 if ((*I)->getAttr<OverloadableAttr>(Context)) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000914 // If this declaration has the "overloadable" attribute, we
915 // might have a set of overloaded functions.
916
917 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000918 while (!(S->getFlags() & Scope::DeclScope) ||
919 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000920 S = S->getParent();
921
922 // Find the last declaration in this scope (with the same
923 // name, naturally).
924 IdentifierResolver::iterator LastI = I;
925 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000926 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000927 break;
928 }
929
930 return LookupResult::CreateLookupResult(Context, I, LastI);
931 }
932
933 // We have a single lookup result.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000934 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000935 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000936 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000937 // Perform C++ unqualified name lookup.
938 std::pair<bool, LookupResult> MaybeResult =
939 CppLookupName(S, Name, NameKind, RedeclarationOnly);
940 if (MaybeResult.first)
941 return MaybeResult.second;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000942 }
943
944 // If we didn't find a use of this identifier, and if the identifier
945 // corresponds to a compiler builtin, create the decl object for the builtin
946 // now, injecting it into translation unit scope, and return it.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000947 if (NameKind == LookupOrdinaryName ||
948 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000949 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000950 if (II && AllowBuiltinCreation) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000951 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor3e41d602009-02-13 23:20:09 +0000952 if (unsigned BuiltinID = II->getBuiltinID()) {
953 // In C++, we don't have any predefined library functions like
954 // 'malloc'. Instead, we'll just error.
955 if (getLangOptions().CPlusPlus &&
956 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
957 return LookupResult::CreateLookupResult(Context, 0);
958
Douglas Gregor69d993a2009-01-17 01:13:24 +0000959 return LookupResult::CreateLookupResult(Context,
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000960 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000961 S, RedeclarationOnly, Loc));
962 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000963 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000964 }
Douglas Gregor69d993a2009-01-17 01:13:24 +0000965 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000966}
967
968/// @brief Perform qualified name lookup into a given context.
969///
970/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
971/// names when the context of those names is explicit specified, e.g.,
972/// "std::vector" or "x->member".
973///
974/// Different lookup criteria can find different names. For example, a
975/// particular scope can have both a struct and a function of the same
976/// name, and each can be found by certain lookup criteria. For more
977/// information about lookup criteria, see the documentation for the
978/// class LookupCriteria.
979///
980/// @param LookupCtx The context in which qualified name lookup will
981/// search. If the lookup criteria permits, name lookup may also search
982/// in the parent contexts or (for C++ classes) base classes.
983///
984/// @param Name The name of the entity that we are searching for.
985///
986/// @param Criteria The criteria that this routine will use to
987/// determine which names are visible and which names will be
988/// found. Note that name lookup will find a name that is visible by
989/// the given criteria, but the entity itself may not be semantically
990/// correct or even the kind of entity expected based on the
991/// lookup. For example, searching for a nested-name-specifier name
992/// might result in an EnumDecl, which is visible but is not permitted
993/// as a nested-name-specifier in C++03.
994///
995/// @returns The result of name lookup, which includes zero or more
996/// declarations and possibly additional information used to diagnose
997/// ambiguities.
998Sema::LookupResult
999Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001000 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001001 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1002
Douglas Gregor69d993a2009-01-17 01:13:24 +00001003 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001004
1005 // If we're performing qualified name lookup (e.g., lookup into a
1006 // struct), find fields as part of ordinary name lookup.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001007 unsigned IDNS
1008 = getIdentifierNamespacesFromLookupNameKind(NameKind,
1009 getLangOptions().CPlusPlus);
1010 if (NameKind == LookupOrdinaryName)
1011 IDNS |= Decl::IDNS_Member;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001012
1013 // Perform qualified name lookup into the LookupCtx.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001014 DeclContext::lookup_iterator I, E;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001015 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001016 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001017 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001018
Douglas Gregor7176fff2009-01-15 00:26:24 +00001019 // If this isn't a C++ class or we aren't allowed to look into base
1020 // classes, we're done.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001021 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001022 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001023
1024 // Perform lookup into our base classes.
1025 BasePaths Paths;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001026 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor7176fff2009-01-15 00:26:24 +00001027
1028 // Look for this member in our base classes
1029 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001030 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001031 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001032
1033 // C++ [class.member.lookup]p2:
1034 // [...] If the resulting set of declarations are not all from
1035 // sub-objects of the same type, or the set has a nonstatic member
1036 // and includes members from distinct sub-objects, there is an
1037 // ambiguity and the program is ill-formed. Otherwise that set is
1038 // the result of the lookup.
1039 // FIXME: support using declarations!
1040 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001041 int SubobjectNumber = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001042 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1043 Path != PathEnd; ++Path) {
1044 const BasePathElement &PathElement = Path->back();
1045
1046 // Determine whether we're looking at a distinct sub-object or not.
1047 if (SubobjectType.isNull()) {
1048 // This is the first subobject we've looked at. Record it's type.
1049 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1050 SubobjectNumber = PathElement.SubobjectNumber;
1051 } else if (SubobjectType
1052 != Context.getCanonicalType(PathElement.Base->getType())) {
1053 // We found members of the given name in two subobjects of
1054 // different types. This lookup is ambiguous.
1055 BasePaths *PathsOnHeap = new BasePaths;
1056 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +00001057 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001058 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1059 // We have a different subobject of the same type.
1060
1061 // C++ [class.member.lookup]p5:
1062 // A static member, a nested type or an enumerator defined in
1063 // a base class T can unambiguously be found even if an object
1064 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001065 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001066 if (isa<VarDecl>(FirstDecl) ||
1067 isa<TypeDecl>(FirstDecl) ||
1068 isa<EnumConstantDecl>(FirstDecl))
1069 continue;
1070
1071 if (isa<CXXMethodDecl>(FirstDecl)) {
1072 // Determine whether all of the methods are static.
1073 bool AllMethodsAreStatic = true;
1074 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1075 Func != Path->Decls.second; ++Func) {
1076 if (!isa<CXXMethodDecl>(*Func)) {
1077 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1078 break;
1079 }
1080
1081 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1082 AllMethodsAreStatic = false;
1083 break;
1084 }
1085 }
1086
1087 if (AllMethodsAreStatic)
1088 continue;
1089 }
1090
1091 // We have found a nonstatic member name in multiple, distinct
1092 // subobjects. Name lookup is ambiguous.
1093 BasePaths *PathsOnHeap = new BasePaths;
1094 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +00001095 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001096 }
1097 }
1098
1099 // Lookup in a base class succeeded; return these results.
1100
1101 // If we found a function declaration, return an overload set.
Douglas Gregore53060f2009-06-25 22:08:12 +00001102 if ((*Paths.front().Decls.first)->isFunctionOrFunctionTemplate())
Douglas Gregor69d993a2009-01-17 01:13:24 +00001103 return LookupResult::CreateLookupResult(Context,
Douglas Gregor7176fff2009-01-15 00:26:24 +00001104 Paths.front().Decls.first, Paths.front().Decls.second);
1105
1106 // We found a non-function declaration; return a single declaration.
Douglas Gregor69d993a2009-01-17 01:13:24 +00001107 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001108}
1109
1110/// @brief Performs name lookup for a name that was parsed in the
1111/// source code, and may contain a C++ scope specifier.
1112///
1113/// This routine is a convenience routine meant to be called from
1114/// contexts that receive a name and an optional C++ scope specifier
1115/// (e.g., "N::M::x"). It will then perform either qualified or
1116/// unqualified name lookup (with LookupQualifiedName or LookupName,
1117/// respectively) on the given name and return those results.
1118///
1119/// @param S The scope from which unqualified name lookup will
1120/// begin.
1121///
1122/// @param SS An optional C++ scope-specified, e.g., "::N::M".
1123///
1124/// @param Name The name of the entity that name lookup will
1125/// search for.
1126///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001127/// @param Loc If provided, the source location where we're performing
1128/// name lookup. At present, this is only used to produce diagnostics when
1129/// C library functions (like "malloc") are implicitly declared.
1130///
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001131/// @returns The result of qualified or unqualified name lookup.
1132Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001133Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1134 DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001135 bool RedeclarationOnly, bool AllowBuiltinCreation,
1136 SourceLocation Loc) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00001137 if (SS && (SS->isSet() || SS->isInvalid())) {
1138 // If the scope specifier is invalid, don't even look for
1139 // anything.
1140 if (SS->isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001141 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001142
Douglas Gregor42af25f2009-05-11 19:58:34 +00001143 assert(!isUnknownSpecialization(*SS) && "Can't lookup dependent types");
1144
1145 if (isDependentScopeSpecifier(*SS)) {
1146 // Determine whether we are looking into the current
1147 // instantiation.
1148 NestedNameSpecifier *NNS
1149 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1150 CXXRecordDecl *Current = getCurrentInstantiationOf(NNS);
1151 assert(Current && "Bad dependent scope specifier");
1152
1153 // We nested name specifier refers to the current instantiation,
1154 // so now we will look for a member of the current instantiation
1155 // (C++0x [temp.dep.type]).
1156 unsigned IDNS = getIdentifierNamespacesFromLookupNameKind(NameKind, true);
1157 DeclContext::lookup_iterator I, E;
1158 for (llvm::tie(I, E) = Current->lookup(Context, Name); I != E; ++I)
1159 if (isAcceptableLookupResult(*I, NameKind, IDNS))
1160 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001161 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001162
1163 if (RequireCompleteDeclContext(*SS))
1164 return LookupResult::CreateLookupResult(Context, 0);
1165
1166 return LookupQualifiedName(computeDeclContext(*SS),
1167 Name, NameKind, RedeclarationOnly);
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001168 }
1169
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001170 LookupResult result(LookupName(S, Name, NameKind, RedeclarationOnly,
1171 AllowBuiltinCreation, Loc));
1172
1173 return(result);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001174}
1175
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001176
Douglas Gregor7176fff2009-01-15 00:26:24 +00001177/// @brief Produce a diagnostic describing the ambiguity that resulted
1178/// from name lookup.
1179///
1180/// @param Result The ambiguous name lookup result.
1181///
1182/// @param Name The name of the entity that name lookup was
1183/// searching for.
1184///
1185/// @param NameLoc The location of the name within the source code.
1186///
1187/// @param LookupRange A source range that provides more
1188/// source-location information concerning the lookup itself. For
1189/// example, this range might highlight a nested-name-specifier that
1190/// precedes the name.
1191///
1192/// @returns true
1193bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1194 SourceLocation NameLoc,
1195 SourceRange LookupRange) {
1196 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1197
Douglas Gregor31a19b62009-04-01 21:51:26 +00001198 if (BasePaths *Paths = Result.getBasePaths()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001199 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1200 QualType SubobjectType = Paths->front().back().Base->getType();
1201 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1202 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1203 << LookupRange;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001204
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001205 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
Douglas Gregor31a19b62009-04-01 21:51:26 +00001206 while (isa<CXXMethodDecl>(*Found) &&
1207 cast<CXXMethodDecl>(*Found)->isStatic())
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001208 ++Found;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001209
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001210 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1211
Douglas Gregor31a19b62009-04-01 21:51:26 +00001212 Result.Destroy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001213 return true;
1214 }
1215
1216 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1217 "Unhandled form of name lookup ambiguity");
1218
1219 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1220 << Name << LookupRange;
1221
1222 std::set<Decl *> DeclsPrinted;
1223 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1224 Path != PathEnd; ++Path) {
1225 Decl *D = *Path->Decls.first;
1226 if (DeclsPrinted.insert(D).second)
1227 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1228 }
1229
Douglas Gregor31a19b62009-04-01 21:51:26 +00001230 Result.Destroy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001231 return true;
1232 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001233 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1234
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001235 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
Douglas Gregor31a19b62009-04-01 21:51:26 +00001236 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001237
Chris Lattner48458d22009-02-03 21:29:32 +00001238 for (; DI != DEnd; ++DI)
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001239 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001240
Douglas Gregor31a19b62009-04-01 21:51:26 +00001241 Result.Destroy();
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001242 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001243 }
1244
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001245 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregor69d993a2009-01-17 01:13:24 +00001246
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001247 // We can't reach here.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001248 return true;
1249}
Douglas Gregorfa047642009-02-04 00:32:51 +00001250
1251// \brief Add the associated classes and namespaces for
1252// argument-dependent lookup with an argument of class type
1253// (C++ [basic.lookup.koenig]p2).
1254static void
1255addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1256 ASTContext &Context,
1257 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001258 Sema::AssociatedClassSet &AssociatedClasses,
1259 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001260 // C++ [basic.lookup.koenig]p2:
1261 // [...]
1262 // -- If T is a class type (including unions), its associated
1263 // classes are: the class itself; the class of which it is a
1264 // member, if any; and its direct and indirect base
1265 // classes. Its associated namespaces are the namespaces in
1266 // which its associated classes are defined.
1267
1268 // Add the class of which it is a member, if any.
1269 DeclContext *Ctx = Class->getDeclContext();
1270 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1271 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001272 // Add the associated namespace for this class.
1273 while (Ctx->isRecord())
1274 Ctx = Ctx->getParent();
1275 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1276 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001277 else if (Ctx->isTranslationUnit())
1278 GlobalScope = true;
1279
Douglas Gregorfa047642009-02-04 00:32:51 +00001280 // Add the class itself. If we've already seen this class, we don't
1281 // need to visit base classes.
1282 if (!AssociatedClasses.insert(Class))
1283 return;
1284
1285 // FIXME: Handle class template specializations
1286
1287 // Add direct and indirect base classes along with their associated
1288 // namespaces.
1289 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1290 Bases.push_back(Class);
1291 while (!Bases.empty()) {
1292 // Pop this class off the stack.
1293 Class = Bases.back();
1294 Bases.pop_back();
1295
1296 // Visit the base classes.
1297 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1298 BaseEnd = Class->bases_end();
1299 Base != BaseEnd; ++Base) {
1300 const RecordType *BaseType = Base->getType()->getAsRecordType();
1301 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1302 if (AssociatedClasses.insert(BaseDecl)) {
1303 // Find the associated namespace for this base class.
1304 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1305 while (BaseCtx->isRecord())
1306 BaseCtx = BaseCtx->getParent();
1307 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1308 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001309 else if (BaseCtx->isTranslationUnit())
1310 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001311
1312 // Make sure we visit the bases of this base class.
1313 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1314 Bases.push_back(BaseDecl);
1315 }
1316 }
1317 }
1318}
1319
1320// \brief Add the associated classes and namespaces for
1321// argument-dependent lookup with an argument of type T
1322// (C++ [basic.lookup.koenig]p2).
1323static void
1324addAssociatedClassesAndNamespaces(QualType T,
1325 ASTContext &Context,
1326 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001327 Sema::AssociatedClassSet &AssociatedClasses,
1328 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001329 // C++ [basic.lookup.koenig]p2:
1330 //
1331 // For each argument type T in the function call, there is a set
1332 // of zero or more associated namespaces and a set of zero or more
1333 // associated classes to be considered. The sets of namespaces and
1334 // classes is determined entirely by the types of the function
1335 // arguments (and the namespace of any template template
1336 // argument). Typedef names and using-declarations used to specify
1337 // the types do not contribute to this set. The sets of namespaces
1338 // and classes are determined in the following way:
1339 T = Context.getCanonicalType(T).getUnqualifiedType();
1340
1341 // -- If T is a pointer to U or an array of U, its associated
1342 // namespaces and classes are those associated with U.
1343 //
1344 // We handle this by unwrapping pointer and array types immediately,
1345 // to avoid unnecessary recursion.
1346 while (true) {
1347 if (const PointerType *Ptr = T->getAsPointerType())
1348 T = Ptr->getPointeeType();
1349 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1350 T = Ptr->getElementType();
1351 else
1352 break;
1353 }
1354
1355 // -- If T is a fundamental type, its associated sets of
1356 // namespaces and classes are both empty.
1357 if (T->getAsBuiltinType())
1358 return;
1359
1360 // -- If T is a class type (including unions), its associated
1361 // classes are: the class itself; the class of which it is a
1362 // member, if any; and its direct and indirect base
1363 // classes. Its associated namespaces are the namespaces in
1364 // which its associated classes are defined.
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001365 if (const RecordType *ClassType = T->getAsRecordType())
1366 if (CXXRecordDecl *ClassDecl
1367 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1368 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1369 AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001370 AssociatedClasses,
1371 GlobalScope);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001372 return;
1373 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001374
1375 // -- If T is an enumeration type, its associated namespace is
1376 // the namespace in which it is defined. If it is class
1377 // member, its associated class is the member’s class; else
1378 // it has no associated class.
1379 if (const EnumType *EnumT = T->getAsEnumType()) {
1380 EnumDecl *Enum = EnumT->getDecl();
1381
1382 DeclContext *Ctx = Enum->getDeclContext();
1383 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1384 AssociatedClasses.insert(EnclosingClass);
1385
1386 // Add the associated namespace for this class.
1387 while (Ctx->isRecord())
1388 Ctx = Ctx->getParent();
1389 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1390 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001391 else if (Ctx->isTranslationUnit())
1392 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001393
1394 return;
1395 }
1396
1397 // -- If T is a function type, its associated namespaces and
1398 // classes are those associated with the function parameter
1399 // types and those associated with the return type.
1400 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1401 // Return type
1402 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1403 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001404 AssociatedNamespaces, AssociatedClasses,
1405 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001406
Douglas Gregor72564e72009-02-26 23:50:07 +00001407 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001408 if (!Proto)
1409 return;
1410
1411 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001412 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001413 ArgEnd = Proto->arg_type_end();
1414 Arg != ArgEnd; ++Arg)
1415 addAssociatedClassesAndNamespaces(*Arg, Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001416 AssociatedNamespaces, AssociatedClasses,
1417 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001418
1419 return;
1420 }
1421
1422 // -- If T is a pointer to a member function of a class X, its
1423 // associated namespaces and classes are those associated
1424 // with the function parameter types and return type,
1425 // together with those associated with X.
1426 //
1427 // -- If T is a pointer to a data member of class X, its
1428 // associated namespaces and classes are those associated
1429 // with the member type together with those associated with
1430 // X.
1431 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1432 // Handle the type that the pointer to member points to.
1433 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1434 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001435 AssociatedNamespaces, AssociatedClasses,
1436 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001437
1438 // Handle the class type into which this points.
1439 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1440 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1441 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001442 AssociatedNamespaces, AssociatedClasses,
1443 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001444
1445 return;
1446 }
1447
1448 // FIXME: What about block pointers?
1449 // FIXME: What about Objective-C message sends?
1450}
1451
1452/// \brief Find the associated classes and namespaces for
1453/// argument-dependent lookup for a call with the given set of
1454/// arguments.
1455///
1456/// This routine computes the sets of associated classes and associated
1457/// namespaces searched by argument-dependent lookup
1458/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1459void
1460Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1461 AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001462 AssociatedClassSet &AssociatedClasses,
1463 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001464 AssociatedNamespaces.clear();
1465 AssociatedClasses.clear();
1466
1467 // C++ [basic.lookup.koenig]p2:
1468 // For each argument type T in the function call, there is a set
1469 // of zero or more associated namespaces and a set of zero or more
1470 // associated classes to be considered. The sets of namespaces and
1471 // classes is determined entirely by the types of the function
1472 // arguments (and the namespace of any template template
1473 // argument).
1474 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1475 Expr *Arg = Args[ArgIdx];
1476
1477 if (Arg->getType() != Context.OverloadTy) {
1478 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001479 AssociatedNamespaces, AssociatedClasses,
1480 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001481 continue;
1482 }
1483
1484 // [...] In addition, if the argument is the name or address of a
1485 // set of overloaded functions and/or function templates, its
1486 // associated classes and namespaces are the union of those
1487 // associated with each of the members of the set: the namespace
1488 // in which the function or function template is defined and the
1489 // classes and namespaces associated with its (non-dependent)
1490 // parameter types and return type.
1491 DeclRefExpr *DRE = 0;
1492 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1493 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1494 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1495 } else
1496 DRE = dyn_cast<DeclRefExpr>(Arg);
1497 if (!DRE)
1498 continue;
1499
1500 OverloadedFunctionDecl *Ovl
1501 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1502 if (!Ovl)
1503 continue;
1504
1505 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1506 FuncEnd = Ovl->function_end();
1507 Func != FuncEnd; ++Func) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001508 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func);
1509 if (!FDecl)
1510 FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001511
1512 // Add the namespace in which this function was defined. Note
1513 // that, if this is a member function, we do *not* consider the
1514 // enclosing namespace of its class.
1515 DeclContext *Ctx = FDecl->getDeclContext();
1516 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1517 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001518 else if (Ctx->isTranslationUnit())
1519 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001520
1521 // Add the classes and namespaces associated with the parameter
1522 // types and return type of this function.
1523 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001524 AssociatedNamespaces, AssociatedClasses,
1525 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001526 }
1527 }
1528}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001529
1530/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1531/// an acceptable non-member overloaded operator for a call whose
1532/// arguments have types T1 (and, if non-empty, T2). This routine
1533/// implements the check in C++ [over.match.oper]p3b2 concerning
1534/// enumeration types.
1535static bool
1536IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1537 QualType T1, QualType T2,
1538 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001539 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1540 return true;
1541
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001542 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1543 return true;
1544
1545 const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1546 if (Proto->getNumArgs() < 1)
1547 return false;
1548
1549 if (T1->isEnumeralType()) {
1550 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1551 if (Context.getCanonicalType(T1).getUnqualifiedType()
1552 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1553 return true;
1554 }
1555
1556 if (Proto->getNumArgs() < 2)
1557 return false;
1558
1559 if (!T2.isNull() && T2->isEnumeralType()) {
1560 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1561 if (Context.getCanonicalType(T2).getUnqualifiedType()
1562 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1563 return true;
1564 }
1565
1566 return false;
1567}
1568
Douglas Gregor6e378de2009-04-23 23:18:26 +00001569/// \brief Find the protocol with the given name, if any.
1570ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001571 Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl();
Douglas Gregor6e378de2009-04-23 23:18:26 +00001572 return cast_or_null<ObjCProtocolDecl>(D);
1573}
1574
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001575/// \brief Find the Objective-C implementation with the given name, if
1576/// any.
1577ObjCImplementationDecl *Sema::LookupObjCImplementation(IdentifierInfo *II) {
1578 Decl *D = LookupName(TUScope, II, LookupObjCImplementationName).getAsDecl();
1579 return cast_or_null<ObjCImplementationDecl>(D);
1580}
1581
1582/// \brief Find the Objective-C category implementation with the given
1583/// name, if any.
1584ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
1585 Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl();
1586 return cast_or_null<ObjCCategoryImplDecl>(D);
1587}
1588
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001589void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1590 QualType T1, QualType T2,
1591 FunctionSet &Functions) {
1592 // C++ [over.match.oper]p3:
1593 // -- The set of non-member candidates is the result of the
1594 // unqualified lookup of operator@ in the context of the
1595 // expression according to the usual rules for name lookup in
1596 // unqualified function calls (3.4.2) except that all member
1597 // functions are ignored. However, if no operand has a class
1598 // type, only those non-member functions in the lookup set
1599 // that have a first parameter of type T1 or “reference to
1600 // (possibly cv-qualified) T1”, when T1 is an enumeration
1601 // type, or (if there is a right operand) a second parameter
1602 // of type T2 or “reference to (possibly cv-qualified) T2”,
1603 // when T2 is an enumeration type, are candidate functions.
1604 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1605 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1606
1607 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1608
1609 if (!Operators)
1610 return;
1611
1612 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1613 Op != OpEnd; ++Op) {
1614 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
1615 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1616 Functions.insert(FD); // FIXME: canonical FD
1617 }
1618}
1619
1620void Sema::ArgumentDependentLookup(DeclarationName Name,
1621 Expr **Args, unsigned NumArgs,
1622 FunctionSet &Functions) {
1623 // Find all of the associated namespaces and classes based on the
1624 // arguments we have.
1625 AssociatedNamespaceSet AssociatedNamespaces;
1626 AssociatedClassSet AssociatedClasses;
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001627 bool GlobalScope = false;
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001628 FindAssociatedClassesAndNamespaces(Args, NumArgs,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001629 AssociatedNamespaces, AssociatedClasses,
1630 GlobalScope);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001631
1632 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001633 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1634 // and let Y be the lookup set produced by argument dependent
1635 // lookup (defined as follows). If X contains [...] then Y is
1636 // empty. Otherwise Y is the set of declarations found in the
1637 // namespaces associated with the argument types as described
1638 // below. The set of declarations found by the lookup of the name
1639 // is the union of X and Y.
1640 //
1641 // Here, we compute Y and add its members to the overloaded
1642 // candidate set.
1643 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1644 NSEnd = AssociatedNamespaces.end();
1645 NS != NSEnd; ++NS) {
1646 // When considering an associated namespace, the lookup is the
1647 // same as the lookup performed when the associated namespace is
1648 // used as a qualifier (3.4.3.2) except that:
1649 //
1650 // -- Any using-directives in the associated namespace are
1651 // ignored.
1652 //
1653 // -- FIXME: Any namespace-scope friend functions declared in
1654 // associated classes are visible within their respective
1655 // namespaces even if they are not visible during an ordinary
1656 // lookup (11.4).
1657 DeclContext::lookup_iterator I, E;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001658 for (llvm::tie(I, E) = (*NS)->lookup(Context, Name); I != E; ++I) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001659 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1660 if (!Func)
1661 break;
1662
1663 Functions.insert(Func);
1664 }
1665 }
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001666
1667 if (GlobalScope) {
1668 DeclContext::lookup_iterator I, E;
1669 for (llvm::tie(I, E)
1670 = Context.getTranslationUnitDecl()->lookup(Context, Name);
1671 I != E; ++I) {
1672 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1673 if (!Func)
1674 break;
1675
1676 Functions.insert(Func);
1677 }
1678 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001679}